repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/Test2/Workspaces/SymbolDescriptionServiceTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.FindSymbols Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.LanguageServices Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces <[UseExportProvider]> Public Class SymbolDescriptionServiceTests Private Shared Async Function TestAsync(languageServiceProvider As HostLanguageServices, workspace As TestWorkspace, expectedDescription As String) As Task Dim solution = workspace.CurrentSolution Dim cursorDocument = workspace.Documents.First(Function(d) d.CursorPosition.HasValue) Dim cursorPosition = cursorDocument.CursorPosition.Value Dim cursorBuffer = cursorDocument.GetTextBuffer() Dim document = workspace.CurrentSolution.GetDocument(cursorDocument.Id) Dim semanticModel = Await document.GetSemanticModelAsync() Dim symbol = Await SymbolFinder.FindSymbolAtPositionAsync(document, cursorPosition) Dim symbolDescriptionService = languageServiceProvider.GetService(Of ISymbolDisplayService)() Dim actualDescription = Await symbolDescriptionService.ToDescriptionStringAsync(workspace, semanticModel, cursorPosition, symbol) Assert.Equal(expectedDescription, actualDescription) End Function Private Shared Function StringFromLines(ParamArray lines As String()) As String Return String.Join(Environment.NewLine, lines) End Function Private Shared Async Function TestCSharpAsync(workspaceDefinition As XElement, expectedDescription As String) As Tasks.Task Using workspace = TestWorkspace.Create(workspaceDefinition) Await TestAsync(GetLanguageServiceProvider(workspace, LanguageNames.CSharp), workspace, expectedDescription) End Using End Function Private Shared Async Function TestBasicAsync(workspaceDefinition As XElement, expectedDescription As String) As Tasks.Task Using workspace = TestWorkspace.Create(workspaceDefinition) Await TestAsync(GetLanguageServiceProvider(workspace, LanguageNames.VisualBasic), workspace, expectedDescription) End Using End Function Private Shared Function GetLanguageServiceProvider(workspace As TestWorkspace, language As String) As HostLanguageServices Return workspace.Services.GetLanguageServices(language) End Function Private Shared Function WrapCodeInWorkspace(ParamArray lines As String()) As XElement Dim part1 = "<Workspace> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document>" Dim part2 = "</Document></Project></Workspace>" Dim code = StringFromLines(lines) Dim workspace = String.Concat(part1, code, part2) WrapCodeInWorkspace = XElement.Parse(workspace) End Function #Region "CSharp SymbolDescription Tests" <Fact> Public Async Function TestCSharpDynamic() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { void M() { dyn$$amic d; } } </Document> </Project> </Workspace> Await TestCSharpAsync(workspace, StringFromLines("dynamic", FeaturesResources.Represents_an_object_whose_operations_will_be_resolved_at_runtime)) End Function <WorkItem(543912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543912")> <Fact> Public Async Function TestCSharpLocalConstant() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { void Method() { const int $$x = 2 } } </Document> </Project> </Workspace> Await TestCSharpAsync(workspace, $"({FeaturesResources.local_constant}) int x = 2") End Function <Fact> Public Async Function TestCSharpStaticField() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Foo { private static int $$x; } </Document> </Project> </Workspace> Await TestCSharpAsync(workspace, $"({FeaturesResources.field}) static int Foo.x") End Function <Fact> Public Async Function TestCSharpReadOnlyField() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Foo { private readonly int $$x; } </Document> </Project> </Workspace> Await TestCSharpAsync(workspace, $"({FeaturesResources.field}) readonly int Foo.x") End Function <Fact> Public Async Function TestCSharpVolatileField() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Foo { private volatile int $$x; } </Document> </Project> </Workspace> Await TestCSharpAsync(workspace, $"({FeaturesResources.field}) volatile int Foo.x") End Function <Fact> Public Async Function TestCSharpStaticReadOnlyField() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Foo { private static readonly int $$x; } </Document> </Project> </Workspace> Await TestCSharpAsync(workspace, $"({FeaturesResources.field}) static readonly int Foo.x") End Function <Fact> Public Async Function TestCSharpStaticVolatileField() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Foo { private static volatile int $$x; } </Document> </Project> </Workspace> Await TestCSharpAsync(workspace, $"({FeaturesResources.field}) static volatile int Foo.x") End Function <Fact> <WorkItem(33049, "https://github.com/dotnet/roslyn/issues/33049")> Public Async Function TestCSharpDefaultParameter() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Threading; class Goo { void Method(CancellationToken cancellationToken = default(CancellationToken)) { $$Method(CancellationToken.None); } } </Document> </Project> </Workspace> Await TestCSharpAsync(workspace, $"void Goo.Method([CancellationToken cancellationToken = default])") End Function #End Region #Region "Basic SymbolDescription Tests" <Fact> Public Async Function TestNamedTypeKindClass() As Task Dim workspace = WrapCodeInWorkspace("class Program", "Dim p as Prog$$ram", "End class") Await TestBasicAsync(workspace, "Class Program") End Function ''' <summary> ''' Design Change from Dev10. Notice that we now show the type information for T ''' C# / VB Quick Info consistency ''' </summary> ''' <remarks></remarks> <Fact> Public Async Function TestGenericClass() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class Program Dim p as New System.Collections.Generic.Lis$$t(Of String) End class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, StringFromLines("Sub List(Of String).New()")) End Function <Fact> Public Async Function TestGenericClassFromSource() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Namespace TestNamespace Public Class Outer(Of T) End Class Module Test Dim x As New O$$uter(Of Integer) End Module End Namespace </Document> </Project> </Workspace> Await TestBasicAsync(workspace, StringFromLines("Sub Outer(Of Integer).New()")) End Function <Fact> Public Async Function TestClassNestedWithinAGenericClass() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Outer(Of T) Public Class Inner Public Sub F(x As T) End Sub End Class End Class Module Test Sub Main() Dim x As New Outer(Of Integer).In$$ner() x.F(4) End Sub End Module </Document> </Project> </Workspace> Await TestBasicAsync(workspace, StringFromLines("Sub Outer(Of Integer).Inner.New()")) End Function <Fact> Public Async Function TestTypeParameter() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Goo(Of T) Dim x as T$$ End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"T {FeaturesResources.in_} Goo(Of T)") End Function <Fact> Public Async Function TestTypeParameterFromNestedClass() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Outer(Of T) Public Class Inner Public Sub F(x As T$$) End Sub End Class End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"T {FeaturesResources.in_} Outer(Of T)") End Function <Fact> Public Async Function TestShadowedTypeParameter() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Outer(Of T) Public Class Inner Public Sub F(x As T$$) End Sub End Class End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"T {FeaturesResources.in_} Outer(Of T)") End Function <Fact> Public Async Function TestNullableOfInt() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Public Class Goo Dim x as Nullab$$le(Of Integer) End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, StringFromLines("Structure System.Nullable(Of T As Structure)", String.Empty, $"T {FeaturesResources.is_} Integer")) End Function <Fact> Public Async Function TestDictionaryOfIntAndString() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System.Collections.Generic class Program Dim p as New Dictio$$nary(Of Integer, String) End class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, StringFromLines("Sub Dictionary(Of Integer, String).New()")) End Function <Fact> Public Async Function TestNamedTypeKindStructure() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Structure Program Dim p as Prog$$ram End Structure </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Structure Program") End Function <Fact> Public Async Function TestNamedTypeKindStructureBuiltIn() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class Program Dim p as Int$$eger End class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Structure System.Int32") End Function <Fact> Public Async Function TestNamedTypeKindEnum() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Enum Program End Enum Module M1 Sub Main(args As String()) Dim p as Prog$$ram End Sub End Module </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Enum Program") End Function <Fact> Public Async Function TestNamedTypeKindDelegate() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Delegate Sub DelegateType() Module M1 Event AnEvent As Delega$$teType Sub Main(args As String()) End Sub End Module </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Delegate Sub DelegateType()") End Function <Fact> Public Async Function TestNamedTypeKindInterface() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Interface Goo End Interface Module M1 Sub Main(args As String()) Dim p as Goo$$ End Sub End Module </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Interface Goo") End Function <Fact> Public Async Function TestNamedTypeKindModule() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo sub Method() $$M1.M() End sub End Class Module M1 public sub M() End sub End Module </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Module M1") End Function <Fact> Public Async Function TestNamespace() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo sub Method() Sys$$tem.Console.Write(5) End sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Namespace System") End Function <Fact> Public Async Function TestNamespace2() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System.Collections.Gene$$ric </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Namespace System.Collections.Generic") End Function <Fact> Public Async Function TestField() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo private field as Integer sub Method() fie$$ld = 5 End sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"({FeaturesResources.field}) Goo.field As Integer") End Function <Fact> Public Async Function TestSharedField() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo private Shared field as Integer sub Method() fie$$ld = 5 End sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"({FeaturesResources.field}) Shared Goo.field As Integer") End Function <Fact> Public Async Function TestReadOnlyField() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo private ReadOnly field as Integer sub Method() fie$$ld = 5 End sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"({FeaturesResources.field}) ReadOnly Goo.field As Integer") End Function <Fact> Public Async Function TestSharedReadOnlyField() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo private Shared ReadOnly field as Integer sub Method() fie$$ld = 5 End sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"({FeaturesResources.field}) Shared ReadOnly Goo.field As Integer") End Function <Fact> Public Async Function TestLocal() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo sub Method() Dim x as String x$$ = "Hello" End sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"({FeaturesResources.local_variable}) x As String") End Function <WorkItem(538732, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538732")> <Fact> Public Async Function TestMethod() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub Method() Fu$$n() End Sub Function Fun() As Integer Return 1 End Function End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Function Goo.Fun() As Integer") End Function ''' <summary> ''' This is a design change from Dev10. Notice that modifiers "public shared sub" are absent. ''' VB / C# Quick Info Consistency ''' </summary> ''' <remarks></remarks> <WorkItem(538732, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538732")> <Fact> Public Async Function TestPEMethod() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub Method() System.Console.Writ$$e(5) End Sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Sub Console.Write(value As Integer)") End Function ''' <summary> ''' This is a design change from Dev10. Showing what we already know is kinda useless. ''' This is what C# does. We are modifying VB to follow this model. ''' </summary> ''' <remarks></remarks> <Fact> Public Async Function TestFormalParameter() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub Method() End Sub Function Fun(x$$ As String) As Integer Return 1 End Function End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"({FeaturesResources.parameter}) x As String") End Function <Fact> Public Async Function TestOptionalParameter() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub Method(x As Short, Optional y As Integer = 10) End Sub Sub Test Met$$hod(1, 2) End Sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Sub Goo.Method(x As Short, [y As Integer = 10])") End Function <Fact> Public Async Function TestOverloadedMethod() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Overloads Sub Method(x As Integer) End Sub Overloads Sub Method(x As String) End Sub Sub Test() Meth$$od("str") End Sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Sub Goo.Method(x As String)") End Function <Fact> Public Async Function TestOverloadedMethods() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Overloads Sub Method(x As Integer) End Sub Overloads Sub Method(x As String) End Sub Overloads Sub Method(x As Double) End Sub Sub Test() Meth$$od("str") End Sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Sub Goo.Method(x As String)") End Function <WorkItem(527639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527639")> <Fact> Public Async Function TestInterfaceConstraintOnClass() As Task Dim workspace = WrapCodeInWorkspace("Imports System.Collections.Generic", "Class CC(Of T$$ As IEnumerable(Of Integer))", "End Class") Dim expectedDescription = $"T {FeaturesResources.in_} CC(Of T As IEnumerable(Of Integer))" Await TestBasicAsync(workspace, expectedDescription) End Function <WorkItem(527639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527639")> <Fact> Public Async Function TestInterfaceConstraintOnInterface() As Task Dim workspace = WrapCodeInWorkspace("Imports System.Collections.Generic", "Interface IMyInterface(Of T$$ As IEnumerable(Of Integer))", "End Interface") Dim expectedDescription = $"T {FeaturesResources.in_} IMyInterface(Of T As IEnumerable(Of Integer))" Await TestBasicAsync(workspace, expectedDescription) End Function <WorkItem(527639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527639")> <Fact> Public Async Function TestReferenceTypeConstraintOnClass() As Task Dim workspace = WrapCodeInWorkspace("Class CC(Of T$$ As Class)", "End Class") Dim expectedDescription = $"T {FeaturesResources.in_} CC(Of T As Class)" Await TestBasicAsync(workspace, expectedDescription) End Function <WorkItem(527639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527639")> <Fact> Public Async Function TestValueTypeConstraintOnClass() As Task Dim workspace = WrapCodeInWorkspace("Class CC(Of T$$ As Structure)", "End Class") Dim expectedDescription = $"T {FeaturesResources.in_} CC(Of T As Structure)" Await TestBasicAsync(workspace, expectedDescription) End Function <WorkItem(527639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527639")> <Fact> Public Async Function TestValueTypeConstraintOnStructure() As Task Dim workspace = WrapCodeInWorkspace("Structure S(Of T$$ As Class)", "End Structure") Dim expectedDescription = $"T {FeaturesResources.in_} S(Of T As Class)" Await TestBasicAsync(workspace, expectedDescription) End Function <WorkItem(527639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527639")> <Fact> Public Async Function TestMultipleConstraintsOnClass() As Task Dim workspace = WrapCodeInWorkspace("Public Class CC(Of T$$ As {IComparable, IDisposable, Class, New})", "End Class") Dim expectedDescription = $"T {FeaturesResources.in_} CC(Of T As {{Class, IComparable, IDisposable, New}})" Await TestBasicAsync(workspace, expectedDescription) End Function ''' TO DO: Add test for Ref Arg <Fact> Public Async Function TestOutArguments() As Task Dim workspace = WrapCodeInWorkspace("Imports System.Collections.Generic", "Class CC(Of T As IEnum$$erable(Of Integer))", "End Class") Dim expectedDescription = StringFromLines("Interface System.Collections.Generic.IEnumerable(Of Out T)", String.Empty, $"T {FeaturesResources.is_} Integer") Await TestBasicAsync(workspace, expectedDescription) End Function <WorkItem(527655, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527655")> <Fact> Public Async Function TestMinimalDisplayName() As Task Dim workspace = WrapCodeInWorkspace("Imports System", "Imports System.Collections.Generic", "Class CC(Of T As IEnu$$merable(Of IEnumerable(of Int32)))", "End Class") Dim expectedDescription = StringFromLines("Interface System.Collections.Generic.IEnumerable(Of Out T)", String.Empty, $"T {FeaturesResources.is_} IEnumerable(Of Integer)") Await TestBasicAsync(workspace, expectedDescription) End Function <Fact> Public Async Function TestOverridableMethod() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class A Public Overridable Sub G() End Sub End Class Class B Inherits A Public Overrides Sub G() End Sub End Class Class C Sub Test() Dim x As A x = new A() x.G$$() End Sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Sub A.G()") End Function <Fact> Public Async Function TestOverriddenMethod2() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class A Public Overridable Sub G() End Sub End Class Class B Inherits A Public Overrides Sub G() End Sub End Class Class C Sub Test() Dim x As A x = new B() x.G$$() End Sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Sub A.G()") End Function <Fact> Public Async Function TestGenericMethod() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Outer(Of T) Public Class Inner Public Sub F(x As T) End Sub End Class End Class Module Test Sub Main() Dim x As New Outer(Of Integer).Inner() x.F$$(4) End Sub End Module </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Sub Outer(Of Integer).Inner.F(x As Integer)") End Function <Fact> Public Async Function TestAutoImplementedProperty() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System.Collections.Generic Class Goo Public Property It$$ems As New List(Of String) From {"M", "T", "W"} End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Property Goo.Items As List(Of String)") End Function <WorkItem(538806, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538806")> <Fact> Public Async Function TestField1() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Dim x As Integer Sub Method() Dim y As Integer $$x = y End Sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"({FeaturesResources.field}) C.x As Integer") End Function <WorkItem(538806, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538806")> <Fact> Public Async Function TestProperty1() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Dim x As Integer Sub Method() Dim y As Integer x = $$y End Sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"({FeaturesResources.local_variable}) y As Integer") End Function <WorkItem(543911, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543911")> <Fact> Public Async Function TestVBLocalConstant() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo sub Method() Const $$b = 2 End sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"({FeaturesResources.local_constant}) b As Integer = 2") End Function #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 System.Threading Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.FindSymbols Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.LanguageServices Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces <[UseExportProvider]> Public Class SymbolDescriptionServiceTests Private Shared Async Function TestAsync(languageServiceProvider As HostLanguageServices, workspace As TestWorkspace, expectedDescription As String) As Task Dim solution = workspace.CurrentSolution Dim cursorDocument = workspace.Documents.First(Function(d) d.CursorPosition.HasValue) Dim cursorPosition = cursorDocument.CursorPosition.Value Dim cursorBuffer = cursorDocument.GetTextBuffer() Dim document = workspace.CurrentSolution.GetDocument(cursorDocument.Id) Dim semanticModel = Await document.GetSemanticModelAsync() Dim symbol = Await SymbolFinder.FindSymbolAtPositionAsync(document, cursorPosition) Dim symbolDescriptionService = languageServiceProvider.GetService(Of ISymbolDisplayService)() Dim actualDescription = Await symbolDescriptionService.ToDescriptionStringAsync(workspace, semanticModel, cursorPosition, symbol) Assert.Equal(expectedDescription, actualDescription) End Function Private Shared Function StringFromLines(ParamArray lines As String()) As String Return String.Join(Environment.NewLine, lines) End Function Private Shared Async Function TestCSharpAsync(workspaceDefinition As XElement, expectedDescription As String) As Tasks.Task Using workspace = TestWorkspace.Create(workspaceDefinition) Await TestAsync(GetLanguageServiceProvider(workspace, LanguageNames.CSharp), workspace, expectedDescription) End Using End Function Private Shared Async Function TestBasicAsync(workspaceDefinition As XElement, expectedDescription As String) As Tasks.Task Using workspace = TestWorkspace.Create(workspaceDefinition) Await TestAsync(GetLanguageServiceProvider(workspace, LanguageNames.VisualBasic), workspace, expectedDescription) End Using End Function Private Shared Function GetLanguageServiceProvider(workspace As TestWorkspace, language As String) As HostLanguageServices Return workspace.Services.GetLanguageServices(language) End Function Private Shared Function WrapCodeInWorkspace(ParamArray lines As String()) As XElement Dim part1 = "<Workspace> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document>" Dim part2 = "</Document></Project></Workspace>" Dim code = StringFromLines(lines) Dim workspace = String.Concat(part1, code, part2) WrapCodeInWorkspace = XElement.Parse(workspace) End Function #Region "CSharp SymbolDescription Tests" <Fact> Public Async Function TestCSharpDynamic() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { void M() { dyn$$amic d; } } </Document> </Project> </Workspace> Await TestCSharpAsync(workspace, StringFromLines("dynamic", FeaturesResources.Represents_an_object_whose_operations_will_be_resolved_at_runtime)) End Function <WorkItem(543912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543912")> <Fact> Public Async Function TestCSharpLocalConstant() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Goo { void Method() { const int $$x = 2 } } </Document> </Project> </Workspace> Await TestCSharpAsync(workspace, $"({FeaturesResources.local_constant}) int x = 2") End Function <Fact> Public Async Function TestCSharpStaticField() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Foo { private static int $$x; } </Document> </Project> </Workspace> Await TestCSharpAsync(workspace, $"({FeaturesResources.field}) static int Foo.x") End Function <Fact> Public Async Function TestCSharpReadOnlyField() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Foo { private readonly int $$x; } </Document> </Project> </Workspace> Await TestCSharpAsync(workspace, $"({FeaturesResources.field}) readonly int Foo.x") End Function <Fact> Public Async Function TestCSharpVolatileField() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Foo { private volatile int $$x; } </Document> </Project> </Workspace> Await TestCSharpAsync(workspace, $"({FeaturesResources.field}) volatile int Foo.x") End Function <Fact> Public Async Function TestCSharpStaticReadOnlyField() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Foo { private static readonly int $$x; } </Document> </Project> </Workspace> Await TestCSharpAsync(workspace, $"({FeaturesResources.field}) static readonly int Foo.x") End Function <Fact> Public Async Function TestCSharpStaticVolatileField() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Foo { private static volatile int $$x; } </Document> </Project> </Workspace> Await TestCSharpAsync(workspace, $"({FeaturesResources.field}) static volatile int Foo.x") End Function <Fact> <WorkItem(33049, "https://github.com/dotnet/roslyn/issues/33049")> Public Async Function TestCSharpDefaultParameter() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Threading; class Goo { void Method(CancellationToken cancellationToken = default(CancellationToken)) { $$Method(CancellationToken.None); } } </Document> </Project> </Workspace> Await TestCSharpAsync(workspace, $"void Goo.Method([CancellationToken cancellationToken = default])") End Function #End Region #Region "Basic SymbolDescription Tests" <Fact> Public Async Function TestNamedTypeKindClass() As Task Dim workspace = WrapCodeInWorkspace("class Program", "Dim p as Prog$$ram", "End class") Await TestBasicAsync(workspace, "Class Program") End Function ''' <summary> ''' Design Change from Dev10. Notice that we now show the type information for T ''' C# / VB Quick Info consistency ''' </summary> ''' <remarks></remarks> <Fact> Public Async Function TestGenericClass() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class Program Dim p as New System.Collections.Generic.Lis$$t(Of String) End class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, StringFromLines("Sub List(Of String).New()")) End Function <Fact> Public Async Function TestGenericClassFromSource() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Namespace TestNamespace Public Class Outer(Of T) End Class Module Test Dim x As New O$$uter(Of Integer) End Module End Namespace </Document> </Project> </Workspace> Await TestBasicAsync(workspace, StringFromLines("Sub Outer(Of Integer).New()")) End Function <Fact> Public Async Function TestClassNestedWithinAGenericClass() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Outer(Of T) Public Class Inner Public Sub F(x As T) End Sub End Class End Class Module Test Sub Main() Dim x As New Outer(Of Integer).In$$ner() x.F(4) End Sub End Module </Document> </Project> </Workspace> Await TestBasicAsync(workspace, StringFromLines("Sub Outer(Of Integer).Inner.New()")) End Function <Fact> Public Async Function TestTypeParameter() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Goo(Of T) Dim x as T$$ End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"T {FeaturesResources.in_} Goo(Of T)") End Function <Fact> Public Async Function TestTypeParameterFromNestedClass() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Outer(Of T) Public Class Inner Public Sub F(x As T$$) End Sub End Class End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"T {FeaturesResources.in_} Outer(Of T)") End Function <Fact> Public Async Function TestShadowedTypeParameter() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Outer(Of T) Public Class Inner Public Sub F(x As T$$) End Sub End Class End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"T {FeaturesResources.in_} Outer(Of T)") End Function <Fact> Public Async Function TestNullableOfInt() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Public Class Goo Dim x as Nullab$$le(Of Integer) End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, StringFromLines("Structure System.Nullable(Of T As Structure)", String.Empty, $"T {FeaturesResources.is_} Integer")) End Function <Fact> Public Async Function TestDictionaryOfIntAndString() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System.Collections.Generic class Program Dim p as New Dictio$$nary(Of Integer, String) End class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, StringFromLines("Sub Dictionary(Of Integer, String).New()")) End Function <Fact> Public Async Function TestNamedTypeKindStructure() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Structure Program Dim p as Prog$$ram End Structure </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Structure Program") End Function <Fact> Public Async Function TestNamedTypeKindStructureBuiltIn() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class Program Dim p as Int$$eger End class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Structure System.Int32") End Function <Fact> Public Async Function TestNamedTypeKindEnum() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Enum Program End Enum Module M1 Sub Main(args As String()) Dim p as Prog$$ram End Sub End Module </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Enum Program") End Function <Fact> Public Async Function TestNamedTypeKindDelegate() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Delegate Sub DelegateType() Module M1 Event AnEvent As Delega$$teType Sub Main(args As String()) End Sub End Module </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Delegate Sub DelegateType()") End Function <Fact> Public Async Function TestNamedTypeKindInterface() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Interface Goo End Interface Module M1 Sub Main(args As String()) Dim p as Goo$$ End Sub End Module </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Interface Goo") End Function <Fact> Public Async Function TestNamedTypeKindModule() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo sub Method() $$M1.M() End sub End Class Module M1 public sub M() End sub End Module </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Module M1") End Function <Fact> Public Async Function TestNamespace() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo sub Method() Sys$$tem.Console.Write(5) End sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Namespace System") End Function <Fact> Public Async Function TestNamespace2() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System.Collections.Gene$$ric </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Namespace System.Collections.Generic") End Function <Fact> Public Async Function TestField() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo private field as Integer sub Method() fie$$ld = 5 End sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"({FeaturesResources.field}) Goo.field As Integer") End Function <Fact> Public Async Function TestSharedField() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo private Shared field as Integer sub Method() fie$$ld = 5 End sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"({FeaturesResources.field}) Shared Goo.field As Integer") End Function <Fact> Public Async Function TestReadOnlyField() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo private ReadOnly field as Integer sub Method() fie$$ld = 5 End sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"({FeaturesResources.field}) ReadOnly Goo.field As Integer") End Function <Fact> Public Async Function TestSharedReadOnlyField() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo private Shared ReadOnly field as Integer sub Method() fie$$ld = 5 End sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"({FeaturesResources.field}) Shared ReadOnly Goo.field As Integer") End Function <Fact> Public Async Function TestLocal() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo sub Method() Dim x as String x$$ = "Hello" End sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"({FeaturesResources.local_variable}) x As String") End Function <WorkItem(538732, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538732")> <Fact> Public Async Function TestMethod() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub Method() Fu$$n() End Sub Function Fun() As Integer Return 1 End Function End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Function Goo.Fun() As Integer") End Function ''' <summary> ''' This is a design change from Dev10. Notice that modifiers "public shared sub" are absent. ''' VB / C# Quick Info Consistency ''' </summary> ''' <remarks></remarks> <WorkItem(538732, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538732")> <Fact> Public Async Function TestPEMethod() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub Method() System.Console.Writ$$e(5) End Sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Sub Console.Write(value As Integer)") End Function ''' <summary> ''' This is a design change from Dev10. Showing what we already know is kinda useless. ''' This is what C# does. We are modifying VB to follow this model. ''' </summary> ''' <remarks></remarks> <Fact> Public Async Function TestFormalParameter() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub Method() End Sub Function Fun(x$$ As String) As Integer Return 1 End Function End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"({FeaturesResources.parameter}) x As String") End Function <Fact> Public Async Function TestOptionalParameter() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Sub Method(x As Short, Optional y As Integer = 10) End Sub Sub Test Met$$hod(1, 2) End Sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Sub Goo.Method(x As Short, [y As Integer = 10])") End Function <Fact> Public Async Function TestOverloadedMethod() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Overloads Sub Method(x As Integer) End Sub Overloads Sub Method(x As String) End Sub Sub Test() Meth$$od("str") End Sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Sub Goo.Method(x As String)") End Function <Fact> Public Async Function TestOverloadedMethods() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo Overloads Sub Method(x As Integer) End Sub Overloads Sub Method(x As String) End Sub Overloads Sub Method(x As Double) End Sub Sub Test() Meth$$od("str") End Sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Sub Goo.Method(x As String)") End Function <WorkItem(527639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527639")> <Fact> Public Async Function TestInterfaceConstraintOnClass() As Task Dim workspace = WrapCodeInWorkspace("Imports System.Collections.Generic", "Class CC(Of T$$ As IEnumerable(Of Integer))", "End Class") Dim expectedDescription = $"T {FeaturesResources.in_} CC(Of T As IEnumerable(Of Integer))" Await TestBasicAsync(workspace, expectedDescription) End Function <WorkItem(527639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527639")> <Fact> Public Async Function TestInterfaceConstraintOnInterface() As Task Dim workspace = WrapCodeInWorkspace("Imports System.Collections.Generic", "Interface IMyInterface(Of T$$ As IEnumerable(Of Integer))", "End Interface") Dim expectedDescription = $"T {FeaturesResources.in_} IMyInterface(Of T As IEnumerable(Of Integer))" Await TestBasicAsync(workspace, expectedDescription) End Function <WorkItem(527639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527639")> <Fact> Public Async Function TestReferenceTypeConstraintOnClass() As Task Dim workspace = WrapCodeInWorkspace("Class CC(Of T$$ As Class)", "End Class") Dim expectedDescription = $"T {FeaturesResources.in_} CC(Of T As Class)" Await TestBasicAsync(workspace, expectedDescription) End Function <WorkItem(527639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527639")> <Fact> Public Async Function TestValueTypeConstraintOnClass() As Task Dim workspace = WrapCodeInWorkspace("Class CC(Of T$$ As Structure)", "End Class") Dim expectedDescription = $"T {FeaturesResources.in_} CC(Of T As Structure)" Await TestBasicAsync(workspace, expectedDescription) End Function <WorkItem(527639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527639")> <Fact> Public Async Function TestValueTypeConstraintOnStructure() As Task Dim workspace = WrapCodeInWorkspace("Structure S(Of T$$ As Class)", "End Structure") Dim expectedDescription = $"T {FeaturesResources.in_} S(Of T As Class)" Await TestBasicAsync(workspace, expectedDescription) End Function <WorkItem(527639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527639")> <Fact> Public Async Function TestMultipleConstraintsOnClass() As Task Dim workspace = WrapCodeInWorkspace("Public Class CC(Of T$$ As {IComparable, IDisposable, Class, New})", "End Class") Dim expectedDescription = $"T {FeaturesResources.in_} CC(Of T As {{Class, IComparable, IDisposable, New}})" Await TestBasicAsync(workspace, expectedDescription) End Function ''' TO DO: Add test for Ref Arg <Fact> Public Async Function TestOutArguments() As Task Dim workspace = WrapCodeInWorkspace("Imports System.Collections.Generic", "Class CC(Of T As IEnum$$erable(Of Integer))", "End Class") Dim expectedDescription = StringFromLines("Interface System.Collections.Generic.IEnumerable(Of Out T)", String.Empty, $"T {FeaturesResources.is_} Integer") Await TestBasicAsync(workspace, expectedDescription) End Function <WorkItem(527655, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527655")> <Fact> Public Async Function TestMinimalDisplayName() As Task Dim workspace = WrapCodeInWorkspace("Imports System", "Imports System.Collections.Generic", "Class CC(Of T As IEnu$$merable(Of IEnumerable(of Int32)))", "End Class") Dim expectedDescription = StringFromLines("Interface System.Collections.Generic.IEnumerable(Of Out T)", String.Empty, $"T {FeaturesResources.is_} IEnumerable(Of Integer)") Await TestBasicAsync(workspace, expectedDescription) End Function <Fact> Public Async Function TestOverridableMethod() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class A Public Overridable Sub G() End Sub End Class Class B Inherits A Public Overrides Sub G() End Sub End Class Class C Sub Test() Dim x As A x = new A() x.G$$() End Sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Sub A.G()") End Function <Fact> Public Async Function TestOverriddenMethod2() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class A Public Overridable Sub G() End Sub End Class Class B Inherits A Public Overrides Sub G() End Sub End Class Class C Sub Test() Dim x As A x = new B() x.G$$() End Sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Sub A.G()") End Function <Fact> Public Async Function TestGenericMethod() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Outer(Of T) Public Class Inner Public Sub F(x As T) End Sub End Class End Class Module Test Sub Main() Dim x As New Outer(Of Integer).Inner() x.F$$(4) End Sub End Module </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Sub Outer(Of Integer).Inner.F(x As Integer)") End Function <Fact> Public Async Function TestAutoImplementedProperty() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System.Collections.Generic Class Goo Public Property It$$ems As New List(Of String) From {"M", "T", "W"} End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, "Property Goo.Items As List(Of String)") End Function <WorkItem(538806, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538806")> <Fact> Public Async Function TestField1() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Dim x As Integer Sub Method() Dim y As Integer $$x = y End Sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"({FeaturesResources.field}) C.x As Integer") End Function <WorkItem(538806, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538806")> <Fact> Public Async Function TestProperty1() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Dim x As Integer Sub Method() Dim y As Integer x = $$y End Sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"({FeaturesResources.local_variable}) y As Integer") End Function <WorkItem(543911, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543911")> <Fact> Public Async Function TestVBLocalConstant() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Goo sub Method() Const $$b = 2 End sub End Class </Document> </Project> </Workspace> Await TestBasicAsync(workspace, $"({FeaturesResources.local_constant}) b As Integer = 2") End Function #End Region End Class End Namespace
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Portable/Symbols/NonMissingAssemblySymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A <see cref="NonMissingAssemblySymbol"/> is a special kind of <see cref="AssemblySymbol"/> that represents /// an assembly that is not missing, i.e. the "real" thing. /// </summary> internal abstract class NonMissingAssemblySymbol : AssemblySymbol { /// <summary> /// This is a cache similar to the one used by MetaImport::GetTypeByName /// in native compiler. The difference is that native compiler pre-populates /// the cache when it loads types. Here we are populating the cache only /// with things we looked for, so that next time we are looking for the same /// thing, the lookup is fast. This cache also takes care of TypeForwarders. /// Gives about 8% win on subsequent lookups in some scenarios. /// </summary> /// <remarks></remarks> private readonly ConcurrentDictionary<MetadataTypeName.Key, NamedTypeSymbol> _emittedNameToTypeMap = new ConcurrentDictionary<MetadataTypeName.Key, NamedTypeSymbol>(); private NamespaceSymbol _globalNamespace; /// <summary> /// Does this symbol represent a missing assembly. /// </summary> internal sealed override bool IsMissing { get { return false; } } /// <summary> /// Gets the merged root namespace that contains all namespaces and types defined in the modules /// of this assembly. If there is just one module in this assembly, this property just returns the /// GlobalNamespace of that module. /// </summary> public sealed override NamespaceSymbol GlobalNamespace { get { if ((object)_globalNamespace == null) { // Get the root namespace from each module, and merge them all together. If there is only one, // then MergedNamespaceSymbol.Create will just return that one. IEnumerable<NamespaceSymbol> allGlobalNamespaces = from m in Modules select m.GlobalNamespace; var result = MergedNamespaceSymbol.Create(new NamespaceExtent(this), null, allGlobalNamespaces.AsImmutable()); Interlocked.CompareExchange(ref _globalNamespace, result, null); } return _globalNamespace; } } /// <summary> /// Lookup a top level type referenced from metadata, names should be /// compared case-sensitively. Detect cycles during lookup. /// </summary> /// <param name="emittedName"> /// Full type name, possibly with generic name mangling. /// </param> /// <param name="visitedAssemblies"> /// List of assemblies lookup has already visited (since type forwarding can introduce cycles). /// </param> /// <param name="digThroughForwardedTypes"> /// Take forwarded types into account. /// </param> internal sealed override NamedTypeSymbol LookupTopLevelMetadataTypeWithCycleDetection(ref MetadataTypeName emittedName, ConsList<AssemblySymbol> visitedAssemblies, bool digThroughForwardedTypes) { NamedTypeSymbol result = null; // This is a cache similar to the one used by MetaImport::GetTypeByName in native // compiler. The difference is that native compiler pre-populates the cache when it // loads types. Here we are populating the cache only with things we looked for, so that // next time we are looking for the same thing, the lookup is fast. This cache also // takes care of TypeForwarders. Gives about 8% win on subsequent lookups in some // scenarios. // // CONSIDER !!! // // However, it is questionable how often subsequent lookup by name is going to happen. // Currently it doesn't happen for TypeDef tokens at all, for TypeRef tokens, the // lookup by name is done once and the result is cached. So, multiple lookups by name // for the same type are going to happen only in these cases: // 1) Resolving GetType() in attribute application, type is encoded by name. // 2) TypeRef token isn't reused within the same module, i.e. multiple TypeRefs point to // the same type. // 3) Different Module refers to the same type, lookup once per Module (with exception of #2). // 4) Multitargeting - retargeting the type to a different version of assembly result = LookupTopLevelMetadataTypeInCache(ref emittedName); if ((object)result != null) { // We only cache result equivalent to digging through type forwarders, which // might produce a forwarder specific ErrorTypeSymbol. We don't want to // return that error symbol, unless digThroughForwardedTypes is true. if (digThroughForwardedTypes || (!result.IsErrorType() && (object)result.ContainingAssembly == (object)this)) { return result; } // According to the cache, the type wasn't found, or isn't declared in this assembly (forwarded). return new MissingMetadataTypeSymbol.TopLevel(this.Modules[0], ref emittedName); } else { // Now we will look for the type in each module of the assembly and pick the first type // we find, this is what native VB compiler does. var modules = this.Modules; var count = modules.Length; var i = 0; result = modules[i].LookupTopLevelMetadataType(ref emittedName); if (result is MissingMetadataTypeSymbol) { for (i = 1; i < count; i++) { var newResult = modules[i].LookupTopLevelMetadataType(ref emittedName); // Hold on to the first missing type result, unless we found the type. if (!(newResult is MissingMetadataTypeSymbol)) { result = newResult; break; } } } bool foundMatchInThisAssembly = (i < count); Debug.Assert(!foundMatchInThisAssembly || (object)result.ContainingAssembly == (object)this); if (!foundMatchInThisAssembly && digThroughForwardedTypes) { // We didn't find the type System.Diagnostics.Debug.Assert(result is MissingMetadataTypeSymbol); NamedTypeSymbol forwarded = TryLookupForwardedMetadataTypeWithCycleDetection(ref emittedName, visitedAssemblies); if ((object)forwarded != null) { result = forwarded; } } System.Diagnostics.Debug.Assert((object)result != null); // Add result of the lookup into the cache if (digThroughForwardedTypes || foundMatchInThisAssembly) { CacheTopLevelMetadataType(ref emittedName, result); } return result; } } internal abstract override NamedTypeSymbol TryLookupForwardedMetadataTypeWithCycleDetection(ref MetadataTypeName emittedName, ConsList<AssemblySymbol> visitedAssemblies); private NamedTypeSymbol LookupTopLevelMetadataTypeInCache(ref MetadataTypeName emittedName) { NamedTypeSymbol result = null; if (_emittedNameToTypeMap.TryGetValue(emittedName.ToKey(), out result)) { return result; } return null; } /// <summary> /// For test purposes only. /// </summary> internal NamedTypeSymbol CachedTypeByEmittedName(string emittedname) { MetadataTypeName mdName = MetadataTypeName.FromFullName(emittedname); return _emittedNameToTypeMap[mdName.ToKey()]; } /// <summary> /// For test purposes only. /// </summary> internal int EmittedNameToTypeMapCount { get { return _emittedNameToTypeMap.Count; } } private void CacheTopLevelMetadataType( ref MetadataTypeName emittedName, NamedTypeSymbol result) { NamedTypeSymbol result1 = null; result1 = _emittedNameToTypeMap.GetOrAdd(emittedName.ToKey(), result); System.Diagnostics.Debug.Assert(TypeSymbol.Equals(result1, result, TypeCompareKind.ConsiderEverything2)); // object identity may differ in error cases } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A <see cref="NonMissingAssemblySymbol"/> is a special kind of <see cref="AssemblySymbol"/> that represents /// an assembly that is not missing, i.e. the "real" thing. /// </summary> internal abstract class NonMissingAssemblySymbol : AssemblySymbol { /// <summary> /// This is a cache similar to the one used by MetaImport::GetTypeByName /// in native compiler. The difference is that native compiler pre-populates /// the cache when it loads types. Here we are populating the cache only /// with things we looked for, so that next time we are looking for the same /// thing, the lookup is fast. This cache also takes care of TypeForwarders. /// Gives about 8% win on subsequent lookups in some scenarios. /// </summary> /// <remarks></remarks> private readonly ConcurrentDictionary<MetadataTypeName.Key, NamedTypeSymbol> _emittedNameToTypeMap = new ConcurrentDictionary<MetadataTypeName.Key, NamedTypeSymbol>(); private NamespaceSymbol _globalNamespace; /// <summary> /// Does this symbol represent a missing assembly. /// </summary> internal sealed override bool IsMissing { get { return false; } } /// <summary> /// Gets the merged root namespace that contains all namespaces and types defined in the modules /// of this assembly. If there is just one module in this assembly, this property just returns the /// GlobalNamespace of that module. /// </summary> public sealed override NamespaceSymbol GlobalNamespace { get { if ((object)_globalNamespace == null) { // Get the root namespace from each module, and merge them all together. If there is only one, // then MergedNamespaceSymbol.Create will just return that one. IEnumerable<NamespaceSymbol> allGlobalNamespaces = from m in Modules select m.GlobalNamespace; var result = MergedNamespaceSymbol.Create(new NamespaceExtent(this), null, allGlobalNamespaces.AsImmutable()); Interlocked.CompareExchange(ref _globalNamespace, result, null); } return _globalNamespace; } } /// <summary> /// Lookup a top level type referenced from metadata, names should be /// compared case-sensitively. Detect cycles during lookup. /// </summary> /// <param name="emittedName"> /// Full type name, possibly with generic name mangling. /// </param> /// <param name="visitedAssemblies"> /// List of assemblies lookup has already visited (since type forwarding can introduce cycles). /// </param> /// <param name="digThroughForwardedTypes"> /// Take forwarded types into account. /// </param> internal sealed override NamedTypeSymbol LookupTopLevelMetadataTypeWithCycleDetection(ref MetadataTypeName emittedName, ConsList<AssemblySymbol> visitedAssemblies, bool digThroughForwardedTypes) { NamedTypeSymbol result = null; // This is a cache similar to the one used by MetaImport::GetTypeByName in native // compiler. The difference is that native compiler pre-populates the cache when it // loads types. Here we are populating the cache only with things we looked for, so that // next time we are looking for the same thing, the lookup is fast. This cache also // takes care of TypeForwarders. Gives about 8% win on subsequent lookups in some // scenarios. // // CONSIDER !!! // // However, it is questionable how often subsequent lookup by name is going to happen. // Currently it doesn't happen for TypeDef tokens at all, for TypeRef tokens, the // lookup by name is done once and the result is cached. So, multiple lookups by name // for the same type are going to happen only in these cases: // 1) Resolving GetType() in attribute application, type is encoded by name. // 2) TypeRef token isn't reused within the same module, i.e. multiple TypeRefs point to // the same type. // 3) Different Module refers to the same type, lookup once per Module (with exception of #2). // 4) Multitargeting - retargeting the type to a different version of assembly result = LookupTopLevelMetadataTypeInCache(ref emittedName); if ((object)result != null) { // We only cache result equivalent to digging through type forwarders, which // might produce a forwarder specific ErrorTypeSymbol. We don't want to // return that error symbol, unless digThroughForwardedTypes is true. if (digThroughForwardedTypes || (!result.IsErrorType() && (object)result.ContainingAssembly == (object)this)) { return result; } // According to the cache, the type wasn't found, or isn't declared in this assembly (forwarded). return new MissingMetadataTypeSymbol.TopLevel(this.Modules[0], ref emittedName); } else { // Now we will look for the type in each module of the assembly and pick the first type // we find, this is what native VB compiler does. var modules = this.Modules; var count = modules.Length; var i = 0; result = modules[i].LookupTopLevelMetadataType(ref emittedName); if (result is MissingMetadataTypeSymbol) { for (i = 1; i < count; i++) { var newResult = modules[i].LookupTopLevelMetadataType(ref emittedName); // Hold on to the first missing type result, unless we found the type. if (!(newResult is MissingMetadataTypeSymbol)) { result = newResult; break; } } } bool foundMatchInThisAssembly = (i < count); Debug.Assert(!foundMatchInThisAssembly || (object)result.ContainingAssembly == (object)this); if (!foundMatchInThisAssembly && digThroughForwardedTypes) { // We didn't find the type System.Diagnostics.Debug.Assert(result is MissingMetadataTypeSymbol); NamedTypeSymbol forwarded = TryLookupForwardedMetadataTypeWithCycleDetection(ref emittedName, visitedAssemblies); if ((object)forwarded != null) { result = forwarded; } } System.Diagnostics.Debug.Assert((object)result != null); // Add result of the lookup into the cache if (digThroughForwardedTypes || foundMatchInThisAssembly) { CacheTopLevelMetadataType(ref emittedName, result); } return result; } } internal abstract override NamedTypeSymbol TryLookupForwardedMetadataTypeWithCycleDetection(ref MetadataTypeName emittedName, ConsList<AssemblySymbol> visitedAssemblies); private NamedTypeSymbol LookupTopLevelMetadataTypeInCache(ref MetadataTypeName emittedName) { NamedTypeSymbol result = null; if (_emittedNameToTypeMap.TryGetValue(emittedName.ToKey(), out result)) { return result; } return null; } /// <summary> /// For test purposes only. /// </summary> internal NamedTypeSymbol CachedTypeByEmittedName(string emittedname) { MetadataTypeName mdName = MetadataTypeName.FromFullName(emittedname); return _emittedNameToTypeMap[mdName.ToKey()]; } /// <summary> /// For test purposes only. /// </summary> internal int EmittedNameToTypeMapCount { get { return _emittedNameToTypeMap.Count; } } private void CacheTopLevelMetadataType( ref MetadataTypeName emittedName, NamedTypeSymbol result) { NamedTypeSymbol result1 = null; result1 = _emittedNameToTypeMap.GetOrAdd(emittedName.ToKey(), result); System.Diagnostics.Debug.Assert(TypeSymbol.Equals(result1, result, TypeCompareKind.ConsiderEverything2)); // object identity may differ in error cases } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Portable/Binder/Semantics/Operators/UnaryOperatorAnalysisResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal struct UnaryOperatorAnalysisResult { public readonly UnaryOperatorSignature Signature; public readonly Conversion Conversion; public readonly OperatorAnalysisResultKind Kind; private UnaryOperatorAnalysisResult(OperatorAnalysisResultKind kind, UnaryOperatorSignature signature, Conversion conversion) { this.Kind = kind; this.Signature = signature; this.Conversion = conversion; } public bool IsValid { get { return this.Kind == OperatorAnalysisResultKind.Applicable; } } public bool HasValue { get { return this.Kind != OperatorAnalysisResultKind.Undefined; } } public static UnaryOperatorAnalysisResult Applicable(UnaryOperatorSignature signature, Conversion conversion) { return new UnaryOperatorAnalysisResult(OperatorAnalysisResultKind.Applicable, signature, conversion); } public static UnaryOperatorAnalysisResult Inapplicable(UnaryOperatorSignature signature, Conversion conversion) { return new UnaryOperatorAnalysisResult(OperatorAnalysisResultKind.Inapplicable, signature, conversion); } public UnaryOperatorAnalysisResult Worse() { return new UnaryOperatorAnalysisResult(OperatorAnalysisResultKind.Worse, this.Signature, this.Conversion); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal struct UnaryOperatorAnalysisResult { public readonly UnaryOperatorSignature Signature; public readonly Conversion Conversion; public readonly OperatorAnalysisResultKind Kind; private UnaryOperatorAnalysisResult(OperatorAnalysisResultKind kind, UnaryOperatorSignature signature, Conversion conversion) { this.Kind = kind; this.Signature = signature; this.Conversion = conversion; } public bool IsValid { get { return this.Kind == OperatorAnalysisResultKind.Applicable; } } public bool HasValue { get { return this.Kind != OperatorAnalysisResultKind.Undefined; } } public static UnaryOperatorAnalysisResult Applicable(UnaryOperatorSignature signature, Conversion conversion) { return new UnaryOperatorAnalysisResult(OperatorAnalysisResultKind.Applicable, signature, conversion); } public static UnaryOperatorAnalysisResult Inapplicable(UnaryOperatorSignature signature, Conversion conversion) { return new UnaryOperatorAnalysisResult(OperatorAnalysisResultKind.Inapplicable, signature, conversion); } public UnaryOperatorAnalysisResult Worse() { return new UnaryOperatorAnalysisResult(OperatorAnalysisResultKind.Worse, this.Signature, this.Conversion); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./docs/compilers/Design/Parser.md
Parser Design Guidelines ======================== This document describes design guidelines for the Roslyn parsers. These are not hard rules that cannot be violated. Use good judgment. It is acceptable to vary from the guidelines when there are reasons that outweigh their benefits. ![image](https://i0.wp.com/media.tumblr.com/tumblr_lzwm2hKMGx1qhkwbs.gif) The parsers do not currently comply with these guidelines, even in places where there is no good reason not to. The guidelines were written after the parsers. We expect to refactor the parsers opportunistically to comply with these guidelines, particularly when there are concrete benefit from doing so. Designing the syntax model (data model for the syntax tree) for new features is currently outside the scope of these guidelines. #### **DO** have the parser accept input text that complies with the syntax model The syntax model defines the contract between syntax and semantic analysis. If the parser can build a meaningful syntax tree for a sequence of input tokens, then it should be left to semantic analysis to report when that tree is not semantically valid. The most important diagnostics to report from the parser are "missing token" and "unexpected token". There may be reasons to violate this rule. For example, the syntax model does not have a concept of precedence, but the parser uses precedence to decide how to assemble the tree. Precedence errors are therefore reported in the parser. #### **DO NOT** use ambient context to direct the behavior of the parser The parser should, as much as possible, be context-free. Use context where needed only to resolve language ambiguities. For example, in contexts where both a type and an expression are permitted, but a type is preferred, (such as the right-hand-side of `is`) we parse `X.Y` as a type. But in contexts where both are permitted, but it is to be treated as a type only if followed by an identifier (such as following `case`), we use look-ahead to decide which kind of tree to build. Try to minimize the amount of context used to make parsing decisions, as that will improve the quality of incremental parsing. There may be reasons to violate this rule, for example where the language is specified to be sensitive to context. For example, `await` is treated as a keyword if the enclosing method has the `async` modifier. #### Examples Here are some examples of places where we might change the parser toward satisfying these guidelines, and the problems that may solve: 1. 100l : warning: use `L` for long literals It may seem a small thing to produce this warning in the parser, but it interferes with incremental parsing. The incremental parser will not reuse a node that has diagnostics. As a consequence, even the presence of this helpful warning in code can reduce the performance of the parser as the user types in that source. That reduced performance may mean that the editor will not appear as responsive. By moving this warning out of the parser and into semantic analysis, the IDE can be more responsive during typing. 1. Member parsing The syntax model represents constructors and methods using separate nodes. When a declaration of the form `public M() {}` is seen, the parser checks the name of the function against the name of the enclosing type to decide whether it should represent it as a constructor, or as a method with a missing type. In this case the name of the enclosing type is a form of *ambient context* that affects the behavior of the compiler. By treating such as declaration as a constructor in the syntax model, and checking the name in semantic analysis, it becomes possible to expose a context-free public API for parsing a member declaration. See https://github.com/dotnet/roslyn/issues/367 for a feature request that we have been unable to do because of this problem.
Parser Design Guidelines ======================== This document describes design guidelines for the Roslyn parsers. These are not hard rules that cannot be violated. Use good judgment. It is acceptable to vary from the guidelines when there are reasons that outweigh their benefits. ![image](https://i0.wp.com/media.tumblr.com/tumblr_lzwm2hKMGx1qhkwbs.gif) The parsers do not currently comply with these guidelines, even in places where there is no good reason not to. The guidelines were written after the parsers. We expect to refactor the parsers opportunistically to comply with these guidelines, particularly when there are concrete benefit from doing so. Designing the syntax model (data model for the syntax tree) for new features is currently outside the scope of these guidelines. #### **DO** have the parser accept input text that complies with the syntax model The syntax model defines the contract between syntax and semantic analysis. If the parser can build a meaningful syntax tree for a sequence of input tokens, then it should be left to semantic analysis to report when that tree is not semantically valid. The most important diagnostics to report from the parser are "missing token" and "unexpected token". There may be reasons to violate this rule. For example, the syntax model does not have a concept of precedence, but the parser uses precedence to decide how to assemble the tree. Precedence errors are therefore reported in the parser. #### **DO NOT** use ambient context to direct the behavior of the parser The parser should, as much as possible, be context-free. Use context where needed only to resolve language ambiguities. For example, in contexts where both a type and an expression are permitted, but a type is preferred, (such as the right-hand-side of `is`) we parse `X.Y` as a type. But in contexts where both are permitted, but it is to be treated as a type only if followed by an identifier (such as following `case`), we use look-ahead to decide which kind of tree to build. Try to minimize the amount of context used to make parsing decisions, as that will improve the quality of incremental parsing. There may be reasons to violate this rule, for example where the language is specified to be sensitive to context. For example, `await` is treated as a keyword if the enclosing method has the `async` modifier. #### Examples Here are some examples of places where we might change the parser toward satisfying these guidelines, and the problems that may solve: 1. 100l : warning: use `L` for long literals It may seem a small thing to produce this warning in the parser, but it interferes with incremental parsing. The incremental parser will not reuse a node that has diagnostics. As a consequence, even the presence of this helpful warning in code can reduce the performance of the parser as the user types in that source. That reduced performance may mean that the editor will not appear as responsive. By moving this warning out of the parser and into semantic analysis, the IDE can be more responsive during typing. 1. Member parsing The syntax model represents constructors and methods using separate nodes. When a declaration of the form `public M() {}` is seen, the parser checks the name of the function against the name of the enclosing type to decide whether it should represent it as a constructor, or as a method with a missing type. In this case the name of the enclosing type is a form of *ambient context* that affects the behavior of the compiler. By treating such as declaration as a constructor in the syntax model, and checking the name in semantic analysis, it becomes possible to expose a context-free public API for parsing a member declaration. See https://github.com/dotnet/roslyn/issues/367 for a feature request that we have been unable to do because of this problem.
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/VSTypeScriptFindUsagesService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Editor.FindUsages; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.Editor.ExternalAccess.VSTypeScript { [ExportLanguageService(typeof(IFindUsagesService), InternalLanguageNames.TypeScript), Shared] internal class VSTypeScriptFindUsagesService : IFindUsagesService { private readonly IVSTypeScriptFindUsagesService _underlyingService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptFindUsagesService(IVSTypeScriptFindUsagesService underlyingService) { _underlyingService = underlyingService; } public Task FindReferencesAsync(Document document, int position, IFindUsagesContext context, CancellationToken cancellationToken) => _underlyingService.FindReferencesAsync(document, position, new VSTypeScriptFindUsagesContext(context), cancellationToken); public Task FindImplementationsAsync(Document document, int position, IFindUsagesContext context, CancellationToken cancellationToken) => _underlyingService.FindImplementationsAsync(document, position, new VSTypeScriptFindUsagesContext(context), cancellationToken); private class VSTypeScriptFindUsagesContext : IVSTypeScriptFindUsagesContext { private readonly IFindUsagesContext _context; private readonly Dictionary<VSTypeScriptDefinitionItem, DefinitionItem> _definitionItemMap = new(); public VSTypeScriptFindUsagesContext(IFindUsagesContext context) { _context = context; } public IVSTypeScriptStreamingProgressTracker ProgressTracker => new VSTypeScriptStreamingProgressTracker(_context.ProgressTracker); public ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken) => _context.ReportMessageAsync(message, cancellationToken); public ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) => _context.SetSearchTitleAsync(title, cancellationToken); private DefinitionItem GetOrCreateDefinitionItem(VSTypeScriptDefinitionItem item) { lock (_definitionItemMap) { if (!_definitionItemMap.TryGetValue(item, out var result)) { result = DefinitionItem.Create( item.Tags, item.DisplayParts, item.SourceSpans, item.NameDisplayParts, item.Properties, item.DisplayableProperties, item.DisplayIfNoReferences); _definitionItemMap.Add(item, result); } return result; } } public ValueTask OnDefinitionFoundAsync(VSTypeScriptDefinitionItem definition, CancellationToken cancellationToken) { var item = GetOrCreateDefinitionItem(definition); return _context.OnDefinitionFoundAsync(item, cancellationToken); } public ValueTask OnReferenceFoundAsync(VSTypeScriptSourceReferenceItem reference, CancellationToken cancellationToken) { var item = GetOrCreateDefinitionItem(reference.Definition); return _context.OnReferenceFoundAsync(new SourceReferenceItem(item, reference.SourceSpan, reference.SymbolUsageInfo), cancellationToken); } } private class VSTypeScriptStreamingProgressTracker : IVSTypeScriptStreamingProgressTracker { private readonly IStreamingProgressTracker _progressTracker; public VSTypeScriptStreamingProgressTracker(IStreamingProgressTracker progressTracker) { _progressTracker = progressTracker; } public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) => _progressTracker.AddItemsAsync(count, cancellationToken); public ValueTask ItemCompletedAsync(CancellationToken cancellationToken) => _progressTracker.ItemCompletedAsync(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.Editor.FindUsages; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.Editor.ExternalAccess.VSTypeScript { [ExportLanguageService(typeof(IFindUsagesService), InternalLanguageNames.TypeScript), Shared] internal class VSTypeScriptFindUsagesService : IFindUsagesService { private readonly IVSTypeScriptFindUsagesService _underlyingService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptFindUsagesService(IVSTypeScriptFindUsagesService underlyingService) { _underlyingService = underlyingService; } public Task FindReferencesAsync(Document document, int position, IFindUsagesContext context, CancellationToken cancellationToken) => _underlyingService.FindReferencesAsync(document, position, new VSTypeScriptFindUsagesContext(context), cancellationToken); public Task FindImplementationsAsync(Document document, int position, IFindUsagesContext context, CancellationToken cancellationToken) => _underlyingService.FindImplementationsAsync(document, position, new VSTypeScriptFindUsagesContext(context), cancellationToken); private class VSTypeScriptFindUsagesContext : IVSTypeScriptFindUsagesContext { private readonly IFindUsagesContext _context; private readonly Dictionary<VSTypeScriptDefinitionItem, DefinitionItem> _definitionItemMap = new(); public VSTypeScriptFindUsagesContext(IFindUsagesContext context) { _context = context; } public IVSTypeScriptStreamingProgressTracker ProgressTracker => new VSTypeScriptStreamingProgressTracker(_context.ProgressTracker); public ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken) => _context.ReportMessageAsync(message, cancellationToken); public ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) => _context.SetSearchTitleAsync(title, cancellationToken); private DefinitionItem GetOrCreateDefinitionItem(VSTypeScriptDefinitionItem item) { lock (_definitionItemMap) { if (!_definitionItemMap.TryGetValue(item, out var result)) { result = DefinitionItem.Create( item.Tags, item.DisplayParts, item.SourceSpans, item.NameDisplayParts, item.Properties, item.DisplayableProperties, item.DisplayIfNoReferences); _definitionItemMap.Add(item, result); } return result; } } public ValueTask OnDefinitionFoundAsync(VSTypeScriptDefinitionItem definition, CancellationToken cancellationToken) { var item = GetOrCreateDefinitionItem(definition); return _context.OnDefinitionFoundAsync(item, cancellationToken); } public ValueTask OnReferenceFoundAsync(VSTypeScriptSourceReferenceItem reference, CancellationToken cancellationToken) { var item = GetOrCreateDefinitionItem(reference.Definition); return _context.OnReferenceFoundAsync(new SourceReferenceItem(item, reference.SourceSpan, reference.SymbolUsageInfo), cancellationToken); } } private class VSTypeScriptStreamingProgressTracker : IVSTypeScriptStreamingProgressTracker { private readonly IStreamingProgressTracker _progressTracker; public VSTypeScriptStreamingProgressTracker(IStreamingProgressTracker progressTracker) { _progressTracker = progressTracker; } public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) => _progressTracker.AddItemsAsync(count, cancellationToken); public ValueTask ItemCompletedAsync(CancellationToken cancellationToken) => _progressTracker.ItemCompletedAsync(cancellationToken); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./.git/hooks/pre-push.sample
#!/bin/sh # An example hook script to verify what is about to be pushed. Called by "git # push" after it has checked the remote status, but before anything has been # pushed. If this script exits with a non-zero status nothing will be pushed. # # This hook is called with the following parameters: # # $1 -- Name of the remote to which the push is being done # $2 -- URL to which the push is being done # # If pushing without using a named remote those arguments will be equal. # # Information about the commits which are being pushed is supplied as lines to # the standard input in the form: # # <local ref> <local sha1> <remote ref> <remote sha1> # # This sample shows how to prevent push of commits where the log message starts # with "WIP" (work in progress). remote="$1" url="$2" z40=0000000000000000000000000000000000000000 while read local_ref local_sha remote_ref remote_sha do if [ "$local_sha" = $z40 ] then # Handle delete : else if [ "$remote_sha" = $z40 ] then # New branch, examine all commits range="$local_sha" else # Update to existing branch, examine new commits range="$remote_sha..$local_sha" fi # Check for WIP commit commit=`git rev-list -n 1 --grep '^WIP' "$range"` if [ -n "$commit" ] then echo >&2 "Found WIP commit in $local_ref, not pushing" exit 1 fi fi done exit 0
#!/bin/sh # An example hook script to verify what is about to be pushed. Called by "git # push" after it has checked the remote status, but before anything has been # pushed. If this script exits with a non-zero status nothing will be pushed. # # This hook is called with the following parameters: # # $1 -- Name of the remote to which the push is being done # $2 -- URL to which the push is being done # # If pushing without using a named remote those arguments will be equal. # # Information about the commits which are being pushed is supplied as lines to # the standard input in the form: # # <local ref> <local sha1> <remote ref> <remote sha1> # # This sample shows how to prevent push of commits where the log message starts # with "WIP" (work in progress). remote="$1" url="$2" z40=0000000000000000000000000000000000000000 while read local_ref local_sha remote_ref remote_sha do if [ "$local_sha" = $z40 ] then # Handle delete : else if [ "$remote_sha" = $z40 ] then # New branch, examine all commits range="$local_sha" else # Update to existing branch, examine new commits range="$remote_sha..$local_sha" fi # Check for WIP commit commit=`git rev-list -n 1 --grep '^WIP' "$range"` if [ -n "$commit" ] then echo >&2 "Found WIP commit in $local_ref, not pushing" exit 1 fi fi done exit 0
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/Core/Implementation/EditAndContinue/ManagedEditAndContinueLanguageService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue { [Shared] [Export(typeof(IManagedEditAndContinueLanguageService))] [ExportMetadata("UIContext", EditAndContinueUIContext.EncCapableProjectExistsInWorkspaceUIContextString)] internal sealed class ManagedEditAndContinueLanguageService : IManagedEditAndContinueLanguageService { private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly EditAndContinueDiagnosticUpdateSource _diagnosticUpdateSource; private readonly Lazy<IManagedEditAndContinueDebuggerService> _debuggerService; private readonly Lazy<IHostWorkspaceProvider> _workspaceProvider; private RemoteDebuggingSessionProxy? _debuggingSession; private bool _disabled; /// <summary> /// Import <see cref="IHostWorkspaceProvider"/> and <see cref="IManagedEditAndContinueDebuggerService"/> lazily so that the host does not need to implement them /// unless it implements debugger components. /// </summary> [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ManagedEditAndContinueLanguageService( Lazy<IHostWorkspaceProvider> workspaceProvider, Lazy<IManagedEditAndContinueDebuggerService> debuggerService, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource) { _workspaceProvider = workspaceProvider; _debuggerService = debuggerService; _diagnosticService = diagnosticService; _diagnosticUpdateSource = diagnosticUpdateSource; } private Solution GetCurrentCompileTimeSolution() { var workspace = _workspaceProvider.Value.Workspace; return workspace.Services.GetRequiredService<ICompileTimeSolutionProvider>().GetCompileTimeSolution(workspace.CurrentSolution); } private IDebuggingWorkspaceService GetDebuggingService() => _workspaceProvider.Value.Workspace.Services.GetRequiredService<IDebuggingWorkspaceService>(); private IActiveStatementTrackingService GetActiveStatementTrackingService() => _workspaceProvider.Value.Workspace.Services.GetRequiredService<IActiveStatementTrackingService>(); private RemoteDebuggingSessionProxy GetDebuggingSession() { var debuggingSession = _debuggingSession; Contract.ThrowIfNull(debuggingSession); return debuggingSession; } /// <summary> /// Called by the debugger when a debugging session starts and managed debugging is being used. /// </summary> public async Task StartDebuggingAsync(DebugSessionFlags flags, CancellationToken cancellationToken) { GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run); _disabled = (flags & DebugSessionFlags.EditAndContinueDisabled) != 0; if (_disabled) { return; } try { var workspace = _workspaceProvider.Value.Workspace; var solution = GetCurrentCompileTimeSolution(); var openedDocumentIds = workspace.GetOpenDocumentIds().ToImmutableArray(); var proxy = new RemoteEditAndContinueServiceProxy(workspace); _debuggingSession = await proxy.StartDebuggingSessionAsync( solution, _debuggerService.Value, captureMatchingDocuments: openedDocumentIds, captureAllMatchingDocuments: false, reportDiagnostics: true, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { } // the service failed, error has been reported - disable further operations _disabled = _debuggingSession == null; } public async Task EnterBreakStateAsync(CancellationToken cancellationToken) { GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Break); if (_disabled) { return; } var solution = GetCurrentCompileTimeSolution(); var session = GetDebuggingSession(); try { await session.BreakStateChangedAsync(_diagnosticService, inBreakState: true, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { _disabled = true; return; } // Start tracking after we entered break state so that break-state session is active. // This is potentially costly operation but entering break state is non-blocking so it should be ok to await. await GetActiveStatementTrackingService().StartTrackingAsync(solution, session, cancellationToken).ConfigureAwait(false); } public async Task ExitBreakStateAsync(CancellationToken cancellationToken) { GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run); if (_disabled) { return; } var session = GetDebuggingSession(); try { await session.BreakStateChangedAsync(_diagnosticService, inBreakState: false, cancellationToken).ConfigureAwait(false); GetActiveStatementTrackingService().EndTracking(); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { _disabled = true; return; } } public async Task CommitUpdatesAsync(CancellationToken cancellationToken) { try { Contract.ThrowIfTrue(_disabled); await GetDebuggingSession().CommitSolutionUpdateAsync(_diagnosticService, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } public async Task DiscardUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { return; } try { await GetDebuggingSession().DiscardSolutionUpdateAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } public async Task StopDebuggingAsync(CancellationToken cancellationToken) { GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Design); if (_disabled) { return; } try { var solution = GetCurrentCompileTimeSolution(); await GetDebuggingSession().EndDebuggingSessionAsync(solution, _diagnosticUpdateSource, _diagnosticService, cancellationToken).ConfigureAwait(false); _debuggingSession = null; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { _disabled = true; } } private ActiveStatementSpanProvider GetActiveStatementSpanProvider(Solution solution) { var service = GetActiveStatementTrackingService(); return new((documentId, filePath, cancellationToken) => service.GetSpansAsync(solution, documentId, filePath, cancellationToken)); } /// <summary> /// Returns true if any changes have been made to the source since the last changes had been applied. /// </summary> public async Task<bool> HasChangesAsync(string? sourceFilePath, CancellationToken cancellationToken) { try { var debuggingSession = _debuggingSession; if (debuggingSession == null) { return false; } var solution = GetCurrentCompileTimeSolution(); var activeStatementSpanProvider = GetActiveStatementSpanProvider(solution); return await debuggingSession.HasChangesAsync(solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return true; } } public async Task<ManagedModuleUpdates> GetManagedModuleUpdatesAsync(CancellationToken cancellationToken) { try { var solution = GetCurrentCompileTimeSolution(); var activeStatementSpanProvider = GetActiveStatementSpanProvider(solution); var (updates, _, _) = await GetDebuggingSession().EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, _diagnosticService, _diagnosticUpdateSource, cancellationToken).ConfigureAwait(false); return updates; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty); } } public async Task<SourceSpan?> GetCurrentActiveStatementPositionAsync(ManagedInstructionId instruction, CancellationToken cancellationToken) { try { var solution = GetCurrentCompileTimeSolution(); var activeStatementTrackingService = GetActiveStatementTrackingService(); var activeStatementSpanProvider = new ActiveStatementSpanProvider((documentId, filePath, cancellationToken) => activeStatementTrackingService.GetSpansAsync(solution, documentId, filePath, cancellationToken)); var span = await GetDebuggingSession().GetCurrentActiveStatementPositionAsync(solution, activeStatementSpanProvider, instruction, cancellationToken).ConfigureAwait(false); return span?.ToSourceSpan(); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } public async Task<bool?> IsActiveStatementInExceptionRegionAsync(ManagedInstructionId instruction, CancellationToken cancellationToken) { try { var solution = GetCurrentCompileTimeSolution(); return await GetDebuggingSession().IsActiveStatementInExceptionRegionAsync(solution, instruction, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue { [Shared] [Export(typeof(IManagedEditAndContinueLanguageService))] [ExportMetadata("UIContext", EditAndContinueUIContext.EncCapableProjectExistsInWorkspaceUIContextString)] internal sealed class ManagedEditAndContinueLanguageService : IManagedEditAndContinueLanguageService { private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly EditAndContinueDiagnosticUpdateSource _diagnosticUpdateSource; private readonly Lazy<IManagedEditAndContinueDebuggerService> _debuggerService; private readonly Lazy<IHostWorkspaceProvider> _workspaceProvider; private RemoteDebuggingSessionProxy? _debuggingSession; private bool _disabled; /// <summary> /// Import <see cref="IHostWorkspaceProvider"/> and <see cref="IManagedEditAndContinueDebuggerService"/> lazily so that the host does not need to implement them /// unless it implements debugger components. /// </summary> [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ManagedEditAndContinueLanguageService( Lazy<IHostWorkspaceProvider> workspaceProvider, Lazy<IManagedEditAndContinueDebuggerService> debuggerService, IDiagnosticAnalyzerService diagnosticService, EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource) { _workspaceProvider = workspaceProvider; _debuggerService = debuggerService; _diagnosticService = diagnosticService; _diagnosticUpdateSource = diagnosticUpdateSource; } private Solution GetCurrentCompileTimeSolution() { var workspace = _workspaceProvider.Value.Workspace; return workspace.Services.GetRequiredService<ICompileTimeSolutionProvider>().GetCompileTimeSolution(workspace.CurrentSolution); } private IDebuggingWorkspaceService GetDebuggingService() => _workspaceProvider.Value.Workspace.Services.GetRequiredService<IDebuggingWorkspaceService>(); private IActiveStatementTrackingService GetActiveStatementTrackingService() => _workspaceProvider.Value.Workspace.Services.GetRequiredService<IActiveStatementTrackingService>(); private RemoteDebuggingSessionProxy GetDebuggingSession() { var debuggingSession = _debuggingSession; Contract.ThrowIfNull(debuggingSession); return debuggingSession; } /// <summary> /// Called by the debugger when a debugging session starts and managed debugging is being used. /// </summary> public async Task StartDebuggingAsync(DebugSessionFlags flags, CancellationToken cancellationToken) { GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run); _disabled = (flags & DebugSessionFlags.EditAndContinueDisabled) != 0; if (_disabled) { return; } try { var workspace = _workspaceProvider.Value.Workspace; var solution = GetCurrentCompileTimeSolution(); var openedDocumentIds = workspace.GetOpenDocumentIds().ToImmutableArray(); var proxy = new RemoteEditAndContinueServiceProxy(workspace); _debuggingSession = await proxy.StartDebuggingSessionAsync( solution, _debuggerService.Value, captureMatchingDocuments: openedDocumentIds, captureAllMatchingDocuments: false, reportDiagnostics: true, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { } // the service failed, error has been reported - disable further operations _disabled = _debuggingSession == null; } public async Task EnterBreakStateAsync(CancellationToken cancellationToken) { GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Break); if (_disabled) { return; } var solution = GetCurrentCompileTimeSolution(); var session = GetDebuggingSession(); try { await session.BreakStateChangedAsync(_diagnosticService, inBreakState: true, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { _disabled = true; return; } // Start tracking after we entered break state so that break-state session is active. // This is potentially costly operation but entering break state is non-blocking so it should be ok to await. await GetActiveStatementTrackingService().StartTrackingAsync(solution, session, cancellationToken).ConfigureAwait(false); } public async Task ExitBreakStateAsync(CancellationToken cancellationToken) { GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run); if (_disabled) { return; } var session = GetDebuggingSession(); try { await session.BreakStateChangedAsync(_diagnosticService, inBreakState: false, cancellationToken).ConfigureAwait(false); GetActiveStatementTrackingService().EndTracking(); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { _disabled = true; return; } } public async Task CommitUpdatesAsync(CancellationToken cancellationToken) { try { Contract.ThrowIfTrue(_disabled); await GetDebuggingSession().CommitSolutionUpdateAsync(_diagnosticService, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } public async Task DiscardUpdatesAsync(CancellationToken cancellationToken) { if (_disabled) { return; } try { await GetDebuggingSession().DiscardSolutionUpdateAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } public async Task StopDebuggingAsync(CancellationToken cancellationToken) { GetDebuggingService().OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Design); if (_disabled) { return; } try { var solution = GetCurrentCompileTimeSolution(); await GetDebuggingSession().EndDebuggingSessionAsync(solution, _diagnosticUpdateSource, _diagnosticService, cancellationToken).ConfigureAwait(false); _debuggingSession = null; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { _disabled = true; } } private ActiveStatementSpanProvider GetActiveStatementSpanProvider(Solution solution) { var service = GetActiveStatementTrackingService(); return new((documentId, filePath, cancellationToken) => service.GetSpansAsync(solution, documentId, filePath, cancellationToken)); } /// <summary> /// Returns true if any changes have been made to the source since the last changes had been applied. /// </summary> public async Task<bool> HasChangesAsync(string? sourceFilePath, CancellationToken cancellationToken) { try { var debuggingSession = _debuggingSession; if (debuggingSession == null) { return false; } var solution = GetCurrentCompileTimeSolution(); var activeStatementSpanProvider = GetActiveStatementSpanProvider(solution); return await debuggingSession.HasChangesAsync(solution, activeStatementSpanProvider, sourceFilePath, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return true; } } public async Task<ManagedModuleUpdates> GetManagedModuleUpdatesAsync(CancellationToken cancellationToken) { try { var solution = GetCurrentCompileTimeSolution(); var activeStatementSpanProvider = GetActiveStatementSpanProvider(solution); var (updates, _, _) = await GetDebuggingSession().EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, _diagnosticService, _diagnosticUpdateSource, cancellationToken).ConfigureAwait(false); return updates; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty); } } public async Task<SourceSpan?> GetCurrentActiveStatementPositionAsync(ManagedInstructionId instruction, CancellationToken cancellationToken) { try { var solution = GetCurrentCompileTimeSolution(); var activeStatementTrackingService = GetActiveStatementTrackingService(); var activeStatementSpanProvider = new ActiveStatementSpanProvider((documentId, filePath, cancellationToken) => activeStatementTrackingService.GetSpansAsync(solution, documentId, filePath, cancellationToken)); var span = await GetDebuggingSession().GetCurrentActiveStatementPositionAsync(solution, activeStatementSpanProvider, instruction, cancellationToken).ConfigureAwait(false); return span?.ToSourceSpan(); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } public async Task<bool?> IsActiveStatementInExceptionRegionAsync(ManagedInstructionId instruction, CancellationToken cancellationToken) { try { var solution = GetCurrentCompileTimeSolution(); return await GetDebuggingSession().IsActiveStatementInExceptionRegionAsync(solution, instruction, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/CSharp/Portable/InitializeParameter/CSharpInitializeMemberFromParameterCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.InitializeParameter; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.CSharp.InitializeParameter { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.InitializeMemberFromParameter), Shared] [ExtensionOrder(Before = nameof(CSharpAddParameterCheckCodeRefactoringProvider))] [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.Wrapping)] internal class CSharpInitializeMemberFromParameterCodeRefactoringProvider : AbstractInitializeMemberFromParameterCodeRefactoringProvider< BaseTypeDeclarationSyntax, ParameterSyntax, StatementSyntax, ExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpInitializeMemberFromParameterCodeRefactoringProvider() { } protected override bool IsFunctionDeclaration(SyntaxNode node) => InitializeParameterHelpers.IsFunctionDeclaration(node); protected override SyntaxNode TryGetLastStatement(IBlockOperation blockStatementOpt) => InitializeParameterHelpers.TryGetLastStatement(blockStatementOpt); protected override void InsertStatement(SyntaxEditor editor, SyntaxNode functionDeclaration, bool returnsVoid, SyntaxNode statementToAddAfterOpt, StatementSyntax statement) => InitializeParameterHelpers.InsertStatement(editor, functionDeclaration, returnsVoid, statementToAddAfterOpt, statement); protected override bool IsImplicitConversion(Compilation compilation, ITypeSymbol source, ITypeSymbol destination) => InitializeParameterHelpers.IsImplicitConversion(compilation, source, destination); // Fields are always private by default in C#. protected override Accessibility DetermineDefaultFieldAccessibility(INamedTypeSymbol containingType) => Accessibility.Private; // Properties are always private by default in C#. protected override Accessibility DetermineDefaultPropertyAccessibility() => Accessibility.Private; protected override SyntaxNode GetBody(SyntaxNode functionDeclaration) => InitializeParameterHelpers.GetBody(functionDeclaration); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.InitializeParameter; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.CSharp.InitializeParameter { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.InitializeMemberFromParameter), Shared] [ExtensionOrder(Before = nameof(CSharpAddParameterCheckCodeRefactoringProvider))] [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.Wrapping)] internal class CSharpInitializeMemberFromParameterCodeRefactoringProvider : AbstractInitializeMemberFromParameterCodeRefactoringProvider< BaseTypeDeclarationSyntax, ParameterSyntax, StatementSyntax, ExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpInitializeMemberFromParameterCodeRefactoringProvider() { } protected override bool IsFunctionDeclaration(SyntaxNode node) => InitializeParameterHelpers.IsFunctionDeclaration(node); protected override SyntaxNode TryGetLastStatement(IBlockOperation blockStatementOpt) => InitializeParameterHelpers.TryGetLastStatement(blockStatementOpt); protected override void InsertStatement(SyntaxEditor editor, SyntaxNode functionDeclaration, bool returnsVoid, SyntaxNode statementToAddAfterOpt, StatementSyntax statement) => InitializeParameterHelpers.InsertStatement(editor, functionDeclaration, returnsVoid, statementToAddAfterOpt, statement); protected override bool IsImplicitConversion(Compilation compilation, ITypeSymbol source, ITypeSymbol destination) => InitializeParameterHelpers.IsImplicitConversion(compilation, source, destination); // Fields are always private by default in C#. protected override Accessibility DetermineDefaultFieldAccessibility(INamedTypeSymbol containingType) => Accessibility.Private; // Properties are always private by default in C#. protected override Accessibility DetermineDefaultPropertyAccessibility() => Accessibility.Private; protected override SyntaxNode GetBody(SyntaxNode functionDeclaration) => InitializeParameterHelpers.GetBody(functionDeclaration); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/CSharpTest/ConvertBetweenRegularAndVerbatimString/ConvertBetweenRegularAndVerbatimStringTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.ConvertBetweenRegularAndVerbatimString; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertBetweenRegularAndVerbatimString { public class ConvertBetweenRegularAndVerbatimStringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new ConvertBetweenRegularAndVerbatimStringCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task EmptyRegularString() { await TestMissingAsync(@" class Test { void Method() { var v = ""[||]""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithMissingCloseQuote() { await TestMissingAsync(@" class Test { void Method() { var v = ""[||]; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task VerbatimStringWithMissingCloseQuote() { await TestMissingAsync(@" class Test { void Method() { var v = @""[||]; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task EmptyVerbatimString() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = @""[||]""; } } ", @" class Test { void Method() { var v = """"; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task TestLeadingAndTrailingTrivia() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = // leading @""[||]"" /* trailing */; } } ", @" class Test { void Method() { var v = // leading """" /* trailing */; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithBasicText() { await TestMissingAsync(@" class Test { void Method() { var v = ""[||]a""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task VerbatimStringWithBasicText() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = @""[||]a""; } } ", @" class Test { void Method() { var v = ""a""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithUnicodeEscape() { await TestMissingAsync(@" class Test { void Method() { var v = ""[||]\u0001""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithEscapedNewLine() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = ""[||]a\r\nb""; } } ", @" class Test { void Method() { var v = @""a b""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task VerbatimStringWithNewLine() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = @""[||]a b""; } } ", @" class Test { void Method() { var v = ""a\r\nb""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithEscapedNull() { await TestMissingAsync(@" class Test { void Method() { var v = ""[||]a\0b""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithEscapedQuote() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = ""[||]a\""b""; } } ", @" class Test { void Method() { var v = @""a""""b""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task VerbatimStringWithEscapedQuote() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = @""[||]a""""b""; } } ", @" class Test { void Method() { var v = ""a\""b""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task DoNotEscapeCurlyBracesInRegularString() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = ""[||]a\r\n{1}""; } } ", @" class Test { void Method() { var v = @""a {1}""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task DoNotEscapeCurlyBracesInVerbatimString() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = @""[||]a {1}""; } } ", @" class Test { void Method() { var v = ""a\r\n{1}""; } } "); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.ConvertBetweenRegularAndVerbatimString; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertBetweenRegularAndVerbatimString { public class ConvertBetweenRegularAndVerbatimStringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new ConvertBetweenRegularAndVerbatimStringCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task EmptyRegularString() { await TestMissingAsync(@" class Test { void Method() { var v = ""[||]""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithMissingCloseQuote() { await TestMissingAsync(@" class Test { void Method() { var v = ""[||]; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task VerbatimStringWithMissingCloseQuote() { await TestMissingAsync(@" class Test { void Method() { var v = @""[||]; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task EmptyVerbatimString() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = @""[||]""; } } ", @" class Test { void Method() { var v = """"; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task TestLeadingAndTrailingTrivia() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = // leading @""[||]"" /* trailing */; } } ", @" class Test { void Method() { var v = // leading """" /* trailing */; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithBasicText() { await TestMissingAsync(@" class Test { void Method() { var v = ""[||]a""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task VerbatimStringWithBasicText() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = @""[||]a""; } } ", @" class Test { void Method() { var v = ""a""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithUnicodeEscape() { await TestMissingAsync(@" class Test { void Method() { var v = ""[||]\u0001""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithEscapedNewLine() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = ""[||]a\r\nb""; } } ", @" class Test { void Method() { var v = @""a b""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task VerbatimStringWithNewLine() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = @""[||]a b""; } } ", @" class Test { void Method() { var v = ""a\r\nb""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithEscapedNull() { await TestMissingAsync(@" class Test { void Method() { var v = ""[||]a\0b""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task RegularStringWithEscapedQuote() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = ""[||]a\""b""; } } ", @" class Test { void Method() { var v = @""a""""b""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task VerbatimStringWithEscapedQuote() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = @""[||]a""""b""; } } ", @" class Test { void Method() { var v = ""a\""b""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task DoNotEscapeCurlyBracesInRegularString() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = ""[||]a\r\n{1}""; } } ", @" class Test { void Method() { var v = @""a {1}""; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertBetweenRegularAndVerbatimString)] public async Task DoNotEscapeCurlyBracesInVerbatimString() { await TestInRegularAndScript1Async(@" class Test { void Method() { var v = @""[||]a {1}""; } } ", @" class Test { void Method() { var v = ""a\r\n{1}""; } } "); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/CSharp/Portable/Simplification/Simplifiers/AbstractCSharpSimplifier.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Simplification.Simplifiers; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers { /// <summary> /// Contains helpers used by several simplifier subclasses. /// </summary> internal abstract class AbstractCSharpSimplifier<TSyntax, TSimplifiedSyntax> : AbstractSimplifier<TSyntax, TSimplifiedSyntax> where TSyntax : SyntaxNode where TSimplifiedSyntax : SyntaxNode { /// <summary> /// Returns the predefined keyword kind for a given <see cref="SpecialType"/>. /// </summary> /// <param name="specialType">The <see cref="SpecialType"/> of this type.</param> /// <returns>The keyword kind for a given special type, or SyntaxKind.None if the type name is not a predefined type.</returns> protected static SyntaxKind GetPredefinedKeywordKind(SpecialType specialType) => specialType switch { SpecialType.System_Boolean => SyntaxKind.BoolKeyword, SpecialType.System_Byte => SyntaxKind.ByteKeyword, SpecialType.System_SByte => SyntaxKind.SByteKeyword, SpecialType.System_Int32 => SyntaxKind.IntKeyword, SpecialType.System_UInt32 => SyntaxKind.UIntKeyword, SpecialType.System_Int16 => SyntaxKind.ShortKeyword, SpecialType.System_UInt16 => SyntaxKind.UShortKeyword, SpecialType.System_Int64 => SyntaxKind.LongKeyword, SpecialType.System_UInt64 => SyntaxKind.ULongKeyword, SpecialType.System_Single => SyntaxKind.FloatKeyword, SpecialType.System_Double => SyntaxKind.DoubleKeyword, SpecialType.System_Decimal => SyntaxKind.DecimalKeyword, SpecialType.System_String => SyntaxKind.StringKeyword, SpecialType.System_Char => SyntaxKind.CharKeyword, SpecialType.System_Object => SyntaxKind.ObjectKeyword, SpecialType.System_Void => SyntaxKind.VoidKeyword, _ => SyntaxKind.None, }; [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Most trees do not have using alias directives, so avoid the expensive " + nameof(CSharpExtensions.GetSymbolInfo) + " call for this case.")] protected static bool TryReplaceExpressionWithAlias( ExpressionSyntax node, SemanticModel semanticModel, ISymbol symbol, CancellationToken cancellationToken, out IAliasSymbol aliasReplacement) { aliasReplacement = null; if (!IsAliasReplaceableExpression(node)) return false; // Avoid the TryReplaceWithAlias algorithm if the tree has no using alias directives. Since the input node // might be a speculative node (not fully rooted in a tree), we use the original semantic model to find the // equivalent node in the original tree, and from there determine if the tree has any using alias // directives. var originalModel = semanticModel.GetOriginalSemanticModel(); // Perf: We are only using the syntax tree root in a fast-path syntax check. If the root is not readily // available, it is fine to continue through the normal algorithm. if (originalModel.SyntaxTree.TryGetRoot(out var root)) { if (!HasUsingAliasDirective(root)) { return false; } } // If the Symbol is a constructor get its containing type if (symbol.IsConstructor()) { symbol = symbol.ContainingType; } if (node is QualifiedNameSyntax || node is AliasQualifiedNameSyntax) { SyntaxAnnotation aliasAnnotationInfo = null; // The following condition checks if the user has used alias in the original code and // if so the expression is replaced with the Alias if (node is QualifiedNameSyntax qualifiedNameNode) { if (qualifiedNameNode.Right.Identifier.HasAnnotations(AliasAnnotation.Kind)) { aliasAnnotationInfo = qualifiedNameNode.Right.Identifier.GetAnnotations(AliasAnnotation.Kind).Single(); } } if (node is AliasQualifiedNameSyntax aliasQualifiedNameNode) { if (aliasQualifiedNameNode.Name.Identifier.HasAnnotations(AliasAnnotation.Kind)) { aliasAnnotationInfo = aliasQualifiedNameNode.Name.Identifier.GetAnnotations(AliasAnnotation.Kind).Single(); } } if (aliasAnnotationInfo != null) { var aliasName = AliasAnnotation.GetAliasName(aliasAnnotationInfo); var aliasIdentifier = SyntaxFactory.IdentifierName(aliasName); var aliasTypeInfo = semanticModel.GetSpeculativeAliasInfo(node.SpanStart, aliasIdentifier, SpeculativeBindingOption.BindAsTypeOrNamespace); if (aliasTypeInfo != null) { aliasReplacement = aliasTypeInfo; return ValidateAliasForTarget(aliasReplacement, semanticModel, node, symbol); } } } if (node.Kind() == SyntaxKind.IdentifierName && semanticModel.GetAliasInfo((IdentifierNameSyntax)node, cancellationToken) != null) { return false; } // an alias can only replace a type or namespace if (symbol == null || (symbol.Kind != SymbolKind.Namespace && symbol.Kind != SymbolKind.NamedType)) { return false; } var preferAliasToQualifiedName = true; if (node is QualifiedNameSyntax qualifiedName) { if (!qualifiedName.Right.HasAnnotation(Simplifier.SpecialTypeAnnotation)) { var type = semanticModel.GetTypeInfo(node, cancellationToken).Type; if (type != null) { var keywordKind = GetPredefinedKeywordKind(type.SpecialType); if (keywordKind != SyntaxKind.None) { preferAliasToQualifiedName = false; } } } } if (node is AliasQualifiedNameSyntax aliasQualifiedNameSyntax) { if (!aliasQualifiedNameSyntax.Name.HasAnnotation(Simplifier.SpecialTypeAnnotation)) { var type = semanticModel.GetTypeInfo(node, cancellationToken).Type; if (type != null) { var keywordKind = GetPredefinedKeywordKind(type.SpecialType); if (keywordKind != SyntaxKind.None) { preferAliasToQualifiedName = false; } } } } aliasReplacement = GetAliasForSymbol((INamespaceOrTypeSymbol)symbol, node.GetFirstToken(), semanticModel, cancellationToken); if (aliasReplacement != null && preferAliasToQualifiedName) { return ValidateAliasForTarget(aliasReplacement, semanticModel, node, symbol); } return false; } private static bool IsAliasReplaceableExpression(ExpressionSyntax expression) { var current = expression; while (current.IsKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax currentMember)) { current = currentMember.Expression; continue; } return current.IsKind(SyntaxKind.AliasQualifiedName, SyntaxKind.IdentifierName, SyntaxKind.GenericName, SyntaxKind.QualifiedName); } private static bool HasUsingAliasDirective(SyntaxNode syntax) { var (usings, members) = syntax switch { BaseNamespaceDeclarationSyntax ns => (ns.Usings, ns.Members), CompilationUnitSyntax compilationUnit => (compilationUnit.Usings, compilationUnit.Members), _ => default, }; foreach (var usingDirective in usings) { if (usingDirective.Alias != null) return true; } foreach (var member in members) { if (HasUsingAliasDirective(member)) return true; } return false; } // We must verify that the alias actually binds back to the thing it's aliasing. // It's possible there's another symbol with the same name as the alias that binds // first private static bool ValidateAliasForTarget(IAliasSymbol aliasReplacement, SemanticModel semanticModel, ExpressionSyntax node, ISymbol symbol) { var aliasName = aliasReplacement.Name; // If we're the argument of a nameof(X.Y) call, then we can't simplify to an // alias unless the alias has the same name as us (i.e. 'Y'). if (node.IsNameOfArgumentExpression()) { var nameofValueOpt = semanticModel.GetConstantValue(node.Parent.Parent.Parent); if (!nameofValueOpt.HasValue) { return false; } if (nameofValueOpt.Value is string existingVal && existingVal != aliasName) { return false; } } var boundSymbols = semanticModel.LookupNamespacesAndTypes(node.SpanStart, name: aliasName); if (boundSymbols.Length == 1) { if (boundSymbols[0] is IAliasSymbol && aliasReplacement.Target.Equals(symbol)) { return true; } } return false; } private static IAliasSymbol GetAliasForSymbol(INamespaceOrTypeSymbol symbol, SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken) { var originalSemanticModel = semanticModel.GetOriginalSemanticModel(); if (!originalSemanticModel.SyntaxTree.HasCompilationUnitRoot) { return null; } var namespaceId = GetNamespaceIdForAliasSearch(semanticModel, token, cancellationToken); if (namespaceId < 0) { return null; } if (!AliasSymbolCache.TryGetAliasSymbol(originalSemanticModel, namespaceId, symbol, out var aliasSymbol)) { // add cache AliasSymbolCache.AddAliasSymbols(originalSemanticModel, namespaceId, semanticModel.LookupNamespacesAndTypes(token.SpanStart).OfType<IAliasSymbol>()); // retry AliasSymbolCache.TryGetAliasSymbol(originalSemanticModel, namespaceId, symbol, out aliasSymbol); } return aliasSymbol; } private static int GetNamespaceIdForAliasSearch(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) { var startNode = GetStartNodeForNamespaceId(semanticModel, token, cancellationToken); if (!startNode.SyntaxTree.HasCompilationUnitRoot) { return -1; } // NOTE: If we're currently in a block of usings, then we want to collect the // aliases that are higher up than this block. Using aliases declared in a block of // usings are not usable from within that same block. var usingDirective = startNode.GetAncestorOrThis<UsingDirectiveSyntax>(); if (usingDirective != null) { startNode = usingDirective.Parent.Parent; if (startNode == null) { return -1; } } // check whether I am under a namespace var @namespace = startNode.GetAncestorOrThis<BaseNamespaceDeclarationSyntax>(); if (@namespace != null) { // since we have node inside of the root, root should be already there // search for namespace id should be quite cheap since normally there should be // only a few namespace defined in a source file if it is not 1. that is why it is // not cached. var startIndex = 1; return GetNamespaceId(startNode.SyntaxTree.GetRoot(cancellationToken), @namespace, ref startIndex); } // no namespace, under compilation unit directly return 0; } private static SyntaxNode GetStartNodeForNamespaceId(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) { if (!semanticModel.IsSpeculativeSemanticModel) { return token.Parent; } var originalSemanticMode = semanticModel.GetOriginalSemanticModel(); token = originalSemanticMode.SyntaxTree.GetRoot(cancellationToken).FindToken(semanticModel.OriginalPositionForSpeculation); return token.Parent; } private static int GetNamespaceId(SyntaxNode container, BaseNamespaceDeclarationSyntax target, ref int index) => container switch { CompilationUnitSyntax compilation => GetNamespaceId(compilation.Members, target, ref index), BaseNamespaceDeclarationSyntax @namespace => GetNamespaceId(@namespace.Members, target, ref index), _ => throw ExceptionUtilities.UnexpectedValue(container) }; private static int GetNamespaceId(SyntaxList<MemberDeclarationSyntax> members, BaseNamespaceDeclarationSyntax target, ref int index) { foreach (var member in members) { if (member is not BaseNamespaceDeclarationSyntax childNamespace) continue; if (childNamespace == target) return index; index++; var result = GetNamespaceId(childNamespace, target, ref index); if (result > 0) return result; } return -1; } protected static TypeSyntax CreatePredefinedTypeSyntax(ExpressionSyntax expression, SyntaxKind keywordKind) => SyntaxFactory.PredefinedType(SyntaxFactory.Token(expression.GetLeadingTrivia(), keywordKind, expression.GetTrailingTrivia())); protected static bool InsideNameOfExpression(ExpressionSyntax expression, SemanticModel semanticModel) { var nameOfInvocationExpr = expression.FirstAncestorOrSelf<InvocationExpressionSyntax>( invocationExpr => { return invocationExpr.Expression is IdentifierNameSyntax identifierName && identifierName.Identifier.Text == "nameof" && semanticModel.GetConstantValue(invocationExpr).HasValue && semanticModel.GetTypeInfo(invocationExpr).Type.SpecialType == SpecialType.System_String; }); return nameOfInvocationExpr != null; } protected static bool PreferPredefinedTypeKeywordInMemberAccess(ExpressionSyntax expression, OptionSet optionSet, SemanticModel semanticModel) { if (!SimplificationHelpers.PreferPredefinedTypeKeywordInMemberAccess(optionSet, semanticModel.Language)) return false; return (expression.IsDirectChildOfMemberAccessExpression() || expression.InsideCrefReference()) && !InsideNameOfExpression(expression, semanticModel); } protected static bool WillConflictWithExistingLocal( ExpressionSyntax expression, ExpressionSyntax simplifiedNode, SemanticModel semanticModel) { if (simplifiedNode is IdentifierNameSyntax identifierName && !SyntaxFacts.IsInNamespaceOrTypeContext(expression)) { var symbols = semanticModel.LookupSymbols(expression.SpanStart, name: identifierName.Identifier.ValueText); return symbols.Any(s => s is ILocalSymbol); } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Simplification.Simplifiers; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers { /// <summary> /// Contains helpers used by several simplifier subclasses. /// </summary> internal abstract class AbstractCSharpSimplifier<TSyntax, TSimplifiedSyntax> : AbstractSimplifier<TSyntax, TSimplifiedSyntax> where TSyntax : SyntaxNode where TSimplifiedSyntax : SyntaxNode { /// <summary> /// Returns the predefined keyword kind for a given <see cref="SpecialType"/>. /// </summary> /// <param name="specialType">The <see cref="SpecialType"/> of this type.</param> /// <returns>The keyword kind for a given special type, or SyntaxKind.None if the type name is not a predefined type.</returns> protected static SyntaxKind GetPredefinedKeywordKind(SpecialType specialType) => specialType switch { SpecialType.System_Boolean => SyntaxKind.BoolKeyword, SpecialType.System_Byte => SyntaxKind.ByteKeyword, SpecialType.System_SByte => SyntaxKind.SByteKeyword, SpecialType.System_Int32 => SyntaxKind.IntKeyword, SpecialType.System_UInt32 => SyntaxKind.UIntKeyword, SpecialType.System_Int16 => SyntaxKind.ShortKeyword, SpecialType.System_UInt16 => SyntaxKind.UShortKeyword, SpecialType.System_Int64 => SyntaxKind.LongKeyword, SpecialType.System_UInt64 => SyntaxKind.ULongKeyword, SpecialType.System_Single => SyntaxKind.FloatKeyword, SpecialType.System_Double => SyntaxKind.DoubleKeyword, SpecialType.System_Decimal => SyntaxKind.DecimalKeyword, SpecialType.System_String => SyntaxKind.StringKeyword, SpecialType.System_Char => SyntaxKind.CharKeyword, SpecialType.System_Object => SyntaxKind.ObjectKeyword, SpecialType.System_Void => SyntaxKind.VoidKeyword, _ => SyntaxKind.None, }; [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Most trees do not have using alias directives, so avoid the expensive " + nameof(CSharpExtensions.GetSymbolInfo) + " call for this case.")] protected static bool TryReplaceExpressionWithAlias( ExpressionSyntax node, SemanticModel semanticModel, ISymbol symbol, CancellationToken cancellationToken, out IAliasSymbol aliasReplacement) { aliasReplacement = null; if (!IsAliasReplaceableExpression(node)) return false; // Avoid the TryReplaceWithAlias algorithm if the tree has no using alias directives. Since the input node // might be a speculative node (not fully rooted in a tree), we use the original semantic model to find the // equivalent node in the original tree, and from there determine if the tree has any using alias // directives. var originalModel = semanticModel.GetOriginalSemanticModel(); // Perf: We are only using the syntax tree root in a fast-path syntax check. If the root is not readily // available, it is fine to continue through the normal algorithm. if (originalModel.SyntaxTree.TryGetRoot(out var root)) { if (!HasUsingAliasDirective(root)) { return false; } } // If the Symbol is a constructor get its containing type if (symbol.IsConstructor()) { symbol = symbol.ContainingType; } if (node is QualifiedNameSyntax || node is AliasQualifiedNameSyntax) { SyntaxAnnotation aliasAnnotationInfo = null; // The following condition checks if the user has used alias in the original code and // if so the expression is replaced with the Alias if (node is QualifiedNameSyntax qualifiedNameNode) { if (qualifiedNameNode.Right.Identifier.HasAnnotations(AliasAnnotation.Kind)) { aliasAnnotationInfo = qualifiedNameNode.Right.Identifier.GetAnnotations(AliasAnnotation.Kind).Single(); } } if (node is AliasQualifiedNameSyntax aliasQualifiedNameNode) { if (aliasQualifiedNameNode.Name.Identifier.HasAnnotations(AliasAnnotation.Kind)) { aliasAnnotationInfo = aliasQualifiedNameNode.Name.Identifier.GetAnnotations(AliasAnnotation.Kind).Single(); } } if (aliasAnnotationInfo != null) { var aliasName = AliasAnnotation.GetAliasName(aliasAnnotationInfo); var aliasIdentifier = SyntaxFactory.IdentifierName(aliasName); var aliasTypeInfo = semanticModel.GetSpeculativeAliasInfo(node.SpanStart, aliasIdentifier, SpeculativeBindingOption.BindAsTypeOrNamespace); if (aliasTypeInfo != null) { aliasReplacement = aliasTypeInfo; return ValidateAliasForTarget(aliasReplacement, semanticModel, node, symbol); } } } if (node.Kind() == SyntaxKind.IdentifierName && semanticModel.GetAliasInfo((IdentifierNameSyntax)node, cancellationToken) != null) { return false; } // an alias can only replace a type or namespace if (symbol == null || (symbol.Kind != SymbolKind.Namespace && symbol.Kind != SymbolKind.NamedType)) { return false; } var preferAliasToQualifiedName = true; if (node is QualifiedNameSyntax qualifiedName) { if (!qualifiedName.Right.HasAnnotation(Simplifier.SpecialTypeAnnotation)) { var type = semanticModel.GetTypeInfo(node, cancellationToken).Type; if (type != null) { var keywordKind = GetPredefinedKeywordKind(type.SpecialType); if (keywordKind != SyntaxKind.None) { preferAliasToQualifiedName = false; } } } } if (node is AliasQualifiedNameSyntax aliasQualifiedNameSyntax) { if (!aliasQualifiedNameSyntax.Name.HasAnnotation(Simplifier.SpecialTypeAnnotation)) { var type = semanticModel.GetTypeInfo(node, cancellationToken).Type; if (type != null) { var keywordKind = GetPredefinedKeywordKind(type.SpecialType); if (keywordKind != SyntaxKind.None) { preferAliasToQualifiedName = false; } } } } aliasReplacement = GetAliasForSymbol((INamespaceOrTypeSymbol)symbol, node.GetFirstToken(), semanticModel, cancellationToken); if (aliasReplacement != null && preferAliasToQualifiedName) { return ValidateAliasForTarget(aliasReplacement, semanticModel, node, symbol); } return false; } private static bool IsAliasReplaceableExpression(ExpressionSyntax expression) { var current = expression; while (current.IsKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax currentMember)) { current = currentMember.Expression; continue; } return current.IsKind(SyntaxKind.AliasQualifiedName, SyntaxKind.IdentifierName, SyntaxKind.GenericName, SyntaxKind.QualifiedName); } private static bool HasUsingAliasDirective(SyntaxNode syntax) { var (usings, members) = syntax switch { BaseNamespaceDeclarationSyntax ns => (ns.Usings, ns.Members), CompilationUnitSyntax compilationUnit => (compilationUnit.Usings, compilationUnit.Members), _ => default, }; foreach (var usingDirective in usings) { if (usingDirective.Alias != null) return true; } foreach (var member in members) { if (HasUsingAliasDirective(member)) return true; } return false; } // We must verify that the alias actually binds back to the thing it's aliasing. // It's possible there's another symbol with the same name as the alias that binds // first private static bool ValidateAliasForTarget(IAliasSymbol aliasReplacement, SemanticModel semanticModel, ExpressionSyntax node, ISymbol symbol) { var aliasName = aliasReplacement.Name; // If we're the argument of a nameof(X.Y) call, then we can't simplify to an // alias unless the alias has the same name as us (i.e. 'Y'). if (node.IsNameOfArgumentExpression()) { var nameofValueOpt = semanticModel.GetConstantValue(node.Parent.Parent.Parent); if (!nameofValueOpt.HasValue) { return false; } if (nameofValueOpt.Value is string existingVal && existingVal != aliasName) { return false; } } var boundSymbols = semanticModel.LookupNamespacesAndTypes(node.SpanStart, name: aliasName); if (boundSymbols.Length == 1) { if (boundSymbols[0] is IAliasSymbol && aliasReplacement.Target.Equals(symbol)) { return true; } } return false; } private static IAliasSymbol GetAliasForSymbol(INamespaceOrTypeSymbol symbol, SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken) { var originalSemanticModel = semanticModel.GetOriginalSemanticModel(); if (!originalSemanticModel.SyntaxTree.HasCompilationUnitRoot) { return null; } var namespaceId = GetNamespaceIdForAliasSearch(semanticModel, token, cancellationToken); if (namespaceId < 0) { return null; } if (!AliasSymbolCache.TryGetAliasSymbol(originalSemanticModel, namespaceId, symbol, out var aliasSymbol)) { // add cache AliasSymbolCache.AddAliasSymbols(originalSemanticModel, namespaceId, semanticModel.LookupNamespacesAndTypes(token.SpanStart).OfType<IAliasSymbol>()); // retry AliasSymbolCache.TryGetAliasSymbol(originalSemanticModel, namespaceId, symbol, out aliasSymbol); } return aliasSymbol; } private static int GetNamespaceIdForAliasSearch(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) { var startNode = GetStartNodeForNamespaceId(semanticModel, token, cancellationToken); if (!startNode.SyntaxTree.HasCompilationUnitRoot) { return -1; } // NOTE: If we're currently in a block of usings, then we want to collect the // aliases that are higher up than this block. Using aliases declared in a block of // usings are not usable from within that same block. var usingDirective = startNode.GetAncestorOrThis<UsingDirectiveSyntax>(); if (usingDirective != null) { startNode = usingDirective.Parent.Parent; if (startNode == null) { return -1; } } // check whether I am under a namespace var @namespace = startNode.GetAncestorOrThis<BaseNamespaceDeclarationSyntax>(); if (@namespace != null) { // since we have node inside of the root, root should be already there // search for namespace id should be quite cheap since normally there should be // only a few namespace defined in a source file if it is not 1. that is why it is // not cached. var startIndex = 1; return GetNamespaceId(startNode.SyntaxTree.GetRoot(cancellationToken), @namespace, ref startIndex); } // no namespace, under compilation unit directly return 0; } private static SyntaxNode GetStartNodeForNamespaceId(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) { if (!semanticModel.IsSpeculativeSemanticModel) { return token.Parent; } var originalSemanticMode = semanticModel.GetOriginalSemanticModel(); token = originalSemanticMode.SyntaxTree.GetRoot(cancellationToken).FindToken(semanticModel.OriginalPositionForSpeculation); return token.Parent; } private static int GetNamespaceId(SyntaxNode container, BaseNamespaceDeclarationSyntax target, ref int index) => container switch { CompilationUnitSyntax compilation => GetNamespaceId(compilation.Members, target, ref index), BaseNamespaceDeclarationSyntax @namespace => GetNamespaceId(@namespace.Members, target, ref index), _ => throw ExceptionUtilities.UnexpectedValue(container) }; private static int GetNamespaceId(SyntaxList<MemberDeclarationSyntax> members, BaseNamespaceDeclarationSyntax target, ref int index) { foreach (var member in members) { if (member is not BaseNamespaceDeclarationSyntax childNamespace) continue; if (childNamespace == target) return index; index++; var result = GetNamespaceId(childNamespace, target, ref index); if (result > 0) return result; } return -1; } protected static TypeSyntax CreatePredefinedTypeSyntax(ExpressionSyntax expression, SyntaxKind keywordKind) => SyntaxFactory.PredefinedType(SyntaxFactory.Token(expression.GetLeadingTrivia(), keywordKind, expression.GetTrailingTrivia())); protected static bool InsideNameOfExpression(ExpressionSyntax expression, SemanticModel semanticModel) { var nameOfInvocationExpr = expression.FirstAncestorOrSelf<InvocationExpressionSyntax>( invocationExpr => { return invocationExpr.Expression is IdentifierNameSyntax identifierName && identifierName.Identifier.Text == "nameof" && semanticModel.GetConstantValue(invocationExpr).HasValue && semanticModel.GetTypeInfo(invocationExpr).Type.SpecialType == SpecialType.System_String; }); return nameOfInvocationExpr != null; } protected static bool PreferPredefinedTypeKeywordInMemberAccess(ExpressionSyntax expression, OptionSet optionSet, SemanticModel semanticModel) { if (!SimplificationHelpers.PreferPredefinedTypeKeywordInMemberAccess(optionSet, semanticModel.Language)) return false; return (expression.IsDirectChildOfMemberAccessExpression() || expression.InsideCrefReference()) && !InsideNameOfExpression(expression, semanticModel); } protected static bool WillConflictWithExistingLocal( ExpressionSyntax expression, ExpressionSyntax simplifiedNode, SemanticModel semanticModel) { if (simplifiedNode is IdentifierNameSyntax identifierName && !SyntaxFacts.IsInNamespaceOrTypeContext(expression)) { var symbols = semanticModel.LookupSymbols(expression.SpanStart, name: identifierName.Identifier.ValueText); return symbols.Any(s => s is ILocalSymbol); } return false; } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./docs/features/task-types.md
Async Task Types in C# ====================== Extend `async` to support _task types_ that match a specific pattern, in addition to the well known types `System.Threading.Tasks.Task` and `System.Threading.Tasks.Task<T>`. ## Task Type A _task type_ is a `class` or `struct` with an associated _builder type_ identified with `System.Runtime.CompilerServices.AsyncMethodBuilderAttribute`. The _task type_ may be non-generic, for async methods that do not return a value, or generic, for methods that return a value. To support `await`, the _task type_ must have a corresponding, accessible `GetAwaiter()` method that returns an instance of an _awaiter type_ (see _C# 7.7.7.1 Awaitable expressions_). ```cs [AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))] class MyTask<T> { public Awaiter<T> GetAwaiter(); } class Awaiter<T> : INotifyCompletion { public bool IsCompleted { get; } public T GetResult(); public void OnCompleted(Action completion); } ``` ## Builder Type The _builder type_ is a `class` or `struct` that corresponds to the specific _task type_. The _builder type_ can have at most 1 type parameter and must not be nested in a generic type. The _builder type_ has the following `public` methods. For non-generic _builder types_, `SetResult()` has no parameters. ```cs class MyTaskMethodBuilder<T> { public static MyTaskMethodBuilder<T> Create(); public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine; public void SetStateMachine(IAsyncStateMachine stateMachine); public void SetException(Exception exception); public void SetResult(T result); public void AwaitOnCompleted<TAwaiter, TStateMachine>( ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine; public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>( ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine; public MyTask<T> Task { get; } } ``` ## Execution The types above are used by the compiler to generate the code for the state machine of an `async` method. (The generated code is equivalent to the code generated for async methods that return `Task`, `Task<T>`, or `void`. The difference is, for those well known types, the _builder types_ are also known to the compiler.) `Builder.Create()` is invoked to create an instance of the _builder type_. If the state machine is implemented as a `struct`, then `builder.SetStateMachine(stateMachine)` is called with a boxed instance of the state machine that the builder can cache if necessary. `builder.Start(ref stateMachine)` is invoked to associate the builder with compiler-generated state machine instance. The builder must call `stateMachine.MoveNext()` either in `Start()` or after `Start()` has returned to advance the state machine. After `Start()` returns, the `async` method calls `builder.Task` for the task to return from the async method. Each call to `stateMachine.MoveNext()` will advance the state machine. If the state machine completes successfully, `builder.SetResult()` is called, with the method return value if any. If an exception is thrown in the state machine, `builder.SetException(exception)` is called. If the state machine reaches an `await expr` expression, `expr.GetAwaiter()` is invoked. If the awaiter implements `ICriticalNotifyCompletion` and `IsCompleted` is false, the state machine invokes `builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine)`. `AwaitUnsafeOnCompleted()` should call `awaiter.OnCompleted(action)` with an action that calls `stateMachine.MoveNext()` when the awaiter completes. Similarly for `INotifyCompletion` and `builder.AwaitOnCompleted()`. ## Overload Resolution Overload resolution is extended to recognize _task types_ in addition to `Task` and `Task<T>`. An `async` lambda with no return value is an exact match for an overload candidate parameter of non-generic _task type_, and an `async` lambda with return type `T` is an exact match for an overload candidate parameter of generic _task type_. Otherwise if an `async` lambda is not an exact match for either of two candidate parameters of _task types_, or an exact match for both, and there is an implicit conversion from one candidate type to the other, the from candidate wins. Otherwise recursively evaluate the types `A` and `B` within `Task1<A>` and `Task2<B>` for better match. Otherwise if an `async` lambda is not an exact match for either of two candidate parameters of _task types_, but one candidate is a more specialized type than the other, the more specialized candidate wins.
Async Task Types in C# ====================== Extend `async` to support _task types_ that match a specific pattern, in addition to the well known types `System.Threading.Tasks.Task` and `System.Threading.Tasks.Task<T>`. ## Task Type A _task type_ is a `class` or `struct` with an associated _builder type_ identified with `System.Runtime.CompilerServices.AsyncMethodBuilderAttribute`. The _task type_ may be non-generic, for async methods that do not return a value, or generic, for methods that return a value. To support `await`, the _task type_ must have a corresponding, accessible `GetAwaiter()` method that returns an instance of an _awaiter type_ (see _C# 7.7.7.1 Awaitable expressions_). ```cs [AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))] class MyTask<T> { public Awaiter<T> GetAwaiter(); } class Awaiter<T> : INotifyCompletion { public bool IsCompleted { get; } public T GetResult(); public void OnCompleted(Action completion); } ``` ## Builder Type The _builder type_ is a `class` or `struct` that corresponds to the specific _task type_. The _builder type_ can have at most 1 type parameter and must not be nested in a generic type. The _builder type_ has the following `public` methods. For non-generic _builder types_, `SetResult()` has no parameters. ```cs class MyTaskMethodBuilder<T> { public static MyTaskMethodBuilder<T> Create(); public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine; public void SetStateMachine(IAsyncStateMachine stateMachine); public void SetException(Exception exception); public void SetResult(T result); public void AwaitOnCompleted<TAwaiter, TStateMachine>( ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine; public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>( ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine; public MyTask<T> Task { get; } } ``` ## Execution The types above are used by the compiler to generate the code for the state machine of an `async` method. (The generated code is equivalent to the code generated for async methods that return `Task`, `Task<T>`, or `void`. The difference is, for those well known types, the _builder types_ are also known to the compiler.) `Builder.Create()` is invoked to create an instance of the _builder type_. If the state machine is implemented as a `struct`, then `builder.SetStateMachine(stateMachine)` is called with a boxed instance of the state machine that the builder can cache if necessary. `builder.Start(ref stateMachine)` is invoked to associate the builder with compiler-generated state machine instance. The builder must call `stateMachine.MoveNext()` either in `Start()` or after `Start()` has returned to advance the state machine. After `Start()` returns, the `async` method calls `builder.Task` for the task to return from the async method. Each call to `stateMachine.MoveNext()` will advance the state machine. If the state machine completes successfully, `builder.SetResult()` is called, with the method return value if any. If an exception is thrown in the state machine, `builder.SetException(exception)` is called. If the state machine reaches an `await expr` expression, `expr.GetAwaiter()` is invoked. If the awaiter implements `ICriticalNotifyCompletion` and `IsCompleted` is false, the state machine invokes `builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine)`. `AwaitUnsafeOnCompleted()` should call `awaiter.OnCompleted(action)` with an action that calls `stateMachine.MoveNext()` when the awaiter completes. Similarly for `INotifyCompletion` and `builder.AwaitOnCompleted()`. ## Overload Resolution Overload resolution is extended to recognize _task types_ in addition to `Task` and `Task<T>`. An `async` lambda with no return value is an exact match for an overload candidate parameter of non-generic _task type_, and an `async` lambda with return type `T` is an exact match for an overload candidate parameter of generic _task type_. Otherwise if an `async` lambda is not an exact match for either of two candidate parameters of _task types_, or an exact match for both, and there is an implicit conversion from one candidate type to the other, the from candidate wins. Otherwise recursively evaluate the types `A` and `B` within `Task1<A>` and `Task2<B>` for better match. Otherwise if an `async` lambda is not an exact match for either of two candidate parameters of _task types_, but one candidate is a more specialized type than the other, the more specialized candidate wins.
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/Core/Implementation/Formatting/FormatCommandHandler.TypeChar.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; namespace Microsoft.CodeAnalysis.Editor.Implementation.Formatting { internal partial class FormatCommandHandler { public CommandState GetCommandState(TypeCharCommandArgs args, Func<CommandState> nextHandler) => nextHandler(); public void ExecuteCommand(TypeCharCommandArgs args, Action nextHandler, CommandExecutionContext context) => ExecuteReturnOrTypeCommand(args, nextHandler, context.OperationContext.UserCancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; namespace Microsoft.CodeAnalysis.Editor.Implementation.Formatting { internal partial class FormatCommandHandler { public CommandState GetCommandState(TypeCharCommandArgs args, Func<CommandState> nextHandler) => nextHandler(); public void ExecuteCommand(TypeCharCommandArgs args, Action nextHandler, CommandExecutionContext context) => ExecuteReturnOrTypeCommand(args, nextHandler, context.OperationContext.UserCancellationToken); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/LanguageServer/ProtocolUnitTests/Ordering/TestRequest.cs
// Licensed to the .NET Foundation under one or more 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.LanguageServer.UnitTests.RequestOrdering { internal class TestRequest { public string MethodName { get; } public TestRequest(string methodName) { MethodName = methodName; } } }
// Licensed to the .NET Foundation under one or more 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.LanguageServer.UnitTests.RequestOrdering { internal class TestRequest { public string MethodName { get; } public TestRequest(string methodName) { MethodName = methodName; } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/VisualBasic/Portable/CommandLine/VisualBasicCompiler.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.IO Imports System.Threading Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Friend MustInherit Class VisualBasicCompiler Inherits CommonCompiler Friend Const ResponseFileName As String = "vbc.rsp" Friend Const VbcCommandLinePrefix = "vbc : " 'Common prefix String For VB diagnostic output with no location. Private Shared ReadOnly s_responseFileName As String Private ReadOnly _responseFile As String Private ReadOnly _diagnosticFormatter As CommandLineDiagnosticFormatter Private ReadOnly _tempDirectory As String Private _additionalTextFiles As ImmutableArray(Of AdditionalTextFile) Protected Sub New(parser As VisualBasicCommandLineParser, responseFile As String, args As String(), buildPaths As BuildPaths, additionalReferenceDirectories As String, analyzerLoader As IAnalyzerAssemblyLoader) MyBase.New(parser, responseFile, args, buildPaths, additionalReferenceDirectories, analyzerLoader) _diagnosticFormatter = New CommandLineDiagnosticFormatter(buildPaths.WorkingDirectory, AddressOf GetAdditionalTextFiles) _additionalTextFiles = Nothing _tempDirectory = buildPaths.TempDirectory Debug.Assert(Arguments.OutputFileName IsNot Nothing OrElse Arguments.Errors.Length > 0 OrElse parser.IsScriptCommandLineParser) End Sub Private Function GetAdditionalTextFiles() As ImmutableArray(Of AdditionalTextFile) Debug.Assert(Not _additionalTextFiles.IsDefault, "GetAdditionalTextFiles called before ResolveAdditionalFilesFromArguments") Return _additionalTextFiles End Function Protected Overrides Function ResolveAdditionalFilesFromArguments(diagnostics As List(Of DiagnosticInfo), messageProvider As CommonMessageProvider, touchedFilesLogger As TouchedFileLogger) As ImmutableArray(Of AdditionalTextFile) _additionalTextFiles = MyBase.ResolveAdditionalFilesFromArguments(diagnostics, messageProvider, touchedFilesLogger) Return _additionalTextFiles End Function Friend Overloads ReadOnly Property Arguments As VisualBasicCommandLineArguments Get Return DirectCast(MyBase.Arguments, VisualBasicCommandLineArguments) End Get End Property Public Overrides ReadOnly Property DiagnosticFormatter As DiagnosticFormatter Get Return _diagnosticFormatter End Get End Property Private Function ParseFile(consoleOutput As TextWriter, parseOptions As VisualBasicParseOptions, scriptParseOptions As VisualBasicParseOptions, ByRef hadErrors As Boolean, file As CommandLineSourceFile, errorLogger As ErrorLogger) As SyntaxTree Dim fileReadDiagnostics As New List(Of DiagnosticInfo)() Dim content = TryReadFileContent(file, fileReadDiagnostics) If content Is Nothing Then ReportDiagnostics(fileReadDiagnostics, consoleOutput, errorLogger, compilation:=Nothing) fileReadDiagnostics.Clear() hadErrors = True Return Nothing End If Dim tree = VisualBasicSyntaxTree.ParseText( content, If(file.IsScript, scriptParseOptions, parseOptions), file.Path) ' prepopulate line tables. ' we will need line tables anyways and it is better to Not wait until we are in emit ' where things run sequentially. Dim isHiddenDummy As Boolean tree.GetMappedLineSpanAndVisibility(Nothing, isHiddenDummy) Return tree End Function Public Overrides Function CreateCompilation(consoleOutput As TextWriter, touchedFilesLogger As TouchedFileLogger, errorLogger As ErrorLogger, analyzerConfigOptions As ImmutableArray(Of AnalyzerConfigOptionsResult), globalAnalyzerConfigOptions As AnalyzerConfigOptionsResult) As Compilation Dim parseOptions = Arguments.ParseOptions ' We compute script parse options once so we don't have to do it repeatedly in ' case there are many script files. Dim scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script) Dim hadErrors As Boolean = False Dim sourceFiles As ImmutableArray(Of CommandLineSourceFile) = Arguments.SourceFiles Dim trees(sourceFiles.Length - 1) As SyntaxTree If Arguments.CompilationOptions.ConcurrentBuild Then RoslynParallel.For( 0, sourceFiles.Length, UICultureUtilities.WithCurrentUICulture(Of Integer)( Sub(i As Integer) ' NOTE: order of trees is important!! trees(i) = ParseFile( consoleOutput, parseOptions, scriptParseOptions, hadErrors, sourceFiles(i), errorLogger) End Sub), CancellationToken.None) Else For i = 0 To sourceFiles.Length - 1 ' NOTE: order of trees is important!! trees(i) = ParseFile( consoleOutput, parseOptions, scriptParseOptions, hadErrors, sourceFiles(i), errorLogger) Next End If If hadErrors Then Return Nothing End If If Arguments.TouchedFilesPath IsNot Nothing Then For Each file In sourceFiles touchedFilesLogger.AddRead(file.Path) Next End If Dim diagnostics = New List(Of DiagnosticInfo)() Dim assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default Dim referenceDirectiveResolver As MetadataReferenceResolver = Nothing Dim resolvedReferences = ResolveMetadataReferences(diagnostics, touchedFilesLogger, referenceDirectiveResolver) If ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation:=Nothing) Then Return Nothing End If If Arguments.OutputLevel = OutputLevel.Verbose Then PrintReferences(resolvedReferences, consoleOutput) End If Dim xmlFileResolver = New LoggingXmlFileResolver(Arguments.BaseDirectory, touchedFilesLogger) ' TODO: support for #load search paths Dim sourceFileResolver = New LoggingSourceFileResolver(ImmutableArray(Of String).Empty, Arguments.BaseDirectory, Arguments.PathMap, touchedFilesLogger) Dim loggingFileSystem = New LoggingStrongNameFileSystem(touchedFilesLogger, _tempDirectory) Dim syntaxTreeOptions = New CompilerSyntaxTreeOptionsProvider(trees, analyzerConfigOptions, globalAnalyzerConfigOptions) Return VisualBasicCompilation.Create( Arguments.CompilationName, trees, resolvedReferences, Arguments.CompilationOptions. WithMetadataReferenceResolver(referenceDirectiveResolver). WithAssemblyIdentityComparer(assemblyIdentityComparer). WithXmlReferenceResolver(xmlFileResolver). WithStrongNameProvider(Arguments.GetStrongNameProvider(loggingFileSystem)). WithSourceReferenceResolver(sourceFileResolver). WithSyntaxTreeOptionsProvider(syntaxTreeOptions)) End Function Protected Overrides Function GetOutputFileName(compilation As Compilation, cancellationToken As CancellationToken) As String ' The only case this is Nothing is when there are errors during parsing in which case this should never get called Debug.Assert(Arguments.OutputFileName IsNot Nothing) Return Arguments.OutputFileName End Function Private Sub PrintReferences(resolvedReferences As List(Of MetadataReference), consoleOutput As TextWriter) For Each reference In resolvedReferences If reference.Properties.Kind = MetadataImageKind.Module Then consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_MSG_ADDMODULE, Culture), reference.Display) ElseIf reference.Properties.EmbedInteropTypes Then consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_MSG_ADDLINKREFERENCE, Culture), reference.Display) Else consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_MSG_ADDREFERENCE, Culture), reference.Display) End If Next consoleOutput.WriteLine() End Sub Friend Overrides Function SuppressDefaultResponseFile(args As IEnumerable(Of String)) As Boolean For Each arg In args Select Case arg.ToLowerInvariant Case "/noconfig", "-noconfig", "/nostdlib", "-nostdlib" Return True End Select Next Return False End Function ''' <summary> ''' Print compiler logo ''' </summary> ''' <param name="consoleOutput"></param> Public Overrides Sub PrintLogo(consoleOutput As TextWriter) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_LogoLine1, Culture), GetToolName(), GetCompilerVersion()) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_LogoLine2, Culture)) consoleOutput.WriteLine() End Sub Friend Overrides Function GetToolName() As String Return ErrorFactory.IdToString(ERRID.IDS_ToolName, Culture) End Function Friend Overrides ReadOnly Property Type As Type Get ' We do not use Me.GetType() so that we don't break mock subtypes Return GetType(VisualBasicCompiler) End Get End Property ''' <summary> ''' Print Commandline help message (up to 80 English characters per line) ''' </summary> ''' <param name="consoleOutput"></param> Public Overrides Sub PrintHelp(consoleOutput As TextWriter) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_VBCHelp, Culture)) End Sub Public Overrides Sub PrintLangVersions(consoleOutput As TextWriter) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_LangVersions, Culture)) Dim defaultVersion = LanguageVersion.Default.MapSpecifiedToEffectiveVersion() Dim latestVersion = LanguageVersion.Latest.MapSpecifiedToEffectiveVersion() For Each v As LanguageVersion In System.Enum.GetValues(GetType(LanguageVersion)) If v = defaultVersion Then consoleOutput.WriteLine($"{v.ToDisplayString()} (default)") ElseIf v = latestVersion Then consoleOutput.WriteLine($"{v.ToDisplayString()} (latest)") Else consoleOutput.WriteLine(v.ToDisplayString()) End If Next consoleOutput.WriteLine() End Sub Protected Overrides Function TryGetCompilerDiagnosticCode(diagnosticId As String, ByRef code As UInteger) As Boolean Return CommonCompiler.TryGetCompilerDiagnosticCode(diagnosticId, "BC", code) End Function Protected Overrides Sub ResolveAnalyzersFromArguments( diagnostics As List(Of DiagnosticInfo), messageProvider As CommonMessageProvider, skipAnalyzers As Boolean, ByRef analyzers As ImmutableArray(Of DiagnosticAnalyzer), ByRef generators As ImmutableArray(Of ISourceGenerator)) Arguments.ResolveAnalyzersFromArguments(LanguageNames.VisualBasic, diagnostics, messageProvider, AssemblyLoader, skipAnalyzers, analyzers, generators) End Sub Protected Overrides Sub ResolveEmbeddedFilesFromExternalSourceDirectives( tree As SyntaxTree, resolver As SourceReferenceResolver, embeddedFiles As OrderedSet(Of String), diagnostics As DiagnosticBag) For Each directive As ExternalSourceDirectiveTriviaSyntax In tree.GetRoot().GetDirectives( Function(d) d.Kind() = SyntaxKind.ExternalSourceDirectiveTrivia) If directive.ExternalSource.IsMissing Then Continue For End If Dim path = CStr(directive.ExternalSource.Value) If path Is Nothing Then Continue For End If Dim resolvedPath = resolver.ResolveReference(path, tree.FilePath) If resolvedPath Is Nothing Then diagnostics.Add( MessageProvider.CreateDiagnostic( MessageProvider.ERR_FileNotFound, directive.ExternalSource.GetLocation(), path)) Continue For End If embeddedFiles.Add(resolvedPath) Next End Sub Private Protected Overrides Function RunGenerators(input As Compilation, parseOptions As ParseOptions, generators As ImmutableArray(Of ISourceGenerator), analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider, additionalTexts As ImmutableArray(Of AdditionalText), diagnostics As DiagnosticBag) As Compilation Dim driver = VisualBasicGeneratorDriver.Create(generators, additionalTexts, DirectCast(parseOptions, VisualBasicParseOptions), analyzerConfigOptionsProvider) Dim compilationOut As Compilation = Nothing, generatorDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(input, compilationOut, generatorDiagnostics) diagnostics.AddRange(generatorDiagnostics) Return compilationOut End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.IO Imports System.Threading Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Friend MustInherit Class VisualBasicCompiler Inherits CommonCompiler Friend Const ResponseFileName As String = "vbc.rsp" Friend Const VbcCommandLinePrefix = "vbc : " 'Common prefix String For VB diagnostic output with no location. Private Shared ReadOnly s_responseFileName As String Private ReadOnly _responseFile As String Private ReadOnly _diagnosticFormatter As CommandLineDiagnosticFormatter Private ReadOnly _tempDirectory As String Private _additionalTextFiles As ImmutableArray(Of AdditionalTextFile) Protected Sub New(parser As VisualBasicCommandLineParser, responseFile As String, args As String(), buildPaths As BuildPaths, additionalReferenceDirectories As String, analyzerLoader As IAnalyzerAssemblyLoader) MyBase.New(parser, responseFile, args, buildPaths, additionalReferenceDirectories, analyzerLoader) _diagnosticFormatter = New CommandLineDiagnosticFormatter(buildPaths.WorkingDirectory, AddressOf GetAdditionalTextFiles) _additionalTextFiles = Nothing _tempDirectory = buildPaths.TempDirectory Debug.Assert(Arguments.OutputFileName IsNot Nothing OrElse Arguments.Errors.Length > 0 OrElse parser.IsScriptCommandLineParser) End Sub Private Function GetAdditionalTextFiles() As ImmutableArray(Of AdditionalTextFile) Debug.Assert(Not _additionalTextFiles.IsDefault, "GetAdditionalTextFiles called before ResolveAdditionalFilesFromArguments") Return _additionalTextFiles End Function Protected Overrides Function ResolveAdditionalFilesFromArguments(diagnostics As List(Of DiagnosticInfo), messageProvider As CommonMessageProvider, touchedFilesLogger As TouchedFileLogger) As ImmutableArray(Of AdditionalTextFile) _additionalTextFiles = MyBase.ResolveAdditionalFilesFromArguments(diagnostics, messageProvider, touchedFilesLogger) Return _additionalTextFiles End Function Friend Overloads ReadOnly Property Arguments As VisualBasicCommandLineArguments Get Return DirectCast(MyBase.Arguments, VisualBasicCommandLineArguments) End Get End Property Public Overrides ReadOnly Property DiagnosticFormatter As DiagnosticFormatter Get Return _diagnosticFormatter End Get End Property Private Function ParseFile(consoleOutput As TextWriter, parseOptions As VisualBasicParseOptions, scriptParseOptions As VisualBasicParseOptions, ByRef hadErrors As Boolean, file As CommandLineSourceFile, errorLogger As ErrorLogger) As SyntaxTree Dim fileReadDiagnostics As New List(Of DiagnosticInfo)() Dim content = TryReadFileContent(file, fileReadDiagnostics) If content Is Nothing Then ReportDiagnostics(fileReadDiagnostics, consoleOutput, errorLogger, compilation:=Nothing) fileReadDiagnostics.Clear() hadErrors = True Return Nothing End If Dim tree = VisualBasicSyntaxTree.ParseText( content, If(file.IsScript, scriptParseOptions, parseOptions), file.Path) ' prepopulate line tables. ' we will need line tables anyways and it is better to Not wait until we are in emit ' where things run sequentially. Dim isHiddenDummy As Boolean tree.GetMappedLineSpanAndVisibility(Nothing, isHiddenDummy) Return tree End Function Public Overrides Function CreateCompilation(consoleOutput As TextWriter, touchedFilesLogger As TouchedFileLogger, errorLogger As ErrorLogger, analyzerConfigOptions As ImmutableArray(Of AnalyzerConfigOptionsResult), globalAnalyzerConfigOptions As AnalyzerConfigOptionsResult) As Compilation Dim parseOptions = Arguments.ParseOptions ' We compute script parse options once so we don't have to do it repeatedly in ' case there are many script files. Dim scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script) Dim hadErrors As Boolean = False Dim sourceFiles As ImmutableArray(Of CommandLineSourceFile) = Arguments.SourceFiles Dim trees(sourceFiles.Length - 1) As SyntaxTree If Arguments.CompilationOptions.ConcurrentBuild Then RoslynParallel.For( 0, sourceFiles.Length, UICultureUtilities.WithCurrentUICulture(Of Integer)( Sub(i As Integer) ' NOTE: order of trees is important!! trees(i) = ParseFile( consoleOutput, parseOptions, scriptParseOptions, hadErrors, sourceFiles(i), errorLogger) End Sub), CancellationToken.None) Else For i = 0 To sourceFiles.Length - 1 ' NOTE: order of trees is important!! trees(i) = ParseFile( consoleOutput, parseOptions, scriptParseOptions, hadErrors, sourceFiles(i), errorLogger) Next End If If hadErrors Then Return Nothing End If If Arguments.TouchedFilesPath IsNot Nothing Then For Each file In sourceFiles touchedFilesLogger.AddRead(file.Path) Next End If Dim diagnostics = New List(Of DiagnosticInfo)() Dim assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default Dim referenceDirectiveResolver As MetadataReferenceResolver = Nothing Dim resolvedReferences = ResolveMetadataReferences(diagnostics, touchedFilesLogger, referenceDirectiveResolver) If ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation:=Nothing) Then Return Nothing End If If Arguments.OutputLevel = OutputLevel.Verbose Then PrintReferences(resolvedReferences, consoleOutput) End If Dim xmlFileResolver = New LoggingXmlFileResolver(Arguments.BaseDirectory, touchedFilesLogger) ' TODO: support for #load search paths Dim sourceFileResolver = New LoggingSourceFileResolver(ImmutableArray(Of String).Empty, Arguments.BaseDirectory, Arguments.PathMap, touchedFilesLogger) Dim loggingFileSystem = New LoggingStrongNameFileSystem(touchedFilesLogger, _tempDirectory) Dim syntaxTreeOptions = New CompilerSyntaxTreeOptionsProvider(trees, analyzerConfigOptions, globalAnalyzerConfigOptions) Return VisualBasicCompilation.Create( Arguments.CompilationName, trees, resolvedReferences, Arguments.CompilationOptions. WithMetadataReferenceResolver(referenceDirectiveResolver). WithAssemblyIdentityComparer(assemblyIdentityComparer). WithXmlReferenceResolver(xmlFileResolver). WithStrongNameProvider(Arguments.GetStrongNameProvider(loggingFileSystem)). WithSourceReferenceResolver(sourceFileResolver). WithSyntaxTreeOptionsProvider(syntaxTreeOptions)) End Function Protected Overrides Function GetOutputFileName(compilation As Compilation, cancellationToken As CancellationToken) As String ' The only case this is Nothing is when there are errors during parsing in which case this should never get called Debug.Assert(Arguments.OutputFileName IsNot Nothing) Return Arguments.OutputFileName End Function Private Sub PrintReferences(resolvedReferences As List(Of MetadataReference), consoleOutput As TextWriter) For Each reference In resolvedReferences If reference.Properties.Kind = MetadataImageKind.Module Then consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_MSG_ADDMODULE, Culture), reference.Display) ElseIf reference.Properties.EmbedInteropTypes Then consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_MSG_ADDLINKREFERENCE, Culture), reference.Display) Else consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_MSG_ADDREFERENCE, Culture), reference.Display) End If Next consoleOutput.WriteLine() End Sub Friend Overrides Function SuppressDefaultResponseFile(args As IEnumerable(Of String)) As Boolean For Each arg In args Select Case arg.ToLowerInvariant Case "/noconfig", "-noconfig", "/nostdlib", "-nostdlib" Return True End Select Next Return False End Function ''' <summary> ''' Print compiler logo ''' </summary> ''' <param name="consoleOutput"></param> Public Overrides Sub PrintLogo(consoleOutput As TextWriter) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_LogoLine1, Culture), GetToolName(), GetCompilerVersion()) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_LogoLine2, Culture)) consoleOutput.WriteLine() End Sub Friend Overrides Function GetToolName() As String Return ErrorFactory.IdToString(ERRID.IDS_ToolName, Culture) End Function Friend Overrides ReadOnly Property Type As Type Get ' We do not use Me.GetType() so that we don't break mock subtypes Return GetType(VisualBasicCompiler) End Get End Property ''' <summary> ''' Print Commandline help message (up to 80 English characters per line) ''' </summary> ''' <param name="consoleOutput"></param> Public Overrides Sub PrintHelp(consoleOutput As TextWriter) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_VBCHelp, Culture)) End Sub Public Overrides Sub PrintLangVersions(consoleOutput As TextWriter) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_LangVersions, Culture)) Dim defaultVersion = LanguageVersion.Default.MapSpecifiedToEffectiveVersion() Dim latestVersion = LanguageVersion.Latest.MapSpecifiedToEffectiveVersion() For Each v As LanguageVersion In System.Enum.GetValues(GetType(LanguageVersion)) If v = defaultVersion Then consoleOutput.WriteLine($"{v.ToDisplayString()} (default)") ElseIf v = latestVersion Then consoleOutput.WriteLine($"{v.ToDisplayString()} (latest)") Else consoleOutput.WriteLine(v.ToDisplayString()) End If Next consoleOutput.WriteLine() End Sub Protected Overrides Function TryGetCompilerDiagnosticCode(diagnosticId As String, ByRef code As UInteger) As Boolean Return CommonCompiler.TryGetCompilerDiagnosticCode(diagnosticId, "BC", code) End Function Protected Overrides Sub ResolveAnalyzersFromArguments( diagnostics As List(Of DiagnosticInfo), messageProvider As CommonMessageProvider, skipAnalyzers As Boolean, ByRef analyzers As ImmutableArray(Of DiagnosticAnalyzer), ByRef generators As ImmutableArray(Of ISourceGenerator)) Arguments.ResolveAnalyzersFromArguments(LanguageNames.VisualBasic, diagnostics, messageProvider, AssemblyLoader, skipAnalyzers, analyzers, generators) End Sub Protected Overrides Sub ResolveEmbeddedFilesFromExternalSourceDirectives( tree As SyntaxTree, resolver As SourceReferenceResolver, embeddedFiles As OrderedSet(Of String), diagnostics As DiagnosticBag) For Each directive As ExternalSourceDirectiveTriviaSyntax In tree.GetRoot().GetDirectives( Function(d) d.Kind() = SyntaxKind.ExternalSourceDirectiveTrivia) If directive.ExternalSource.IsMissing Then Continue For End If Dim path = CStr(directive.ExternalSource.Value) If path Is Nothing Then Continue For End If Dim resolvedPath = resolver.ResolveReference(path, tree.FilePath) If resolvedPath Is Nothing Then diagnostics.Add( MessageProvider.CreateDiagnostic( MessageProvider.ERR_FileNotFound, directive.ExternalSource.GetLocation(), path)) Continue For End If embeddedFiles.Add(resolvedPath) Next End Sub Private Protected Overrides Function RunGenerators(input As Compilation, parseOptions As ParseOptions, generators As ImmutableArray(Of ISourceGenerator), analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider, additionalTexts As ImmutableArray(Of AdditionalText), diagnostics As DiagnosticBag) As Compilation Dim driver = VisualBasicGeneratorDriver.Create(generators, additionalTexts, DirectCast(parseOptions, VisualBasicParseOptions), analyzerConfigOptionsProvider) Dim compilationOut As Compilation = Nothing, generatorDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(input, compilationOut, generatorDiagnostics) diagnostics.AddRange(generatorDiagnostics) Return compilationOut End Function End Class End Namespace
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/VisualBasic/Impl/Snippets/SnippetCommandHandler.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.ComponentModel.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Editor Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp Imports Microsoft.CodeAnalysis.Editor.Shared.Extensions Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.Editor Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion Imports Microsoft.VisualStudio.LanguageServices.Implementation.Snippets Imports Microsoft.VisualStudio.Shell Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Editor.Commanding Imports Microsoft.VisualStudio.TextManager.Interop Imports Microsoft.VisualStudio.Utilities Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Snippets <Export(GetType(Commanding.ICommandHandler))> <ContentType(ContentTypeNames.VisualBasicContentType)> <Name("VB Snippets")> <Order(After:=PredefinedCompletionNames.CompletionCommandHandler)> <Order(After:=PredefinedCommandHandlerNames.SignatureHelpAfterCompletion)> <Order(Before:=PredefinedCommandHandlerNames.AutomaticLineEnder)> Friend NotInheritable Class SnippetCommandHandler Inherits AbstractSnippetCommandHandler Private ReadOnly _argumentProviders As ImmutableArray(Of Lazy(Of ArgumentProvider, OrderableLanguageMetadata)) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New(threadingContext As IThreadingContext, signatureHelpControllerProvider As SignatureHelpControllerProvider, editorCommandHandlerServiceFactory As IEditorCommandHandlerServiceFactory, editorAdaptersFactoryService As IVsEditorAdaptersFactoryService, serviceProvider As SVsServiceProvider, <ImportMany> argumentProviders As IEnumerable(Of Lazy(Of ArgumentProvider, OrderableLanguageMetadata))) MyBase.New(threadingContext, signatureHelpControllerProvider, editorCommandHandlerServiceFactory, editorAdaptersFactoryService, serviceProvider) _argumentProviders = argumentProviders.ToImmutableArray() End Sub Protected Overrides Function IsSnippetExpansionContext(document As Document, startPosition As Integer, cancellationToken As CancellationToken) As Boolean Dim syntaxTree = document.GetSyntaxTreeSynchronously(CancellationToken.None) Return Not syntaxTree.IsEntirelyWithinStringOrCharOrNumericLiteral(startPosition, cancellationToken) AndAlso Not syntaxTree.IsEntirelyWithinComment(startPosition, cancellationToken) AndAlso Not syntaxTree.FindTokenOnRightOfPosition(startPosition, cancellationToken).HasAncestor(Of XmlElementSyntax)() End Function Protected Overrides Function GetSnippetExpansionClient(textView As ITextView, subjectBuffer As ITextBuffer) As AbstractSnippetExpansionClient Return SnippetExpansionClient.GetSnippetExpansionClient(ThreadingContext, textView, subjectBuffer, SignatureHelpControllerProvider, EditorCommandHandlerServiceFactory, EditorAdaptersFactoryService, _argumentProviders) End Function Protected Overrides Function TryInvokeInsertionUI(textView As ITextView, subjectBuffer As ITextBuffer, Optional surroundWith As Boolean = False) As Boolean Debug.Assert(Not surroundWith) Dim expansionManager As IVsExpansionManager = Nothing If Not TryGetExpansionManager(expansionManager) Then Return False End If expansionManager.InvokeInsertionUI( EditorAdaptersFactoryService.GetViewAdapter(textView), GetSnippetExpansionClient(textView, subjectBuffer), Guids.VisualBasicDebuggerLanguageId, bstrTypes:=Nothing, iCountTypes:=0, fIncludeNULLType:=1, bstrKinds:=Nothing, iCountKinds:=0, fIncludeNULLKind:=1, bstrPrefixText:=BasicVSResources.Insert_Snippet, bstrCompletionChar:=">"c) Return True End Function Protected Overrides Function TryInvokeSnippetPickerOnQuestionMark(textView As ITextView, subjectBuffer As ITextBuffer) As Boolean Dim text = subjectBuffer.AsTextContainer().CurrentText Dim caretPosition = textView.GetCaretPoint(subjectBuffer).Value.Position If (caretPosition > 1 AndAlso text(caretPosition - 1) = "?"c AndAlso Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts.IsWhitespace(text(caretPosition - 2))) OrElse (caretPosition = 1 AndAlso text(0) = "?"c) Then DeleteQuestionMark(subjectBuffer, caretPosition) TryInvokeInsertionUI(textView, subjectBuffer) Return True End If Return False End Function Private Sub DeleteQuestionMark(subjectBuffer As ITextBuffer, caretPosition As Integer) Dim currentSnapshot = subjectBuffer.CurrentSnapshot Dim document = currentSnapshot.GetOpenDocumentInCurrentContextWithChanges() If document IsNot Nothing Then Dim editorWorkspace = document.Project.Solution.Workspace Dim text = currentSnapshot.AsText() Dim change = New TextChange(Microsoft.CodeAnalysis.Text.TextSpan.FromBounds(caretPosition - 1, caretPosition), String.Empty) editorWorkspace.ApplyTextChanges(document.Id, change, CancellationToken.None) End If End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.ComponentModel.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Editor Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp Imports Microsoft.CodeAnalysis.Editor.Shared.Extensions Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.Editor Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion Imports Microsoft.VisualStudio.LanguageServices.Implementation.Snippets Imports Microsoft.VisualStudio.Shell Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Editor.Commanding Imports Microsoft.VisualStudio.TextManager.Interop Imports Microsoft.VisualStudio.Utilities Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Snippets <Export(GetType(Commanding.ICommandHandler))> <ContentType(ContentTypeNames.VisualBasicContentType)> <Name("VB Snippets")> <Order(After:=PredefinedCompletionNames.CompletionCommandHandler)> <Order(After:=PredefinedCommandHandlerNames.SignatureHelpAfterCompletion)> <Order(Before:=PredefinedCommandHandlerNames.AutomaticLineEnder)> Friend NotInheritable Class SnippetCommandHandler Inherits AbstractSnippetCommandHandler Private ReadOnly _argumentProviders As ImmutableArray(Of Lazy(Of ArgumentProvider, OrderableLanguageMetadata)) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New(threadingContext As IThreadingContext, signatureHelpControllerProvider As SignatureHelpControllerProvider, editorCommandHandlerServiceFactory As IEditorCommandHandlerServiceFactory, editorAdaptersFactoryService As IVsEditorAdaptersFactoryService, serviceProvider As SVsServiceProvider, <ImportMany> argumentProviders As IEnumerable(Of Lazy(Of ArgumentProvider, OrderableLanguageMetadata))) MyBase.New(threadingContext, signatureHelpControllerProvider, editorCommandHandlerServiceFactory, editorAdaptersFactoryService, serviceProvider) _argumentProviders = argumentProviders.ToImmutableArray() End Sub Protected Overrides Function IsSnippetExpansionContext(document As Document, startPosition As Integer, cancellationToken As CancellationToken) As Boolean Dim syntaxTree = document.GetSyntaxTreeSynchronously(CancellationToken.None) Return Not syntaxTree.IsEntirelyWithinStringOrCharOrNumericLiteral(startPosition, cancellationToken) AndAlso Not syntaxTree.IsEntirelyWithinComment(startPosition, cancellationToken) AndAlso Not syntaxTree.FindTokenOnRightOfPosition(startPosition, cancellationToken).HasAncestor(Of XmlElementSyntax)() End Function Protected Overrides Function GetSnippetExpansionClient(textView As ITextView, subjectBuffer As ITextBuffer) As AbstractSnippetExpansionClient Return SnippetExpansionClient.GetSnippetExpansionClient(ThreadingContext, textView, subjectBuffer, SignatureHelpControllerProvider, EditorCommandHandlerServiceFactory, EditorAdaptersFactoryService, _argumentProviders) End Function Protected Overrides Function TryInvokeInsertionUI(textView As ITextView, subjectBuffer As ITextBuffer, Optional surroundWith As Boolean = False) As Boolean Debug.Assert(Not surroundWith) Dim expansionManager As IVsExpansionManager = Nothing If Not TryGetExpansionManager(expansionManager) Then Return False End If expansionManager.InvokeInsertionUI( EditorAdaptersFactoryService.GetViewAdapter(textView), GetSnippetExpansionClient(textView, subjectBuffer), Guids.VisualBasicDebuggerLanguageId, bstrTypes:=Nothing, iCountTypes:=0, fIncludeNULLType:=1, bstrKinds:=Nothing, iCountKinds:=0, fIncludeNULLKind:=1, bstrPrefixText:=BasicVSResources.Insert_Snippet, bstrCompletionChar:=">"c) Return True End Function Protected Overrides Function TryInvokeSnippetPickerOnQuestionMark(textView As ITextView, subjectBuffer As ITextBuffer) As Boolean Dim text = subjectBuffer.AsTextContainer().CurrentText Dim caretPosition = textView.GetCaretPoint(subjectBuffer).Value.Position If (caretPosition > 1 AndAlso text(caretPosition - 1) = "?"c AndAlso Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts.IsWhitespace(text(caretPosition - 2))) OrElse (caretPosition = 1 AndAlso text(0) = "?"c) Then DeleteQuestionMark(subjectBuffer, caretPosition) TryInvokeInsertionUI(textView, subjectBuffer) Return True End If Return False End Function Private Sub DeleteQuestionMark(subjectBuffer As ITextBuffer, caretPosition As Integer) Dim currentSnapshot = subjectBuffer.CurrentSnapshot Dim document = currentSnapshot.GetOpenDocumentInCurrentContextWithChanges() If document IsNot Nothing Then Dim editorWorkspace = document.Project.Solution.Workspace Dim text = currentSnapshot.AsText() Dim change = New TextChange(Microsoft.CodeAnalysis.Text.TextSpan.FromBounds(caretPosition - 1, caretPosition), String.Empty) editorWorkspace.ApplyTextChanges(document.Id, change, CancellationToken.None) End If End Sub End Class End Namespace
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/CSharp/Test/GlyphExtensionsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Moq; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { public class GlyphExtensionsTests : TestBase { [Fact] public void GetGlyphGroupTests() { TestGlyph( StandardGlyphGroup.GlyphAssembly, SymbolKind.Assembly); TestGlyph( StandardGlyphGroup.GlyphAssembly, SymbolKind.NetModule); TestGlyph( StandardGlyphGroup.GlyphGroupNamespace, SymbolKind.Namespace); TestGlyph( StandardGlyphGroup.GlyphGroupType, SymbolKind.TypeParameter); TestGlyph( StandardGlyphGroup.GlyphGroupClass, SymbolKind.DynamicType); TestGlyph( StandardGlyphGroup.GlyphExtensionMethodPrivate, SymbolKind.Method, Accessibility.Private); TestGlyph( StandardGlyphGroup.GlyphExtensionMethodPrivate, SymbolKind.Method, Accessibility.Private, isExtensionMethod: false, methodKind: MethodKind.ReducedExtension); TestGlyph( StandardGlyphGroup.GlyphExtensionMethodProtected, declaredAccessibility: Accessibility.ProtectedAndInternal); TestGlyph( StandardGlyphGroup.GlyphExtensionMethodProtected, declaredAccessibility: Accessibility.Protected); TestGlyph( StandardGlyphGroup.GlyphExtensionMethodProtected, declaredAccessibility: Accessibility.ProtectedOrInternal); TestGlyph( StandardGlyphGroup.GlyphExtensionMethodInternal, declaredAccessibility: Accessibility.Internal); TestGlyph( StandardGlyphGroup.GlyphExtensionMethod, declaredAccessibility: Accessibility.Public); TestGlyph( StandardGlyphGroup.GlyphGroupMethod, declaredAccessibility: Accessibility.Public, isExtensionMethod: false); TestGlyph( StandardGlyphGroup.GlyphGroupClass, SymbolKind.PointerType, pointedAtType: (INamedTypeSymbol)CreateSymbolMock(SymbolKind.NamedType, typeKind: TypeKind.Class)); TestGlyph( StandardGlyphGroup.GlyphGroupProperty, SymbolKind.Property); TestGlyph( StandardGlyphGroup.GlyphGroupEnumMember, SymbolKind.Field, containingType: (INamedTypeSymbol)CreateSymbolMock(SymbolKind.NamedType, typeKind: TypeKind.Enum)); TestGlyph( StandardGlyphGroup.GlyphGroupConstant, SymbolKind.Field, isConst: true); TestGlyph( StandardGlyphGroup.GlyphGroupField, SymbolKind.Field); TestGlyph(StandardGlyphGroup.GlyphGroupVariable, SymbolKind.Parameter); TestGlyph(StandardGlyphGroup.GlyphGroupVariable, SymbolKind.Local); TestGlyph(StandardGlyphGroup.GlyphGroupVariable, SymbolKind.RangeVariable); TestGlyph(StandardGlyphGroup.GlyphGroupIntrinsic, SymbolKind.Label); TestGlyph(StandardGlyphGroup.GlyphGroupEvent, SymbolKind.Event); TestGlyph( StandardGlyphGroup.GlyphGroupClass, SymbolKind.ArrayType, elementType: (INamedTypeSymbol)CreateSymbolMock(SymbolKind.NamedType, typeKind: TypeKind.Class)); TestGlyph( StandardGlyphGroup.GlyphGroupClass, SymbolKind.Alias, target: (INamedTypeSymbol)CreateSymbolMock(SymbolKind.NamedType, typeKind: TypeKind.Class)); Assert.ThrowsAny<ArgumentException>(() => TestGlyph( StandardGlyphGroup.GlyphGroupClass, (SymbolKind)1000)); TestGlyph( StandardGlyphGroup.GlyphGroupClass, SymbolKind.NamedType, typeKind: TypeKind.Class); TestGlyph( StandardGlyphGroup.GlyphGroupDelegate, SymbolKind.NamedType, typeKind: TypeKind.Delegate); TestGlyph( StandardGlyphGroup.GlyphGroupEnum, SymbolKind.NamedType, typeKind: TypeKind.Enum); TestGlyph( StandardGlyphGroup.GlyphGroupModule, SymbolKind.NamedType, typeKind: TypeKind.Module); TestGlyph( StandardGlyphGroup.GlyphGroupInterface, SymbolKind.NamedType, typeKind: TypeKind.Interface); TestGlyph( StandardGlyphGroup.GlyphGroupStruct, SymbolKind.NamedType, typeKind: TypeKind.Struct); TestGlyph( StandardGlyphGroup.GlyphGroupError, SymbolKind.NamedType, typeKind: TypeKind.Error); Assert.ThrowsAny<Exception>(() => TestGlyph( StandardGlyphGroup.GlyphGroupClass, SymbolKind.NamedType, typeKind: TypeKind.Unknown)); } [Fact, WorkItem(545015, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545015")] public void TestRegularOperatorGlyph() { TestGlyph( StandardGlyphGroup.GlyphGroupOperator, SymbolKind.Method, methodKind: MethodKind.UserDefinedOperator); } [Fact, WorkItem(545015, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545015")] public void TestConversionOperatorGlyph() { TestGlyph( StandardGlyphGroup.GlyphGroupOperator, SymbolKind.Method, methodKind: MethodKind.Conversion); } [Fact] public void TestWithEventsMemberGlyph() { TestGlyph( StandardGlyphGroup.GlyphGroupField, SymbolKind.Property, isWithEvents: true); } private void TestGlyph( StandardGlyphGroup expectedGlyphGroup, SymbolKind kind = SymbolKind.Method, Accessibility declaredAccessibility = Accessibility.NotApplicable, bool isExtensionMethod = true, MethodKind methodKind = MethodKind.Ordinary, INamedTypeSymbol containingType = null, bool isConst = false, ITypeSymbol elementType = null, INamespaceOrTypeSymbol target = null, ITypeSymbol pointedAtType = null, bool isWithEvents = false, TypeKind typeKind = TypeKind.Unknown) { var symbol = CreateSymbolMock(kind, declaredAccessibility, isExtensionMethod, methodKind, containingType, isConst, elementType, target, pointedAtType, isWithEvents, typeKind); Assert.Equal(expectedGlyphGroup, symbol.GetGlyph().GetStandardGlyphGroup()); } private static ISymbol CreateSymbolMock( SymbolKind kind, Accessibility declaredAccessibility = Accessibility.NotApplicable, bool isExtensionMethod = false, MethodKind methodKind = MethodKind.Ordinary, INamedTypeSymbol containingType = null, bool isConst = false, ITypeSymbol elementType = null, INamespaceOrTypeSymbol target = null, ITypeSymbol pointedAtType = null, bool isWithEvents = false, TypeKind typeKind = TypeKind.Unknown) { var symbolMock = new Mock<ISymbol>(MockBehavior.Strict); symbolMock.SetupGet(s => s.Kind).Returns(kind); symbolMock.SetupGet(s => s.DeclaredAccessibility).Returns(declaredAccessibility); symbolMock.SetupGet(s => s.ContainingType).Returns(containingType); if (kind == SymbolKind.ArrayType) { var arrayTypeMock = symbolMock.As<IArrayTypeSymbol>(); arrayTypeMock.SetupGet(s => s.ElementType).Returns(elementType); } if (kind == SymbolKind.Alias) { var aliasMock = symbolMock.As<IAliasSymbol>(); aliasMock.SetupGet(s => s.Target).Returns(target); } if (kind == SymbolKind.Method) { var methodTypeMock = symbolMock.As<IMethodSymbol>(); methodTypeMock.SetupGet(s => s.MethodKind).Returns(methodKind); methodTypeMock.SetupGet(s => s.IsExtensionMethod).Returns(isExtensionMethod); } if (kind == SymbolKind.NamedType) { var namedTypeMock = symbolMock.As<INamedTypeSymbol>(); namedTypeMock.SetupGet(s => s.TypeKind).Returns(typeKind); } if (kind == SymbolKind.Field) { var fieldMock = symbolMock.As<IFieldSymbol>(); fieldMock.SetupGet(s => s.IsConst).Returns(isConst); } if (kind == SymbolKind.PointerType) { var pointerTypeMock = symbolMock.As<IPointerTypeSymbol>(); pointerTypeMock.SetupGet(s => s.PointedAtType).Returns(pointedAtType); } if (kind == SymbolKind.Property) { var propertyMock = symbolMock.As<IPropertySymbol>(); propertyMock.SetupGet(s => s.IsWithEvents).Returns(isWithEvents); } return symbolMock.Object; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Moq; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { public class GlyphExtensionsTests : TestBase { [Fact] public void GetGlyphGroupTests() { TestGlyph( StandardGlyphGroup.GlyphAssembly, SymbolKind.Assembly); TestGlyph( StandardGlyphGroup.GlyphAssembly, SymbolKind.NetModule); TestGlyph( StandardGlyphGroup.GlyphGroupNamespace, SymbolKind.Namespace); TestGlyph( StandardGlyphGroup.GlyphGroupType, SymbolKind.TypeParameter); TestGlyph( StandardGlyphGroup.GlyphGroupClass, SymbolKind.DynamicType); TestGlyph( StandardGlyphGroup.GlyphExtensionMethodPrivate, SymbolKind.Method, Accessibility.Private); TestGlyph( StandardGlyphGroup.GlyphExtensionMethodPrivate, SymbolKind.Method, Accessibility.Private, isExtensionMethod: false, methodKind: MethodKind.ReducedExtension); TestGlyph( StandardGlyphGroup.GlyphExtensionMethodProtected, declaredAccessibility: Accessibility.ProtectedAndInternal); TestGlyph( StandardGlyphGroup.GlyphExtensionMethodProtected, declaredAccessibility: Accessibility.Protected); TestGlyph( StandardGlyphGroup.GlyphExtensionMethodProtected, declaredAccessibility: Accessibility.ProtectedOrInternal); TestGlyph( StandardGlyphGroup.GlyphExtensionMethodInternal, declaredAccessibility: Accessibility.Internal); TestGlyph( StandardGlyphGroup.GlyphExtensionMethod, declaredAccessibility: Accessibility.Public); TestGlyph( StandardGlyphGroup.GlyphGroupMethod, declaredAccessibility: Accessibility.Public, isExtensionMethod: false); TestGlyph( StandardGlyphGroup.GlyphGroupClass, SymbolKind.PointerType, pointedAtType: (INamedTypeSymbol)CreateSymbolMock(SymbolKind.NamedType, typeKind: TypeKind.Class)); TestGlyph( StandardGlyphGroup.GlyphGroupProperty, SymbolKind.Property); TestGlyph( StandardGlyphGroup.GlyphGroupEnumMember, SymbolKind.Field, containingType: (INamedTypeSymbol)CreateSymbolMock(SymbolKind.NamedType, typeKind: TypeKind.Enum)); TestGlyph( StandardGlyphGroup.GlyphGroupConstant, SymbolKind.Field, isConst: true); TestGlyph( StandardGlyphGroup.GlyphGroupField, SymbolKind.Field); TestGlyph(StandardGlyphGroup.GlyphGroupVariable, SymbolKind.Parameter); TestGlyph(StandardGlyphGroup.GlyphGroupVariable, SymbolKind.Local); TestGlyph(StandardGlyphGroup.GlyphGroupVariable, SymbolKind.RangeVariable); TestGlyph(StandardGlyphGroup.GlyphGroupIntrinsic, SymbolKind.Label); TestGlyph(StandardGlyphGroup.GlyphGroupEvent, SymbolKind.Event); TestGlyph( StandardGlyphGroup.GlyphGroupClass, SymbolKind.ArrayType, elementType: (INamedTypeSymbol)CreateSymbolMock(SymbolKind.NamedType, typeKind: TypeKind.Class)); TestGlyph( StandardGlyphGroup.GlyphGroupClass, SymbolKind.Alias, target: (INamedTypeSymbol)CreateSymbolMock(SymbolKind.NamedType, typeKind: TypeKind.Class)); Assert.ThrowsAny<ArgumentException>(() => TestGlyph( StandardGlyphGroup.GlyphGroupClass, (SymbolKind)1000)); TestGlyph( StandardGlyphGroup.GlyphGroupClass, SymbolKind.NamedType, typeKind: TypeKind.Class); TestGlyph( StandardGlyphGroup.GlyphGroupDelegate, SymbolKind.NamedType, typeKind: TypeKind.Delegate); TestGlyph( StandardGlyphGroup.GlyphGroupEnum, SymbolKind.NamedType, typeKind: TypeKind.Enum); TestGlyph( StandardGlyphGroup.GlyphGroupModule, SymbolKind.NamedType, typeKind: TypeKind.Module); TestGlyph( StandardGlyphGroup.GlyphGroupInterface, SymbolKind.NamedType, typeKind: TypeKind.Interface); TestGlyph( StandardGlyphGroup.GlyphGroupStruct, SymbolKind.NamedType, typeKind: TypeKind.Struct); TestGlyph( StandardGlyphGroup.GlyphGroupError, SymbolKind.NamedType, typeKind: TypeKind.Error); Assert.ThrowsAny<Exception>(() => TestGlyph( StandardGlyphGroup.GlyphGroupClass, SymbolKind.NamedType, typeKind: TypeKind.Unknown)); } [Fact, WorkItem(545015, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545015")] public void TestRegularOperatorGlyph() { TestGlyph( StandardGlyphGroup.GlyphGroupOperator, SymbolKind.Method, methodKind: MethodKind.UserDefinedOperator); } [Fact, WorkItem(545015, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545015")] public void TestConversionOperatorGlyph() { TestGlyph( StandardGlyphGroup.GlyphGroupOperator, SymbolKind.Method, methodKind: MethodKind.Conversion); } [Fact] public void TestWithEventsMemberGlyph() { TestGlyph( StandardGlyphGroup.GlyphGroupField, SymbolKind.Property, isWithEvents: true); } private void TestGlyph( StandardGlyphGroup expectedGlyphGroup, SymbolKind kind = SymbolKind.Method, Accessibility declaredAccessibility = Accessibility.NotApplicable, bool isExtensionMethod = true, MethodKind methodKind = MethodKind.Ordinary, INamedTypeSymbol containingType = null, bool isConst = false, ITypeSymbol elementType = null, INamespaceOrTypeSymbol target = null, ITypeSymbol pointedAtType = null, bool isWithEvents = false, TypeKind typeKind = TypeKind.Unknown) { var symbol = CreateSymbolMock(kind, declaredAccessibility, isExtensionMethod, methodKind, containingType, isConst, elementType, target, pointedAtType, isWithEvents, typeKind); Assert.Equal(expectedGlyphGroup, symbol.GetGlyph().GetStandardGlyphGroup()); } private static ISymbol CreateSymbolMock( SymbolKind kind, Accessibility declaredAccessibility = Accessibility.NotApplicable, bool isExtensionMethod = false, MethodKind methodKind = MethodKind.Ordinary, INamedTypeSymbol containingType = null, bool isConst = false, ITypeSymbol elementType = null, INamespaceOrTypeSymbol target = null, ITypeSymbol pointedAtType = null, bool isWithEvents = false, TypeKind typeKind = TypeKind.Unknown) { var symbolMock = new Mock<ISymbol>(MockBehavior.Strict); symbolMock.SetupGet(s => s.Kind).Returns(kind); symbolMock.SetupGet(s => s.DeclaredAccessibility).Returns(declaredAccessibility); symbolMock.SetupGet(s => s.ContainingType).Returns(containingType); if (kind == SymbolKind.ArrayType) { var arrayTypeMock = symbolMock.As<IArrayTypeSymbol>(); arrayTypeMock.SetupGet(s => s.ElementType).Returns(elementType); } if (kind == SymbolKind.Alias) { var aliasMock = symbolMock.As<IAliasSymbol>(); aliasMock.SetupGet(s => s.Target).Returns(target); } if (kind == SymbolKind.Method) { var methodTypeMock = symbolMock.As<IMethodSymbol>(); methodTypeMock.SetupGet(s => s.MethodKind).Returns(methodKind); methodTypeMock.SetupGet(s => s.IsExtensionMethod).Returns(isExtensionMethod); } if (kind == SymbolKind.NamedType) { var namedTypeMock = symbolMock.As<INamedTypeSymbol>(); namedTypeMock.SetupGet(s => s.TypeKind).Returns(typeKind); } if (kind == SymbolKind.Field) { var fieldMock = symbolMock.As<IFieldSymbol>(); fieldMock.SetupGet(s => s.IsConst).Returns(isConst); } if (kind == SymbolKind.PointerType) { var pointerTypeMock = symbolMock.As<IPointerTypeSymbol>(); pointerTypeMock.SetupGet(s => s.PointedAtType).Returns(pointedAtType); } if (kind == SymbolKind.Property) { var propertyMock = symbolMock.As<IPropertySymbol>(); propertyMock.SetupGet(s => s.IsWithEvents).Returns(isWithEvents); } return symbolMock.Object; } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/ExpressionEvaluator/Core/Test/ExpressionCompiler/ExpressionCompilerTestHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable extern alias PDB; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Runtime.CompilerServices; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading; using Microsoft.Cci; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.DiaSymReader; using Microsoft.Metadata.Tools; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; using PDB::Roslyn.Test.Utilities; using PDB::Roslyn.Test.PdbUtilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { internal sealed class Scope { internal readonly int StartOffset; internal readonly int EndOffset; internal readonly ImmutableArray<string> Locals; internal Scope(int startOffset, int endOffset, ImmutableArray<string> locals, bool isEndInclusive) { this.StartOffset = startOffset; this.EndOffset = endOffset + (isEndInclusive ? 1 : 0); this.Locals = locals; } internal int Length { get { return this.EndOffset - this.StartOffset + 1; } } internal bool Contains(int offset) { return (offset >= this.StartOffset) && (offset < this.EndOffset); } } internal static class ExpressionCompilerTestHelpers { internal static CompileResult CompileAssignment( this EvaluationContextBase context, string target, string expr, out string error, CompilationTestData testData = null, DiagnosticFormatter formatter = null) { ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var result = context.CompileAssignment( target, expr, ImmutableArray<Alias>.Empty, formatter ?? DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); // This is a crude way to test the language, but it's convenient to share this test helper. var isCSharp = context.GetType().Namespace.IndexOf("csharp", StringComparison.OrdinalIgnoreCase) >= 0; var expectedFlags = error != null ? DkmClrCompilationResultFlags.None : isCSharp ? DkmClrCompilationResultFlags.PotentialSideEffect : DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult; Assert.Equal(expectedFlags, resultProperties.Flags); Assert.Equal(default(DkmEvaluationResultCategory), resultProperties.Category); Assert.Equal(default(DkmEvaluationResultAccessType), resultProperties.AccessType); Assert.Equal(default(DkmEvaluationResultStorageType), resultProperties.StorageType); Assert.Equal(default(DkmEvaluationResultTypeModifierFlags), resultProperties.ModifierFlags); return result; } internal static CompileResult CompileAssignment( this EvaluationContextBase context, string target, string expr, ImmutableArray<Alias> aliases, DiagnosticFormatter formatter, out ResultProperties resultProperties, out string error, out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities, CultureInfo preferredUICulture, CompilationTestData testData) { var diagnostics = DiagnosticBag.GetInstance(); var result = context.CompileAssignment(target, expr, aliases, diagnostics, out resultProperties, testData); if (diagnostics.HasAnyErrors()) { bool useReferencedModulesOnly; error = context.GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, EvaluationContextBase.SystemCoreIdentity, out useReferencedModulesOnly, out missingAssemblyIdentities); } else { error = null; missingAssemblyIdentities = ImmutableArray<AssemblyIdentity>.Empty; } diagnostics.Free(); return result; } internal static ReadOnlyCollection<byte> CompileGetLocals( this EvaluationContextBase context, ArrayBuilder<LocalAndMethod> locals, bool argumentsOnly, out string typeName, CompilationTestData testData, DiagnosticDescription[] expectedDiagnostics = null) { var diagnostics = DiagnosticBag.GetInstance(); var result = context.CompileGetLocals( locals, argumentsOnly, ImmutableArray<Alias>.Empty, diagnostics, out typeName, testData); diagnostics.Verify(expectedDiagnostics ?? DiagnosticDescription.None); diagnostics.Free(); return result; } internal static CompileResult CompileExpression( this EvaluationContextBase context, string expr, out string error, CompilationTestData testData = null, DiagnosticFormatter formatter = null) { ResultProperties resultProperties; return CompileExpression(context, expr, out resultProperties, out error, testData, formatter); } internal static CompileResult CompileExpression( this EvaluationContextBase context, string expr, out ResultProperties resultProperties, out string error, CompilationTestData testData = null, DiagnosticFormatter formatter = null) { ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var result = context.CompileExpression( expr, DkmEvaluationFlags.TreatAsExpression, ImmutableArray<Alias>.Empty, formatter ?? DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); return result; } internal static CompileResult CompileExpression( this EvaluationContextBase evaluationContext, string expr, DkmEvaluationFlags compilationFlags, ImmutableArray<Alias> aliases, out string error, CompilationTestData testData = null, DiagnosticFormatter formatter = null) { ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var result = evaluationContext.CompileExpression( expr, compilationFlags, aliases, formatter ?? DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); return result; } /// <summary> /// Compile C# expression and emit assembly with evaluation method. /// </summary> /// <returns> /// Result containing generated assembly, type and method names, and any format specifiers. /// </returns> internal static CompileResult CompileExpression( this EvaluationContextBase evaluationContext, string expr, DkmEvaluationFlags compilationFlags, ImmutableArray<Alias> aliases, DiagnosticFormatter formatter, out ResultProperties resultProperties, out string error, out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities, CultureInfo preferredUICulture, CompilationTestData testData) { var diagnostics = DiagnosticBag.GetInstance(); var result = evaluationContext.CompileExpression(expr, compilationFlags, aliases, diagnostics, out resultProperties, testData); if (diagnostics.HasAnyErrors()) { bool useReferencedModulesOnly; error = evaluationContext.GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, EvaluationContextBase.SystemCoreIdentity, out useReferencedModulesOnly, out missingAssemblyIdentities); } else { error = null; missingAssemblyIdentities = ImmutableArray<AssemblyIdentity>.Empty; } diagnostics.Free(); return result; } internal static CompileResult CompileExpressionWithRetry( ImmutableArray<MetadataBlock> metadataBlocks, EvaluationContextBase context, ExpressionCompiler.CompileDelegate<CompileResult> compile, DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr, out string errorMessage) { return ExpressionCompiler.CompileWithRetry( metadataBlocks, DebuggerDiagnosticFormatter.Instance, (blocks, useReferencedModulesOnly) => context, compile, getMetaDataBytesPtr, out errorMessage); } internal static CompileResult CompileExpressionWithRetry( ImmutableArray<MetadataBlock> metadataBlocks, string expr, ImmutableArray<Alias> aliases, ExpressionCompiler.CreateContextDelegate createContext, DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr, out string errorMessage, out CompilationTestData testData) { var r = ExpressionCompiler.CompileWithRetry( metadataBlocks, DebuggerDiagnosticFormatter.Instance, createContext, (context, diagnostics) => { var td = new CompilationTestData(); ResultProperties resultProperties; var compileResult = context.CompileExpression( expr, DkmEvaluationFlags.TreatAsExpression, aliases, diagnostics, out resultProperties, td); return new CompileExpressionResult(compileResult, td); }, getMetaDataBytesPtr, out errorMessage); testData = r.TestData; return r.CompileResult; } private struct CompileExpressionResult { internal readonly CompileResult CompileResult; internal readonly CompilationTestData TestData; internal CompileExpressionResult(CompileResult compileResult, CompilationTestData testData) { this.CompileResult = compileResult; this.TestData = testData; } } internal static TypeDefinition GetTypeDef(this MetadataReader reader, string typeName) { return reader.TypeDefinitions.Select(reader.GetTypeDefinition).First(t => reader.StringComparer.Equals(t.Name, typeName)); } internal static MethodDefinition GetMethodDef(this MetadataReader reader, TypeDefinition typeDef, string methodName) { return typeDef.GetMethods().Select(reader.GetMethodDefinition).First(m => reader.StringComparer.Equals(m.Name, methodName)); } internal static MethodDefinitionHandle GetMethodDefHandle(this MetadataReader reader, TypeDefinition typeDef, string methodName) { return typeDef.GetMethods().First(h => reader.StringComparer.Equals(reader.GetMethodDefinition(h).Name, methodName)); } internal static void CheckTypeParameters(this MetadataReader reader, GenericParameterHandleCollection genericParameters, params string[] expectedNames) { var actualNames = genericParameters.Select(reader.GetGenericParameter).Select(tp => reader.GetString(tp.Name)).ToArray(); Assert.True(expectedNames.SequenceEqual(actualNames)); } internal static AssemblyName GetAssemblyName(this byte[] exeBytes) { using (var reader = new PEReader(ImmutableArray.CreateRange(exeBytes))) { var metadataReader = reader.GetMetadataReader(); var def = metadataReader.GetAssemblyDefinition(); var name = metadataReader.GetString(def.Name); return new AssemblyName() { Name = name, Version = def.Version }; } } internal static Guid GetModuleVersionId(this byte[] exeBytes) { using (var reader = new PEReader(ImmutableArray.CreateRange(exeBytes))) { return reader.GetMetadataReader().GetModuleVersionId(); } } internal static ImmutableArray<string> GetLocalNames(this ISymUnmanagedReader symReader, int methodToken, int methodVersion = 1) { var method = symReader.GetMethodByVersion(methodToken, methodVersion); if (method == null) { return ImmutableArray<string>.Empty; } var scopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance(); method.GetAllScopes(scopes); var names = ArrayBuilder<string>.GetInstance(); foreach (var scope in scopes) { foreach (var local in scope.GetLocals()) { var name = local.GetName(); int slot; local.GetAddressField1(out slot); while (names.Count <= slot) { names.Add(null); } names[slot] = name; } } scopes.Free(); return names.ToImmutableAndFree(); } internal static void VerifyIL( this byte[] assembly, int methodToken, string qualifiedName, string expectedIL, [CallerLineNumber] int expectedValueSourceLine = 0, [CallerFilePath] string expectedValueSourcePath = null) { var parts = qualifiedName.Split('.'); if (parts.Length != 2) { throw new NotImplementedException(); } using (var metadata = ModuleMetadata.CreateFromImage(assembly)) { var module = metadata.Module; var reader = module.MetadataReader; var methodHandle = (MethodDefinitionHandle)MetadataTokens.Handle(methodToken); var methodDef = reader.GetMethodDefinition(methodHandle); var typeDef = reader.GetTypeDefinition(methodDef.GetDeclaringType()); Assert.True(reader.StringComparer.Equals(typeDef.Name, parts[0])); Assert.True(reader.StringComparer.Equals(methodDef.Name, parts[1])); var methodBody = module.GetMethodBodyOrThrow(methodHandle); var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; if (!methodBody.LocalSignature.IsNil) { var visualizer = new MetadataVisualizer(reader, new StringWriter(), MetadataVisualizerOptions.NoHeapReferences); var signature = reader.GetStandaloneSignature(methodBody.LocalSignature); builder.AppendFormat("Locals: {0}", visualizer.StandaloneSignature(signature.Signature)); builder.AppendLine(); } ILVisualizer.Default.DumpMethod( builder, methodBody.MaxStack, methodBody.GetILContent(), ImmutableArray.Create<ILVisualizer.LocalInfo>(), ImmutableArray.Create<ILVisualizer.HandlerSpan>()); var actualIL = pooled.ToStringAndFree(); AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL, escapeQuotes: true, expectedValueSourcePath: expectedValueSourcePath, expectedValueSourceLine: expectedValueSourceLine); } } internal static ImmutableArray<MetadataReference> GetEmittedReferences(Compilation compilation, MetadataReader mdReader) { // Determine the set of references that were actually used // and ignore any references that were dropped in emit. var referenceNames = new HashSet<string>(mdReader.AssemblyReferences.Select(h => GetAssemblyReferenceName(mdReader, h))); return ImmutableArray.CreateRange(compilation.References.Where(r => IsReferenced(r, referenceNames))); } internal static ImmutableArray<Scope> GetScopes(this ISymUnmanagedReader symReader, int methodToken, int methodVersion, bool isEndInclusive) { var method = symReader.GetMethodByVersion(methodToken, methodVersion); if (method == null) { return ImmutableArray<Scope>.Empty; } var scopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance(); method.GetAllScopes(scopes); var result = scopes.SelectAsArray(s => new Scope(s.GetStartOffset(), s.GetEndOffset(), ImmutableArray.CreateRange(s.GetLocals().Select(l => l.GetName())), isEndInclusive)); scopes.Free(); return result; } internal static Scope GetInnermostScope(this ImmutableArray<Scope> scopes, int offset) { Scope result = null; foreach (var scope in scopes) { if (scope.Contains(offset)) { if ((result == null) || (result.Length > scope.Length)) { result = scope; } } } return result; } private static string GetAssemblyReferenceName(MetadataReader reader, AssemblyReferenceHandle handle) { var reference = reader.GetAssemblyReference(handle); return reader.GetString(reference.Name); } private static bool IsReferenced(MetadataReference reference, HashSet<string> referenceNames) { var assemblyMetadata = ((PortableExecutableReference)reference).GetMetadataNoCopy() as AssemblyMetadata; if (assemblyMetadata == null) { // Netmodule. Assume it is referenced. return true; } var name = assemblyMetadata.GetAssembly().Identity.Name; return referenceNames.Contains(name); } internal static ModuleInstance ToModuleInstance(this MetadataReference reference) { return ModuleInstance.Create((PortableExecutableReference)reference); } internal static ModuleInstance ToModuleInstance( this Compilation compilation, DebugInformationFormat debugFormat = DebugInformationFormat.Pdb, bool includeLocalSignatures = true) { var pdbStream = (debugFormat != 0) ? new MemoryStream() : null; var peImage = compilation.EmitToArray(new EmitOptions(debugInformationFormat: debugFormat), pdbStream: pdbStream); var symReader = (debugFormat != 0) ? SymReaderFactory.CreateReader(pdbStream, new PEReader(peImage)) : null; return ModuleInstance.Create(peImage, symReader, includeLocalSignatures); } internal static ModuleInstance GetModuleInstanceForIL(string ilSource) { ImmutableArray<byte> peBytes; ImmutableArray<byte> pdbBytes; CommonTestBase.EmitILToArray(ilSource, appendDefaultHeader: true, includePdb: true, assemblyBytes: out peBytes, pdbBytes: out pdbBytes); return ModuleInstance.Create(peBytes, SymReaderFactory.CreateReader(pdbBytes), includeLocalSignatures: true); } internal static void VerifyLocal<TMethodSymbol>( this CompilationTestData testData, string typeName, LocalAndMethod localAndMethod, string expectedMethodName, string expectedLocalName, string expectedLocalDisplayName, DkmClrCompilationResultFlags expectedFlags, Action<TMethodSymbol> verifyTypeParameters, string expectedILOpt, bool expectedGeneric, string expectedValueSourcePath, int expectedValueSourceLine) where TMethodSymbol : IMethodSymbolInternal { Assert.Equal(expectedLocalName, localAndMethod.LocalName); Assert.Equal(expectedLocalDisplayName, localAndMethod.LocalDisplayName); Assert.True(expectedMethodName.StartsWith(localAndMethod.MethodName, StringComparison.Ordinal), expectedMethodName + " does not start with " + localAndMethod.MethodName); // Expected name may include type arguments and parameters. Assert.Equal(expectedFlags, localAndMethod.Flags); var methodData = testData.GetMethodData(typeName + "." + expectedMethodName); verifyTypeParameters((TMethodSymbol)methodData.Method); if (expectedILOpt != null) { string actualIL = methodData.GetMethodIL(); AssertEx.AssertEqualToleratingWhitespaceDifferences( expectedILOpt, actualIL, escapeQuotes: true, expectedValueSourcePath: expectedValueSourcePath, expectedValueSourceLine: expectedValueSourceLine); } Assert.Equal(((Cci.IMethodDefinition)methodData.Method.GetCciAdapter()).CallingConvention, expectedGeneric ? Cci.CallingConvention.Generic : Cci.CallingConvention.Default); } internal static void VerifyResolutionRequests(EEMetadataReferenceResolver resolver, (AssemblyIdentity, AssemblyIdentity, int)[] expectedRequests) { #if DEBUG var expected = ArrayBuilder<(AssemblyIdentity, AssemblyIdentity, int)>.GetInstance(); var actual = ArrayBuilder<(AssemblyIdentity, AssemblyIdentity, int)>.GetInstance(); expected.AddRange(expectedRequests); sort(expected); actual.AddRange(resolver.Requests.Select(pair => (pair.Key, pair.Value.Identity, pair.Value.Count))); sort(actual); AssertEx.Equal(expected, actual); actual.Free(); expected.Free(); void sort(ArrayBuilder<(AssemblyIdentity, AssemblyIdentity, int)> builder) { builder.Sort((x, y) => AssemblyIdentityComparer.SimpleNameComparer.Compare(x.Item1.GetDisplayName(), y.Item1.GetDisplayName())); } #endif } internal static void VerifyAppDomainMetadataContext<TAssemblyContext>(MetadataContext<TAssemblyContext> metadataContext, Guid[] moduleVersionIds) where TAssemblyContext : struct { var actualIds = metadataContext.AssemblyContexts.Keys.Select(key => key.ModuleVersionId.ToString()).ToArray(); Array.Sort(actualIds); var expectedIds = moduleVersionIds.Select(mvid => mvid.ToString()).ToArray(); Array.Sort(expectedIds); AssertEx.Equal(expectedIds, actualIds); } internal static ISymUnmanagedReader ConstructSymReaderWithImports(ImmutableArray<byte> peImage, string methodName, params string[] importStrings) { using (var peReader = new PEReader(peImage)) { var metadataReader = peReader.GetMetadataReader(); var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, methodName)); var methodToken = metadataReader.GetToken(methodHandle); return new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes> { { methodToken, new MethodDebugInfoBytes.Builder(new [] { importStrings }).Build() }, }.ToImmutableDictionary()); } } internal const uint NoILOffset = 0xffffffff; internal static readonly MetadataReference IntrinsicAssemblyReference = GetIntrinsicAssemblyReference(); internal static ImmutableArray<MetadataReference> AddIntrinsicAssembly(this ImmutableArray<MetadataReference> references) { var builder = ArrayBuilder<MetadataReference>.GetInstance(); builder.AddRange(references); builder.Add(IntrinsicAssemblyReference); return builder.ToImmutableAndFree(); } private static MetadataReference GetIntrinsicAssemblyReference() { var source = @".assembly extern mscorlib { } .class public Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods { .method public static object GetObjectAtAddress(uint64 address) { ldnull throw } .method public static class [mscorlib]System.Exception GetException() { ldnull throw } .method public static class [mscorlib]System.Exception GetStowedException() { ldnull throw } .method public static object GetReturnValue(int32 index) { ldnull throw } .method public static void CreateVariable(class [mscorlib]System.Type 'type', string name, valuetype [mscorlib]System.Guid customTypeInfoPayloadTypeId, uint8[] customTypeInfoPayload) { ldnull throw } .method public static object GetObjectByAlias(string name) { ldnull throw } .method public static !!T& GetVariableAddress<T>(string name) { ldnull throw } }"; return CommonTestBase.CompileIL(source); } /// <summary> /// Return MetadataReferences to the .winmd assemblies /// for the given namespaces. /// </summary> internal static ImmutableArray<MetadataReference> GetRuntimeWinMds(params string[] namespaces) { var paths = new HashSet<string>(); foreach (var @namespace in namespaces) { foreach (var path in WindowsRuntimeMetadata.ResolveNamespace(@namespace, null)) { paths.Add(path); } } return ImmutableArray.CreateRange(paths.Select(GetAssembly)); } private const string Version1_3CLRString = "WindowsRuntime 1.3;CLR v4.0.30319"; private const string Version1_3String = "WindowsRuntime 1.3"; private const string Version1_4String = "WindowsRuntime 1.4"; private static readonly int s_versionStringLength = Version1_3CLRString.Length; private static readonly byte[] s_version1_3CLRBytes = ToByteArray(Version1_3CLRString, s_versionStringLength); private static readonly byte[] s_version1_3Bytes = ToByteArray(Version1_3String, s_versionStringLength); private static readonly byte[] s_version1_4Bytes = ToByteArray(Version1_4String, s_versionStringLength); private static byte[] ToByteArray(string str, int length) { var bytes = new byte[length]; for (int i = 0; i < str.Length; i++) { bytes[i] = (byte)str[i]; } return bytes; } internal static byte[] ToVersion1_3(byte[] bytes) { return ToVersion(bytes, s_version1_3CLRBytes, s_version1_3Bytes); } internal static byte[] ToVersion1_4(byte[] bytes) { return ToVersion(bytes, s_version1_3CLRBytes, s_version1_4Bytes); } private static byte[] ToVersion(byte[] bytes, byte[] from, byte[] to) { int n = bytes.Length; var copy = new byte[n]; Array.Copy(bytes, copy, n); int index = IndexOf(copy, from); Array.Copy(to, 0, copy, index, to.Length); return copy; } private static int IndexOf(byte[] a, byte[] b) { int m = b.Length; int n = a.Length - m; for (int x = 0; x < n; x++) { var matches = true; for (int y = 0; y < m; y++) { if (a[x + y] != b[y]) { matches = false; break; } } if (matches) { return x; } } return -1; } private static MetadataReference GetAssembly(string path) { var bytes = File.ReadAllBytes(path); var metadata = ModuleMetadata.CreateFromImage(bytes); return metadata.GetReference(filePath: path); } internal static uint GetOffset(int methodToken, ISymUnmanagedReader symReader, int atLineNumber = -1) { int ilOffset; if (symReader == null) { ilOffset = 0; } else { var symMethod = symReader.GetMethod(methodToken); if (symMethod == null) { ilOffset = 0; } else { var sequencePoints = symMethod.GetSequencePoints(); ilOffset = atLineNumber < 0 ? sequencePoints.Where(sp => sp.StartLine != Cci.SequencePoint.HiddenLine).Select(sp => sp.Offset).FirstOrDefault() : sequencePoints.First(sp => sp.StartLine == atLineNumber).Offset; } } Assert.InRange(ilOffset, 0, int.MaxValue); return (uint)ilOffset; } internal static string GetMethodOrTypeSignatureParts(string signature, out string[] parameterTypeNames) { var parameterListStart = signature.IndexOf('('); if (parameterListStart < 0) { parameterTypeNames = null; return signature; } var parameters = signature.Substring(parameterListStart + 1, signature.Length - parameterListStart - 2); var methodName = signature.Substring(0, parameterListStart); parameterTypeNames = (parameters.Length == 0) ? new string[0] : parameters.Split(','); return methodName; } internal static unsafe ModuleMetadata ToModuleMetadata(this PEMemoryBlock metadata, bool ignoreAssemblyRefs) { return ModuleMetadata.CreateFromMetadata( (IntPtr)metadata.Pointer, metadata.Length, includeEmbeddedInteropTypes: false, ignoreAssemblyRefs: ignoreAssemblyRefs); } internal static unsafe MetadataReader ToMetadataReader(this PEMemoryBlock metadata) { return new MetadataReader(metadata.Pointer, metadata.Length, MetadataReaderOptions.None); } internal static void EmitCorLibWithAssemblyReferences( Compilation comp, string pdbPath, Func<CommonPEModuleBuilder, EmitOptions, CommonPEModuleBuilder> getModuleBuilder, out ImmutableArray<byte> peBytes, out ImmutableArray<byte> pdbBytes) { var diagnostics = DiagnosticBag.GetInstance(); var emitOptions = EmitOptions.Default.WithRuntimeMetadataVersion("0.0.0.0").WithDebugInformationFormat(DebugInformationFormat.PortablePdb); var moduleBuilder = comp.CheckOptionsAndCreateModuleBuilder( diagnostics, null, emitOptions, null, null, null, null, default(CancellationToken)); // Wrap the module builder in a module builder that // reports the "System.Object" type as having no base type. moduleBuilder = getModuleBuilder(moduleBuilder, emitOptions); bool result = comp.Compile( moduleBuilder, emittingPdb: pdbPath != null, diagnostics: diagnostics, filterOpt: null, cancellationToken: default(CancellationToken)); using (var peStream = new MemoryStream()) { using (var pdbStream = new MemoryStream()) { PeWriter.WritePeToStream( new EmitContext(moduleBuilder, null, diagnostics, metadataOnly: false, includePrivateMembers: true), comp.MessageProvider, () => peStream, () => pdbStream, nativePdbWriterOpt: null, pdbPathOpt: null, metadataOnly: true, isDeterministic: false, emitTestCoverageData: false, privateKeyOpt: null, cancellationToken: default(CancellationToken)); peBytes = peStream.ToImmutable(); pdbBytes = pdbStream.ToImmutable(); } } diagnostics.Verify(); diagnostics.Free(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable extern alias PDB; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Runtime.CompilerServices; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading; using Microsoft.Cci; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.DiaSymReader; using Microsoft.Metadata.Tools; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; using PDB::Roslyn.Test.Utilities; using PDB::Roslyn.Test.PdbUtilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { internal sealed class Scope { internal readonly int StartOffset; internal readonly int EndOffset; internal readonly ImmutableArray<string> Locals; internal Scope(int startOffset, int endOffset, ImmutableArray<string> locals, bool isEndInclusive) { this.StartOffset = startOffset; this.EndOffset = endOffset + (isEndInclusive ? 1 : 0); this.Locals = locals; } internal int Length { get { return this.EndOffset - this.StartOffset + 1; } } internal bool Contains(int offset) { return (offset >= this.StartOffset) && (offset < this.EndOffset); } } internal static class ExpressionCompilerTestHelpers { internal static CompileResult CompileAssignment( this EvaluationContextBase context, string target, string expr, out string error, CompilationTestData testData = null, DiagnosticFormatter formatter = null) { ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var result = context.CompileAssignment( target, expr, ImmutableArray<Alias>.Empty, formatter ?? DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); // This is a crude way to test the language, but it's convenient to share this test helper. var isCSharp = context.GetType().Namespace.IndexOf("csharp", StringComparison.OrdinalIgnoreCase) >= 0; var expectedFlags = error != null ? DkmClrCompilationResultFlags.None : isCSharp ? DkmClrCompilationResultFlags.PotentialSideEffect : DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult; Assert.Equal(expectedFlags, resultProperties.Flags); Assert.Equal(default(DkmEvaluationResultCategory), resultProperties.Category); Assert.Equal(default(DkmEvaluationResultAccessType), resultProperties.AccessType); Assert.Equal(default(DkmEvaluationResultStorageType), resultProperties.StorageType); Assert.Equal(default(DkmEvaluationResultTypeModifierFlags), resultProperties.ModifierFlags); return result; } internal static CompileResult CompileAssignment( this EvaluationContextBase context, string target, string expr, ImmutableArray<Alias> aliases, DiagnosticFormatter formatter, out ResultProperties resultProperties, out string error, out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities, CultureInfo preferredUICulture, CompilationTestData testData) { var diagnostics = DiagnosticBag.GetInstance(); var result = context.CompileAssignment(target, expr, aliases, diagnostics, out resultProperties, testData); if (diagnostics.HasAnyErrors()) { bool useReferencedModulesOnly; error = context.GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, EvaluationContextBase.SystemCoreIdentity, out useReferencedModulesOnly, out missingAssemblyIdentities); } else { error = null; missingAssemblyIdentities = ImmutableArray<AssemblyIdentity>.Empty; } diagnostics.Free(); return result; } internal static ReadOnlyCollection<byte> CompileGetLocals( this EvaluationContextBase context, ArrayBuilder<LocalAndMethod> locals, bool argumentsOnly, out string typeName, CompilationTestData testData, DiagnosticDescription[] expectedDiagnostics = null) { var diagnostics = DiagnosticBag.GetInstance(); var result = context.CompileGetLocals( locals, argumentsOnly, ImmutableArray<Alias>.Empty, diagnostics, out typeName, testData); diagnostics.Verify(expectedDiagnostics ?? DiagnosticDescription.None); diagnostics.Free(); return result; } internal static CompileResult CompileExpression( this EvaluationContextBase context, string expr, out string error, CompilationTestData testData = null, DiagnosticFormatter formatter = null) { ResultProperties resultProperties; return CompileExpression(context, expr, out resultProperties, out error, testData, formatter); } internal static CompileResult CompileExpression( this EvaluationContextBase context, string expr, out ResultProperties resultProperties, out string error, CompilationTestData testData = null, DiagnosticFormatter formatter = null) { ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var result = context.CompileExpression( expr, DkmEvaluationFlags.TreatAsExpression, ImmutableArray<Alias>.Empty, formatter ?? DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); return result; } internal static CompileResult CompileExpression( this EvaluationContextBase evaluationContext, string expr, DkmEvaluationFlags compilationFlags, ImmutableArray<Alias> aliases, out string error, CompilationTestData testData = null, DiagnosticFormatter formatter = null) { ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var result = evaluationContext.CompileExpression( expr, compilationFlags, aliases, formatter ?? DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); return result; } /// <summary> /// Compile C# expression and emit assembly with evaluation method. /// </summary> /// <returns> /// Result containing generated assembly, type and method names, and any format specifiers. /// </returns> internal static CompileResult CompileExpression( this EvaluationContextBase evaluationContext, string expr, DkmEvaluationFlags compilationFlags, ImmutableArray<Alias> aliases, DiagnosticFormatter formatter, out ResultProperties resultProperties, out string error, out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities, CultureInfo preferredUICulture, CompilationTestData testData) { var diagnostics = DiagnosticBag.GetInstance(); var result = evaluationContext.CompileExpression(expr, compilationFlags, aliases, diagnostics, out resultProperties, testData); if (diagnostics.HasAnyErrors()) { bool useReferencedModulesOnly; error = evaluationContext.GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, EvaluationContextBase.SystemCoreIdentity, out useReferencedModulesOnly, out missingAssemblyIdentities); } else { error = null; missingAssemblyIdentities = ImmutableArray<AssemblyIdentity>.Empty; } diagnostics.Free(); return result; } internal static CompileResult CompileExpressionWithRetry( ImmutableArray<MetadataBlock> metadataBlocks, EvaluationContextBase context, ExpressionCompiler.CompileDelegate<CompileResult> compile, DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr, out string errorMessage) { return ExpressionCompiler.CompileWithRetry( metadataBlocks, DebuggerDiagnosticFormatter.Instance, (blocks, useReferencedModulesOnly) => context, compile, getMetaDataBytesPtr, out errorMessage); } internal static CompileResult CompileExpressionWithRetry( ImmutableArray<MetadataBlock> metadataBlocks, string expr, ImmutableArray<Alias> aliases, ExpressionCompiler.CreateContextDelegate createContext, DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr, out string errorMessage, out CompilationTestData testData) { var r = ExpressionCompiler.CompileWithRetry( metadataBlocks, DebuggerDiagnosticFormatter.Instance, createContext, (context, diagnostics) => { var td = new CompilationTestData(); ResultProperties resultProperties; var compileResult = context.CompileExpression( expr, DkmEvaluationFlags.TreatAsExpression, aliases, diagnostics, out resultProperties, td); return new CompileExpressionResult(compileResult, td); }, getMetaDataBytesPtr, out errorMessage); testData = r.TestData; return r.CompileResult; } private struct CompileExpressionResult { internal readonly CompileResult CompileResult; internal readonly CompilationTestData TestData; internal CompileExpressionResult(CompileResult compileResult, CompilationTestData testData) { this.CompileResult = compileResult; this.TestData = testData; } } internal static TypeDefinition GetTypeDef(this MetadataReader reader, string typeName) { return reader.TypeDefinitions.Select(reader.GetTypeDefinition).First(t => reader.StringComparer.Equals(t.Name, typeName)); } internal static MethodDefinition GetMethodDef(this MetadataReader reader, TypeDefinition typeDef, string methodName) { return typeDef.GetMethods().Select(reader.GetMethodDefinition).First(m => reader.StringComparer.Equals(m.Name, methodName)); } internal static MethodDefinitionHandle GetMethodDefHandle(this MetadataReader reader, TypeDefinition typeDef, string methodName) { return typeDef.GetMethods().First(h => reader.StringComparer.Equals(reader.GetMethodDefinition(h).Name, methodName)); } internal static void CheckTypeParameters(this MetadataReader reader, GenericParameterHandleCollection genericParameters, params string[] expectedNames) { var actualNames = genericParameters.Select(reader.GetGenericParameter).Select(tp => reader.GetString(tp.Name)).ToArray(); Assert.True(expectedNames.SequenceEqual(actualNames)); } internal static AssemblyName GetAssemblyName(this byte[] exeBytes) { using (var reader = new PEReader(ImmutableArray.CreateRange(exeBytes))) { var metadataReader = reader.GetMetadataReader(); var def = metadataReader.GetAssemblyDefinition(); var name = metadataReader.GetString(def.Name); return new AssemblyName() { Name = name, Version = def.Version }; } } internal static Guid GetModuleVersionId(this byte[] exeBytes) { using (var reader = new PEReader(ImmutableArray.CreateRange(exeBytes))) { return reader.GetMetadataReader().GetModuleVersionId(); } } internal static ImmutableArray<string> GetLocalNames(this ISymUnmanagedReader symReader, int methodToken, int methodVersion = 1) { var method = symReader.GetMethodByVersion(methodToken, methodVersion); if (method == null) { return ImmutableArray<string>.Empty; } var scopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance(); method.GetAllScopes(scopes); var names = ArrayBuilder<string>.GetInstance(); foreach (var scope in scopes) { foreach (var local in scope.GetLocals()) { var name = local.GetName(); int slot; local.GetAddressField1(out slot); while (names.Count <= slot) { names.Add(null); } names[slot] = name; } } scopes.Free(); return names.ToImmutableAndFree(); } internal static void VerifyIL( this byte[] assembly, int methodToken, string qualifiedName, string expectedIL, [CallerLineNumber] int expectedValueSourceLine = 0, [CallerFilePath] string expectedValueSourcePath = null) { var parts = qualifiedName.Split('.'); if (parts.Length != 2) { throw new NotImplementedException(); } using (var metadata = ModuleMetadata.CreateFromImage(assembly)) { var module = metadata.Module; var reader = module.MetadataReader; var methodHandle = (MethodDefinitionHandle)MetadataTokens.Handle(methodToken); var methodDef = reader.GetMethodDefinition(methodHandle); var typeDef = reader.GetTypeDefinition(methodDef.GetDeclaringType()); Assert.True(reader.StringComparer.Equals(typeDef.Name, parts[0])); Assert.True(reader.StringComparer.Equals(methodDef.Name, parts[1])); var methodBody = module.GetMethodBodyOrThrow(methodHandle); var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; if (!methodBody.LocalSignature.IsNil) { var visualizer = new MetadataVisualizer(reader, new StringWriter(), MetadataVisualizerOptions.NoHeapReferences); var signature = reader.GetStandaloneSignature(methodBody.LocalSignature); builder.AppendFormat("Locals: {0}", visualizer.StandaloneSignature(signature.Signature)); builder.AppendLine(); } ILVisualizer.Default.DumpMethod( builder, methodBody.MaxStack, methodBody.GetILContent(), ImmutableArray.Create<ILVisualizer.LocalInfo>(), ImmutableArray.Create<ILVisualizer.HandlerSpan>()); var actualIL = pooled.ToStringAndFree(); AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL, escapeQuotes: true, expectedValueSourcePath: expectedValueSourcePath, expectedValueSourceLine: expectedValueSourceLine); } } internal static ImmutableArray<MetadataReference> GetEmittedReferences(Compilation compilation, MetadataReader mdReader) { // Determine the set of references that were actually used // and ignore any references that were dropped in emit. var referenceNames = new HashSet<string>(mdReader.AssemblyReferences.Select(h => GetAssemblyReferenceName(mdReader, h))); return ImmutableArray.CreateRange(compilation.References.Where(r => IsReferenced(r, referenceNames))); } internal static ImmutableArray<Scope> GetScopes(this ISymUnmanagedReader symReader, int methodToken, int methodVersion, bool isEndInclusive) { var method = symReader.GetMethodByVersion(methodToken, methodVersion); if (method == null) { return ImmutableArray<Scope>.Empty; } var scopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance(); method.GetAllScopes(scopes); var result = scopes.SelectAsArray(s => new Scope(s.GetStartOffset(), s.GetEndOffset(), ImmutableArray.CreateRange(s.GetLocals().Select(l => l.GetName())), isEndInclusive)); scopes.Free(); return result; } internal static Scope GetInnermostScope(this ImmutableArray<Scope> scopes, int offset) { Scope result = null; foreach (var scope in scopes) { if (scope.Contains(offset)) { if ((result == null) || (result.Length > scope.Length)) { result = scope; } } } return result; } private static string GetAssemblyReferenceName(MetadataReader reader, AssemblyReferenceHandle handle) { var reference = reader.GetAssemblyReference(handle); return reader.GetString(reference.Name); } private static bool IsReferenced(MetadataReference reference, HashSet<string> referenceNames) { var assemblyMetadata = ((PortableExecutableReference)reference).GetMetadataNoCopy() as AssemblyMetadata; if (assemblyMetadata == null) { // Netmodule. Assume it is referenced. return true; } var name = assemblyMetadata.GetAssembly().Identity.Name; return referenceNames.Contains(name); } internal static ModuleInstance ToModuleInstance(this MetadataReference reference) { return ModuleInstance.Create((PortableExecutableReference)reference); } internal static ModuleInstance ToModuleInstance( this Compilation compilation, DebugInformationFormat debugFormat = DebugInformationFormat.Pdb, bool includeLocalSignatures = true) { var pdbStream = (debugFormat != 0) ? new MemoryStream() : null; var peImage = compilation.EmitToArray(new EmitOptions(debugInformationFormat: debugFormat), pdbStream: pdbStream); var symReader = (debugFormat != 0) ? SymReaderFactory.CreateReader(pdbStream, new PEReader(peImage)) : null; return ModuleInstance.Create(peImage, symReader, includeLocalSignatures); } internal static ModuleInstance GetModuleInstanceForIL(string ilSource) { ImmutableArray<byte> peBytes; ImmutableArray<byte> pdbBytes; CommonTestBase.EmitILToArray(ilSource, appendDefaultHeader: true, includePdb: true, assemblyBytes: out peBytes, pdbBytes: out pdbBytes); return ModuleInstance.Create(peBytes, SymReaderFactory.CreateReader(pdbBytes), includeLocalSignatures: true); } internal static void VerifyLocal<TMethodSymbol>( this CompilationTestData testData, string typeName, LocalAndMethod localAndMethod, string expectedMethodName, string expectedLocalName, string expectedLocalDisplayName, DkmClrCompilationResultFlags expectedFlags, Action<TMethodSymbol> verifyTypeParameters, string expectedILOpt, bool expectedGeneric, string expectedValueSourcePath, int expectedValueSourceLine) where TMethodSymbol : IMethodSymbolInternal { Assert.Equal(expectedLocalName, localAndMethod.LocalName); Assert.Equal(expectedLocalDisplayName, localAndMethod.LocalDisplayName); Assert.True(expectedMethodName.StartsWith(localAndMethod.MethodName, StringComparison.Ordinal), expectedMethodName + " does not start with " + localAndMethod.MethodName); // Expected name may include type arguments and parameters. Assert.Equal(expectedFlags, localAndMethod.Flags); var methodData = testData.GetMethodData(typeName + "." + expectedMethodName); verifyTypeParameters((TMethodSymbol)methodData.Method); if (expectedILOpt != null) { string actualIL = methodData.GetMethodIL(); AssertEx.AssertEqualToleratingWhitespaceDifferences( expectedILOpt, actualIL, escapeQuotes: true, expectedValueSourcePath: expectedValueSourcePath, expectedValueSourceLine: expectedValueSourceLine); } Assert.Equal(((Cci.IMethodDefinition)methodData.Method.GetCciAdapter()).CallingConvention, expectedGeneric ? Cci.CallingConvention.Generic : Cci.CallingConvention.Default); } internal static void VerifyResolutionRequests(EEMetadataReferenceResolver resolver, (AssemblyIdentity, AssemblyIdentity, int)[] expectedRequests) { #if DEBUG var expected = ArrayBuilder<(AssemblyIdentity, AssemblyIdentity, int)>.GetInstance(); var actual = ArrayBuilder<(AssemblyIdentity, AssemblyIdentity, int)>.GetInstance(); expected.AddRange(expectedRequests); sort(expected); actual.AddRange(resolver.Requests.Select(pair => (pair.Key, pair.Value.Identity, pair.Value.Count))); sort(actual); AssertEx.Equal(expected, actual); actual.Free(); expected.Free(); void sort(ArrayBuilder<(AssemblyIdentity, AssemblyIdentity, int)> builder) { builder.Sort((x, y) => AssemblyIdentityComparer.SimpleNameComparer.Compare(x.Item1.GetDisplayName(), y.Item1.GetDisplayName())); } #endif } internal static void VerifyAppDomainMetadataContext<TAssemblyContext>(MetadataContext<TAssemblyContext> metadataContext, Guid[] moduleVersionIds) where TAssemblyContext : struct { var actualIds = metadataContext.AssemblyContexts.Keys.Select(key => key.ModuleVersionId.ToString()).ToArray(); Array.Sort(actualIds); var expectedIds = moduleVersionIds.Select(mvid => mvid.ToString()).ToArray(); Array.Sort(expectedIds); AssertEx.Equal(expectedIds, actualIds); } internal static ISymUnmanagedReader ConstructSymReaderWithImports(ImmutableArray<byte> peImage, string methodName, params string[] importStrings) { using (var peReader = new PEReader(peImage)) { var metadataReader = peReader.GetMetadataReader(); var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, methodName)); var methodToken = metadataReader.GetToken(methodHandle); return new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes> { { methodToken, new MethodDebugInfoBytes.Builder(new [] { importStrings }).Build() }, }.ToImmutableDictionary()); } } internal const uint NoILOffset = 0xffffffff; internal static readonly MetadataReference IntrinsicAssemblyReference = GetIntrinsicAssemblyReference(); internal static ImmutableArray<MetadataReference> AddIntrinsicAssembly(this ImmutableArray<MetadataReference> references) { var builder = ArrayBuilder<MetadataReference>.GetInstance(); builder.AddRange(references); builder.Add(IntrinsicAssemblyReference); return builder.ToImmutableAndFree(); } private static MetadataReference GetIntrinsicAssemblyReference() { var source = @".assembly extern mscorlib { } .class public Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods { .method public static object GetObjectAtAddress(uint64 address) { ldnull throw } .method public static class [mscorlib]System.Exception GetException() { ldnull throw } .method public static class [mscorlib]System.Exception GetStowedException() { ldnull throw } .method public static object GetReturnValue(int32 index) { ldnull throw } .method public static void CreateVariable(class [mscorlib]System.Type 'type', string name, valuetype [mscorlib]System.Guid customTypeInfoPayloadTypeId, uint8[] customTypeInfoPayload) { ldnull throw } .method public static object GetObjectByAlias(string name) { ldnull throw } .method public static !!T& GetVariableAddress<T>(string name) { ldnull throw } }"; return CommonTestBase.CompileIL(source); } /// <summary> /// Return MetadataReferences to the .winmd assemblies /// for the given namespaces. /// </summary> internal static ImmutableArray<MetadataReference> GetRuntimeWinMds(params string[] namespaces) { var paths = new HashSet<string>(); foreach (var @namespace in namespaces) { foreach (var path in WindowsRuntimeMetadata.ResolveNamespace(@namespace, null)) { paths.Add(path); } } return ImmutableArray.CreateRange(paths.Select(GetAssembly)); } private const string Version1_3CLRString = "WindowsRuntime 1.3;CLR v4.0.30319"; private const string Version1_3String = "WindowsRuntime 1.3"; private const string Version1_4String = "WindowsRuntime 1.4"; private static readonly int s_versionStringLength = Version1_3CLRString.Length; private static readonly byte[] s_version1_3CLRBytes = ToByteArray(Version1_3CLRString, s_versionStringLength); private static readonly byte[] s_version1_3Bytes = ToByteArray(Version1_3String, s_versionStringLength); private static readonly byte[] s_version1_4Bytes = ToByteArray(Version1_4String, s_versionStringLength); private static byte[] ToByteArray(string str, int length) { var bytes = new byte[length]; for (int i = 0; i < str.Length; i++) { bytes[i] = (byte)str[i]; } return bytes; } internal static byte[] ToVersion1_3(byte[] bytes) { return ToVersion(bytes, s_version1_3CLRBytes, s_version1_3Bytes); } internal static byte[] ToVersion1_4(byte[] bytes) { return ToVersion(bytes, s_version1_3CLRBytes, s_version1_4Bytes); } private static byte[] ToVersion(byte[] bytes, byte[] from, byte[] to) { int n = bytes.Length; var copy = new byte[n]; Array.Copy(bytes, copy, n); int index = IndexOf(copy, from); Array.Copy(to, 0, copy, index, to.Length); return copy; } private static int IndexOf(byte[] a, byte[] b) { int m = b.Length; int n = a.Length - m; for (int x = 0; x < n; x++) { var matches = true; for (int y = 0; y < m; y++) { if (a[x + y] != b[y]) { matches = false; break; } } if (matches) { return x; } } return -1; } private static MetadataReference GetAssembly(string path) { var bytes = File.ReadAllBytes(path); var metadata = ModuleMetadata.CreateFromImage(bytes); return metadata.GetReference(filePath: path); } internal static uint GetOffset(int methodToken, ISymUnmanagedReader symReader, int atLineNumber = -1) { int ilOffset; if (symReader == null) { ilOffset = 0; } else { var symMethod = symReader.GetMethod(methodToken); if (symMethod == null) { ilOffset = 0; } else { var sequencePoints = symMethod.GetSequencePoints(); ilOffset = atLineNumber < 0 ? sequencePoints.Where(sp => sp.StartLine != Cci.SequencePoint.HiddenLine).Select(sp => sp.Offset).FirstOrDefault() : sequencePoints.First(sp => sp.StartLine == atLineNumber).Offset; } } Assert.InRange(ilOffset, 0, int.MaxValue); return (uint)ilOffset; } internal static string GetMethodOrTypeSignatureParts(string signature, out string[] parameterTypeNames) { var parameterListStart = signature.IndexOf('('); if (parameterListStart < 0) { parameterTypeNames = null; return signature; } var parameters = signature.Substring(parameterListStart + 1, signature.Length - parameterListStart - 2); var methodName = signature.Substring(0, parameterListStart); parameterTypeNames = (parameters.Length == 0) ? new string[0] : parameters.Split(','); return methodName; } internal static unsafe ModuleMetadata ToModuleMetadata(this PEMemoryBlock metadata, bool ignoreAssemblyRefs) { return ModuleMetadata.CreateFromMetadata( (IntPtr)metadata.Pointer, metadata.Length, includeEmbeddedInteropTypes: false, ignoreAssemblyRefs: ignoreAssemblyRefs); } internal static unsafe MetadataReader ToMetadataReader(this PEMemoryBlock metadata) { return new MetadataReader(metadata.Pointer, metadata.Length, MetadataReaderOptions.None); } internal static void EmitCorLibWithAssemblyReferences( Compilation comp, string pdbPath, Func<CommonPEModuleBuilder, EmitOptions, CommonPEModuleBuilder> getModuleBuilder, out ImmutableArray<byte> peBytes, out ImmutableArray<byte> pdbBytes) { var diagnostics = DiagnosticBag.GetInstance(); var emitOptions = EmitOptions.Default.WithRuntimeMetadataVersion("0.0.0.0").WithDebugInformationFormat(DebugInformationFormat.PortablePdb); var moduleBuilder = comp.CheckOptionsAndCreateModuleBuilder( diagnostics, null, emitOptions, null, null, null, null, default(CancellationToken)); // Wrap the module builder in a module builder that // reports the "System.Object" type as having no base type. moduleBuilder = getModuleBuilder(moduleBuilder, emitOptions); bool result = comp.Compile( moduleBuilder, emittingPdb: pdbPath != null, diagnostics: diagnostics, filterOpt: null, cancellationToken: default(CancellationToken)); using (var peStream = new MemoryStream()) { using (var pdbStream = new MemoryStream()) { PeWriter.WritePeToStream( new EmitContext(moduleBuilder, null, diagnostics, metadataOnly: false, includePrivateMembers: true), comp.MessageProvider, () => peStream, () => pdbStream, nativePdbWriterOpt: null, pdbPathOpt: null, metadataOnly: true, isDeterministic: false, emitTestCoverageData: false, privateKeyOpt: null, cancellationToken: default(CancellationToken)); peBytes = peStream.ToImmutable(); pdbBytes = pdbStream.ToImmutable(); } } diagnostics.Verify(); diagnostics.Free(); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Portable/Binder/LockBinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class LockBinder : LockOrUsingBinder { private readonly LockStatementSyntax _syntax; public LockBinder(Binder enclosing, LockStatementSyntax syntax) : base(enclosing) { _syntax = syntax; } protected override ExpressionSyntax TargetExpressionSyntax { get { return _syntax.Expression; } } internal override BoundStatement BindLockStatementParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { // Allow method groups during binding and then rule them out when we check that the expression has // a reference type. ExpressionSyntax exprSyntax = TargetExpressionSyntax; BoundExpression expr = BindTargetExpression(diagnostics, originalBinder); TypeSymbol exprType = expr.Type; bool hasErrors = false; if ((object)exprType == null) { if (expr.ConstantValue != ConstantValue.Null || Compilation.FeatureStrictEnabled) // Dev10 allows the null literal. { Error(diagnostics, ErrorCode.ERR_LockNeedsReference, exprSyntax, expr.Display); hasErrors = true; } } else if (!exprType.IsReferenceType && (exprType.IsValueType || Compilation.FeatureStrictEnabled)) { Error(diagnostics, ErrorCode.ERR_LockNeedsReference, exprSyntax, exprType); hasErrors = true; } BoundStatement stmt = originalBinder.BindPossibleEmbeddedStatement(_syntax.Statement, diagnostics); Debug.Assert(this.Locals.IsDefaultOrEmpty); return new BoundLockStatement(_syntax, expr, stmt, hasErrors); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class LockBinder : LockOrUsingBinder { private readonly LockStatementSyntax _syntax; public LockBinder(Binder enclosing, LockStatementSyntax syntax) : base(enclosing) { _syntax = syntax; } protected override ExpressionSyntax TargetExpressionSyntax { get { return _syntax.Expression; } } internal override BoundStatement BindLockStatementParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { // Allow method groups during binding and then rule them out when we check that the expression has // a reference type. ExpressionSyntax exprSyntax = TargetExpressionSyntax; BoundExpression expr = BindTargetExpression(diagnostics, originalBinder); TypeSymbol exprType = expr.Type; bool hasErrors = false; if ((object)exprType == null) { if (expr.ConstantValue != ConstantValue.Null || Compilation.FeatureStrictEnabled) // Dev10 allows the null literal. { Error(diagnostics, ErrorCode.ERR_LockNeedsReference, exprSyntax, expr.Display); hasErrors = true; } } else if (!exprType.IsReferenceType && (exprType.IsValueType || Compilation.FeatureStrictEnabled)) { Error(diagnostics, ErrorCode.ERR_LockNeedsReference, exprSyntax, exprType); hasErrors = true; } BoundStatement stmt = originalBinder.BindPossibleEmbeddedStatement(_syntax.Statement, diagnostics); Debug.Assert(this.Locals.IsDefaultOrEmpty); return new BoundLockStatement(_syntax, expr, stmt, hasErrors); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/Core/Portable/ImplementType/ImplementTypeOptionsProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.ImplementType { [ExportOptionProvider, Shared] internal class ImplementTypeOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ImplementTypeOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( ImplementTypeOptions.InsertionBehavior); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.ImplementType { [ExportOptionProvider, Shared] internal class ImplementTypeOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ImplementTypeOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( ImplementTypeOptions.InsertionBehavior); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_SwitchExpression.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal partial class LocalRewriter { public override BoundNode VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node) { // The switch expression is lowered to an expression that involves the use of side-effects // such as jumps and labels, therefore it is represented by a BoundSpillSequence and // the resulting nodes will need to be "spilled" to move such statements to the top // level (i.e. into the enclosing statement list). this._needsSpilling = true; return SwitchExpressionLocalRewriter.Rewrite(this, node); } private sealed class SwitchExpressionLocalRewriter : BaseSwitchLocalRewriter { private SwitchExpressionLocalRewriter(BoundConvertedSwitchExpression node, LocalRewriter localRewriter) : base(node.Syntax, localRewriter, node.SwitchArms.SelectAsArray(arm => arm.Syntax), generateInstrumentation: !node.WasCompilerGenerated && localRewriter.Instrument) { } public static BoundExpression Rewrite(LocalRewriter localRewriter, BoundConvertedSwitchExpression node) { var rewriter = new SwitchExpressionLocalRewriter(node, localRewriter); BoundExpression result = rewriter.LowerSwitchExpression(node); rewriter.Free(); return result; } private BoundExpression LowerSwitchExpression(BoundConvertedSwitchExpression node) { // When compiling for Debug (not Release), we produce the most detailed sequence points. var produceDetailedSequencePoints = GenerateInstrumentation && _localRewriter._compilation.Options.OptimizationLevel != OptimizationLevel.Release; _factory.Syntax = node.Syntax; var result = ArrayBuilder<BoundStatement>.GetInstance(); var outerVariables = ArrayBuilder<LocalSymbol>.GetInstance(); var loweredSwitchGoverningExpression = _localRewriter.VisitExpression(node.Expression); BoundDecisionDag decisionDag = ShareTempsIfPossibleAndEvaluateInput( node.DecisionDag, loweredSwitchGoverningExpression, result, out BoundExpression savedInputExpression); Debug.Assert(savedInputExpression != null); object restorePointForEnclosingStatement = new object(); object restorePointForSwitchBody = new object(); // lower the decision dag. (ImmutableArray<BoundStatement> loweredDag, ImmutableDictionary<SyntaxNode, ImmutableArray<BoundStatement>> switchSections) = LowerDecisionDag(decisionDag); if (produceDetailedSequencePoints) { var syntax = (SwitchExpressionSyntax)node.Syntax; result.Add(new BoundSavePreviousSequencePoint(syntax, restorePointForEnclosingStatement)); // While evaluating the state machine, we highlight the `switch {...}` part. var spanStart = syntax.SwitchKeyword.Span.Start; var spanEnd = syntax.Span.End; var spanForSwitchBody = new TextSpan(spanStart, spanEnd - spanStart); result.Add(new BoundStepThroughSequencePoint(node.Syntax, span: spanForSwitchBody)); result.Add(new BoundSavePreviousSequencePoint(syntax, restorePointForSwitchBody)); } // add the rest of the lowered dag that references that input result.Add(_factory.Block(loweredDag)); // A branch to the default label when no switch case matches is included in the // decision tree, so the code in result is unreachable at this point. // Lower each switch expression arm LocalSymbol resultTemp = _factory.SynthesizedLocal(node.Type, node.Syntax, kind: SynthesizedLocalKind.LoweringTemp); LabelSymbol afterSwitchExpression = _factory.GenerateLabel("afterSwitchExpression"); foreach (BoundSwitchExpressionArm arm in node.SwitchArms) { _factory.Syntax = arm.Syntax; var sectionBuilder = ArrayBuilder<BoundStatement>.GetInstance(); sectionBuilder.AddRange(switchSections[arm.Syntax]); sectionBuilder.Add(_factory.Label(arm.Label)); var loweredValue = _localRewriter.VisitExpression(arm.Value); if (GenerateInstrumentation) loweredValue = this._localRewriter._instrumenter.InstrumentSwitchExpressionArmExpression(arm.Value, loweredValue, _factory); sectionBuilder.Add(_factory.Assignment(_factory.Local(resultTemp), loweredValue)); sectionBuilder.Add(_factory.Goto(afterSwitchExpression)); var statements = sectionBuilder.ToImmutableAndFree(); if (arm.Locals.IsEmpty) { result.Add(_factory.StatementList(statements)); } else { // Lifetime of these locals is expanded to the entire switch body, as it is possible to // share them as temps in the decision dag. outerVariables.AddRange(arm.Locals); // Note the language scope of the locals, even though they are included for the purposes of // lifetime analysis in the enclosing scope. result.Add(new BoundScope(arm.Syntax, arm.Locals, statements)); } } _factory.Syntax = node.Syntax; if (node.DefaultLabel != null) { result.Add(_factory.Label(node.DefaultLabel)); if (produceDetailedSequencePoints) result.Add(new BoundRestorePreviousSequencePoint(node.Syntax, restorePointForSwitchBody)); var objectType = _factory.SpecialType(SpecialType.System_Object); var thrownExpression = (implicitConversionExists(savedInputExpression, objectType) && _factory.WellKnownMember(WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctorObject, isOptional: true) is MethodSymbol exception1) ? _factory.New(exception1, _factory.Convert(objectType, savedInputExpression)) : (_factory.WellKnownMember(WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctor, isOptional: true) is MethodSymbol exception0) ? _factory.New(exception0) : _factory.New(_factory.WellKnownMethod(WellKnownMember.System_InvalidOperationException__ctor)); result.Add(_factory.Throw(thrownExpression)); } if (GenerateInstrumentation) result.Add(_factory.HiddenSequencePoint()); result.Add(_factory.Label(afterSwitchExpression)); if (produceDetailedSequencePoints) result.Add(new BoundRestorePreviousSequencePoint(node.Syntax, restorePointForEnclosingStatement)); outerVariables.Add(resultTemp); outerVariables.AddRange(_tempAllocator.AllTemps()); return _factory.SpillSequence(outerVariables.ToImmutableAndFree(), result.ToImmutableAndFree(), _factory.Local(resultTemp)); bool implicitConversionExists(BoundExpression expression, TypeSymbol type) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; Conversion c = _localRewriter._compilation.Conversions.ClassifyConversionFromExpression(expression, type, ref discardedUseSiteInfo); return c.IsImplicit; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal partial class LocalRewriter { public override BoundNode VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node) { // The switch expression is lowered to an expression that involves the use of side-effects // such as jumps and labels, therefore it is represented by a BoundSpillSequence and // the resulting nodes will need to be "spilled" to move such statements to the top // level (i.e. into the enclosing statement list). this._needsSpilling = true; return SwitchExpressionLocalRewriter.Rewrite(this, node); } private sealed class SwitchExpressionLocalRewriter : BaseSwitchLocalRewriter { private SwitchExpressionLocalRewriter(BoundConvertedSwitchExpression node, LocalRewriter localRewriter) : base(node.Syntax, localRewriter, node.SwitchArms.SelectAsArray(arm => arm.Syntax), generateInstrumentation: !node.WasCompilerGenerated && localRewriter.Instrument) { } public static BoundExpression Rewrite(LocalRewriter localRewriter, BoundConvertedSwitchExpression node) { var rewriter = new SwitchExpressionLocalRewriter(node, localRewriter); BoundExpression result = rewriter.LowerSwitchExpression(node); rewriter.Free(); return result; } private BoundExpression LowerSwitchExpression(BoundConvertedSwitchExpression node) { // When compiling for Debug (not Release), we produce the most detailed sequence points. var produceDetailedSequencePoints = GenerateInstrumentation && _localRewriter._compilation.Options.OptimizationLevel != OptimizationLevel.Release; _factory.Syntax = node.Syntax; var result = ArrayBuilder<BoundStatement>.GetInstance(); var outerVariables = ArrayBuilder<LocalSymbol>.GetInstance(); var loweredSwitchGoverningExpression = _localRewriter.VisitExpression(node.Expression); BoundDecisionDag decisionDag = ShareTempsIfPossibleAndEvaluateInput( node.DecisionDag, loweredSwitchGoverningExpression, result, out BoundExpression savedInputExpression); Debug.Assert(savedInputExpression != null); object restorePointForEnclosingStatement = new object(); object restorePointForSwitchBody = new object(); // lower the decision dag. (ImmutableArray<BoundStatement> loweredDag, ImmutableDictionary<SyntaxNode, ImmutableArray<BoundStatement>> switchSections) = LowerDecisionDag(decisionDag); if (produceDetailedSequencePoints) { var syntax = (SwitchExpressionSyntax)node.Syntax; result.Add(new BoundSavePreviousSequencePoint(syntax, restorePointForEnclosingStatement)); // While evaluating the state machine, we highlight the `switch {...}` part. var spanStart = syntax.SwitchKeyword.Span.Start; var spanEnd = syntax.Span.End; var spanForSwitchBody = new TextSpan(spanStart, spanEnd - spanStart); result.Add(new BoundStepThroughSequencePoint(node.Syntax, span: spanForSwitchBody)); result.Add(new BoundSavePreviousSequencePoint(syntax, restorePointForSwitchBody)); } // add the rest of the lowered dag that references that input result.Add(_factory.Block(loweredDag)); // A branch to the default label when no switch case matches is included in the // decision tree, so the code in result is unreachable at this point. // Lower each switch expression arm LocalSymbol resultTemp = _factory.SynthesizedLocal(node.Type, node.Syntax, kind: SynthesizedLocalKind.LoweringTemp); LabelSymbol afterSwitchExpression = _factory.GenerateLabel("afterSwitchExpression"); foreach (BoundSwitchExpressionArm arm in node.SwitchArms) { _factory.Syntax = arm.Syntax; var sectionBuilder = ArrayBuilder<BoundStatement>.GetInstance(); sectionBuilder.AddRange(switchSections[arm.Syntax]); sectionBuilder.Add(_factory.Label(arm.Label)); var loweredValue = _localRewriter.VisitExpression(arm.Value); if (GenerateInstrumentation) loweredValue = this._localRewriter._instrumenter.InstrumentSwitchExpressionArmExpression(arm.Value, loweredValue, _factory); sectionBuilder.Add(_factory.Assignment(_factory.Local(resultTemp), loweredValue)); sectionBuilder.Add(_factory.Goto(afterSwitchExpression)); var statements = sectionBuilder.ToImmutableAndFree(); if (arm.Locals.IsEmpty) { result.Add(_factory.StatementList(statements)); } else { // Lifetime of these locals is expanded to the entire switch body, as it is possible to // share them as temps in the decision dag. outerVariables.AddRange(arm.Locals); // Note the language scope of the locals, even though they are included for the purposes of // lifetime analysis in the enclosing scope. result.Add(new BoundScope(arm.Syntax, arm.Locals, statements)); } } _factory.Syntax = node.Syntax; if (node.DefaultLabel != null) { result.Add(_factory.Label(node.DefaultLabel)); if (produceDetailedSequencePoints) result.Add(new BoundRestorePreviousSequencePoint(node.Syntax, restorePointForSwitchBody)); var objectType = _factory.SpecialType(SpecialType.System_Object); var thrownExpression = (implicitConversionExists(savedInputExpression, objectType) && _factory.WellKnownMember(WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctorObject, isOptional: true) is MethodSymbol exception1) ? _factory.New(exception1, _factory.Convert(objectType, savedInputExpression)) : (_factory.WellKnownMember(WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctor, isOptional: true) is MethodSymbol exception0) ? _factory.New(exception0) : _factory.New(_factory.WellKnownMethod(WellKnownMember.System_InvalidOperationException__ctor)); result.Add(_factory.Throw(thrownExpression)); } if (GenerateInstrumentation) result.Add(_factory.HiddenSequencePoint()); result.Add(_factory.Label(afterSwitchExpression)); if (produceDetailedSequencePoints) result.Add(new BoundRestorePreviousSequencePoint(node.Syntax, restorePointForEnclosingStatement)); outerVariables.Add(resultTemp); outerVariables.AddRange(_tempAllocator.AllTemps()); return _factory.SpillSequence(outerVariables.ToImmutableAndFree(), result.ToImmutableAndFree(), _factory.Local(resultTemp)); bool implicitConversionExists(BoundExpression expression, TypeSymbol type) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; Conversion c = _localRewriter._compilation.Conversions.ClassifyConversionFromExpression(expression, type, ref discardedUseSiteInfo); return c.IsImplicit; } } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/Core/Portable/Shared/Naming/IdentifierNameParts.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.NamingStyles; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Shared.Naming { internal readonly struct IdentifierNameParts { public readonly string BaseName; public readonly ImmutableArray<string> BaseNameParts; public IdentifierNameParts(string baseName, ImmutableArray<string> baseNameParts) { BaseName = baseName; BaseNameParts = baseNameParts; } public static IdentifierNameParts CreateIdentifierNameParts(ISymbol symbol, ImmutableArray<NamingRule> rules) { var baseName = RemovePrefixesAndSuffixes(symbol, rules, symbol.Name); using var parts = TemporaryArray<TextSpan>.Empty; StringBreaker.AddWordParts(baseName, ref parts.AsRef()); var words = CreateWords(parts, baseName); return new IdentifierNameParts(baseName, words); } private static string RemovePrefixesAndSuffixes(ISymbol symbol, ImmutableArray<NamingRule> rules, string baseName) { var newBaseName = baseName; foreach (var rule in rules) { if (rule.SymbolSpecification.AppliesTo(symbol)) { // remove specified prefix var prefix = rule.NamingStyle.Prefix; newBaseName = newBaseName.StartsWith(prefix) ? newBaseName[prefix.Length..] : newBaseName; // remove specified suffix var suffix = rule.NamingStyle.Suffix; newBaseName = newBaseName.EndsWith(suffix) ? newBaseName.Substring(0, newBaseName.Length - suffix.Length) : newBaseName; break; } } // remove any common prefixes newBaseName = NamingStyle.StripCommonPrefixes(newBaseName, out var _); // If no changes were made to the basename passed in, we're done if (newBaseName == baseName) { return baseName; } // otherwise, see if any other prefixes exist return RemovePrefixesAndSuffixes(symbol, rules, newBaseName); } private static ImmutableArray<string> CreateWords(in TemporaryArray<TextSpan> parts, string name) { using var words = TemporaryArray<string>.Empty; foreach (var part in parts) words.Add(name.Substring(part.Start, part.Length)); return words.ToImmutableAndClear(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.NamingStyles; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Shared.Naming { internal readonly struct IdentifierNameParts { public readonly string BaseName; public readonly ImmutableArray<string> BaseNameParts; public IdentifierNameParts(string baseName, ImmutableArray<string> baseNameParts) { BaseName = baseName; BaseNameParts = baseNameParts; } public static IdentifierNameParts CreateIdentifierNameParts(ISymbol symbol, ImmutableArray<NamingRule> rules) { var baseName = RemovePrefixesAndSuffixes(symbol, rules, symbol.Name); using var parts = TemporaryArray<TextSpan>.Empty; StringBreaker.AddWordParts(baseName, ref parts.AsRef()); var words = CreateWords(parts, baseName); return new IdentifierNameParts(baseName, words); } private static string RemovePrefixesAndSuffixes(ISymbol symbol, ImmutableArray<NamingRule> rules, string baseName) { var newBaseName = baseName; foreach (var rule in rules) { if (rule.SymbolSpecification.AppliesTo(symbol)) { // remove specified prefix var prefix = rule.NamingStyle.Prefix; newBaseName = newBaseName.StartsWith(prefix) ? newBaseName[prefix.Length..] : newBaseName; // remove specified suffix var suffix = rule.NamingStyle.Suffix; newBaseName = newBaseName.EndsWith(suffix) ? newBaseName.Substring(0, newBaseName.Length - suffix.Length) : newBaseName; break; } } // remove any common prefixes newBaseName = NamingStyle.StripCommonPrefixes(newBaseName, out var _); // If no changes were made to the basename passed in, we're done if (newBaseName == baseName) { return baseName; } // otherwise, see if any other prefixes exist return RemovePrefixesAndSuffixes(symbol, rules, newBaseName); } private static ImmutableArray<string> CreateWords(in TemporaryArray<TextSpan> parts, string name) { using var words = TemporaryArray<string>.Empty; foreach (var part in parts) words.Add(name.Substring(part.Start, part.Length)); return words.ToImmutableAndClear(); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/ExpressionEvaluator/CSharp/Test/ResultProvider/DebuggerVisualizerAttributeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class DebuggerVisualizerAttributeTests : CSharpResultProviderTestBase { /// <summary> /// Tests that the DebuggerVisualizer attribute works with multiple attributes defined. /// </summary> [Fact] public void Visualizer() { var source = @"using System.Diagnostics; [DebuggerVisualizer(typeof(P))] [DebuggerVisualizer(typeof(Q), Description = ""Q Visualizer"")] class C { object F = 1; object P { get { return 3; } } } class P { public P() { } } class Q { public Q() { } }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: new DkmClrType((TypeImpl)type), evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("new C()", value); var typeP = assembly.GetType("P"); var typeQ = assembly.GetType("Q"); string defaultDebuggeeSideVisualizerTypeName = "Microsoft.VisualStudio.DebuggerVisualizers.VisualizerObjectSource"; var vsVersion = Environment.GetEnvironmentVariable("VisualStudioVersion") ?? "14.0"; string defaultDebuggeeSideVisualizerAssemblyName = $"Microsoft.VisualStudio.DebuggerVisualizers, Version={vsVersion}.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; DkmCustomUIVisualizerInfo[] customUIVisualizerInfo = { new DkmCustomUIVisualizerInfo { Id = 0, Description = "P", MenuName = "P", Metric = "ClrCustomVisualizerVSHost", UISideVisualizerTypeName = typeP.FullName, UISideVisualizerAssemblyName = typeP.Assembly.FullName, UISideVisualizerAssemblyLocation = DkmClrCustomVisualizerAssemblyLocation.Unknown, DebuggeeSideVisualizerTypeName = defaultDebuggeeSideVisualizerTypeName, DebuggeeSideVisualizerAssemblyName = defaultDebuggeeSideVisualizerAssemblyName}, new DkmCustomUIVisualizerInfo { Id = 1, Description = "Q Visualizer", MenuName = "Q Visualizer", Metric = "ClrCustomVisualizerVSHost", UISideVisualizerTypeName = typeQ.FullName, UISideVisualizerAssemblyName = typeQ.Assembly.FullName, UISideVisualizerAssemblyLocation = DkmClrCustomVisualizerAssemblyLocation.Unknown, DebuggeeSideVisualizerTypeName = defaultDebuggeeSideVisualizerTypeName, DebuggeeSideVisualizerAssemblyName = defaultDebuggeeSideVisualizerAssemblyName} }; Verify(evalResult, EvalResult("new C()", "{C}", "C", "new C()", flags: DkmEvaluationResultFlags.Expandable, customUIVisualizerInfo: customUIVisualizerInfo)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class DebuggerVisualizerAttributeTests : CSharpResultProviderTestBase { /// <summary> /// Tests that the DebuggerVisualizer attribute works with multiple attributes defined. /// </summary> [Fact] public void Visualizer() { var source = @"using System.Diagnostics; [DebuggerVisualizer(typeof(P))] [DebuggerVisualizer(typeof(Q), Description = ""Q Visualizer"")] class C { object F = 1; object P { get { return 3; } } } class P { public P() { } } class Q { public Q() { } }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: new DkmClrType((TypeImpl)type), evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("new C()", value); var typeP = assembly.GetType("P"); var typeQ = assembly.GetType("Q"); string defaultDebuggeeSideVisualizerTypeName = "Microsoft.VisualStudio.DebuggerVisualizers.VisualizerObjectSource"; var vsVersion = Environment.GetEnvironmentVariable("VisualStudioVersion") ?? "14.0"; string defaultDebuggeeSideVisualizerAssemblyName = $"Microsoft.VisualStudio.DebuggerVisualizers, Version={vsVersion}.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; DkmCustomUIVisualizerInfo[] customUIVisualizerInfo = { new DkmCustomUIVisualizerInfo { Id = 0, Description = "P", MenuName = "P", Metric = "ClrCustomVisualizerVSHost", UISideVisualizerTypeName = typeP.FullName, UISideVisualizerAssemblyName = typeP.Assembly.FullName, UISideVisualizerAssemblyLocation = DkmClrCustomVisualizerAssemblyLocation.Unknown, DebuggeeSideVisualizerTypeName = defaultDebuggeeSideVisualizerTypeName, DebuggeeSideVisualizerAssemblyName = defaultDebuggeeSideVisualizerAssemblyName}, new DkmCustomUIVisualizerInfo { Id = 1, Description = "Q Visualizer", MenuName = "Q Visualizer", Metric = "ClrCustomVisualizerVSHost", UISideVisualizerTypeName = typeQ.FullName, UISideVisualizerAssemblyName = typeQ.Assembly.FullName, UISideVisualizerAssemblyLocation = DkmClrCustomVisualizerAssemblyLocation.Unknown, DebuggeeSideVisualizerTypeName = defaultDebuggeeSideVisualizerTypeName, DebuggeeSideVisualizerAssemblyName = defaultDebuggeeSideVisualizerAssemblyName} }; Verify(evalResult, EvalResult("new C()", "{C}", "C", "new C()", flags: DkmEvaluationResultFlags.Expandable, customUIVisualizerInfo: customUIVisualizerInfo)); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/Core/Portable/QuickInfo/QuickInfoSectionKinds.cs
// Licensed to the .NET Foundation under one or more 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.QuickInfo { /// <summary> /// The set of well known kinds used for the <see cref="QuickInfoSection.Kind"/> property. /// These tags influence the presentation of quick info section. /// </summary> public static class QuickInfoSectionKinds { public const string Description = nameof(Description); public const string DocumentationComments = nameof(DocumentationComments); public const string RemarksDocumentationComments = nameof(RemarksDocumentationComments); public const string ReturnsDocumentationComments = nameof(ReturnsDocumentationComments); public const string ValueDocumentationComments = nameof(ValueDocumentationComments); public const string TypeParameters = nameof(TypeParameters); public const string AnonymousTypes = nameof(AnonymousTypes); public const string Usage = nameof(Usage); public const string Exception = nameof(Exception); public const string Text = nameof(Text); public const string Captures = nameof(Captures); internal const string NullabilityAnalysis = nameof(NullabilityAnalysis); } }
// Licensed to the .NET Foundation under one or more 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.QuickInfo { /// <summary> /// The set of well known kinds used for the <see cref="QuickInfoSection.Kind"/> property. /// These tags influence the presentation of quick info section. /// </summary> public static class QuickInfoSectionKinds { public const string Description = nameof(Description); public const string DocumentationComments = nameof(DocumentationComments); public const string RemarksDocumentationComments = nameof(RemarksDocumentationComments); public const string ReturnsDocumentationComments = nameof(ReturnsDocumentationComments); public const string ValueDocumentationComments = nameof(ValueDocumentationComments); public const string TypeParameters = nameof(TypeParameters); public const string AnonymousTypes = nameof(AnonymousTypes); public const string Usage = nameof(Usage); public const string Exception = nameof(Exception); public const string Text = nameof(Text); public const string Captures = nameof(Captures); internal const string NullabilityAnalysis = nameof(NullabilityAnalysis); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxTriviaExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class SyntaxTriviaExtensions { public static bool MatchesKind(this SyntaxTrivia trivia, SyntaxKind kind) => trivia.Kind() == kind; public static bool MatchesKind(this SyntaxTrivia trivia, SyntaxKind kind1, SyntaxKind kind2) { var triviaKind = trivia.Kind(); return triviaKind == kind1 || triviaKind == kind2; } public static bool MatchesKind(this SyntaxTrivia trivia, params SyntaxKind[] kinds) => kinds.Contains(trivia.Kind()); public static bool IsSingleOrMultiLineComment(this SyntaxTrivia trivia) => trivia.IsKind(SyntaxKind.MultiLineCommentTrivia) || trivia.IsKind(SyntaxKind.SingleLineCommentTrivia); public static bool IsRegularComment(this SyntaxTrivia trivia) => trivia.IsSingleOrMultiLineComment() || trivia.IsShebangDirective(); public static bool IsWhitespaceOrSingleOrMultiLineComment(this SyntaxTrivia trivia) => trivia.IsWhitespace() || trivia.IsSingleOrMultiLineComment(); public static bool IsRegularOrDocComment(this SyntaxTrivia trivia) => trivia.IsRegularComment() || trivia.IsDocComment(); public static bool IsSingleLineComment(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.SingleLineCommentTrivia; public static bool IsMultiLineComment(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.MultiLineCommentTrivia; public static bool IsShebangDirective(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.ShebangDirectiveTrivia; public static bool IsCompleteMultiLineComment(this SyntaxTrivia trivia) { if (trivia.Kind() != SyntaxKind.MultiLineCommentTrivia) { return false; } var text = trivia.ToFullString(); return text.Length >= 4 && text[text.Length - 1] == '/' && text[text.Length - 2] == '*'; } public static bool IsDocComment(this SyntaxTrivia trivia) => trivia.IsSingleLineDocComment() || trivia.IsMultiLineDocComment(); public static bool IsSingleLineDocComment(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia; public static bool IsMultiLineDocComment(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia; public static string GetCommentText(this SyntaxTrivia trivia) { var commentText = trivia.ToString(); if (trivia.Kind() == SyntaxKind.SingleLineCommentTrivia) { if (commentText.StartsWith("//", StringComparison.Ordinal)) { commentText = commentText.Substring(2); } return commentText.TrimStart(null); } else if (trivia.Kind() == SyntaxKind.MultiLineCommentTrivia) { var textBuilder = new StringBuilder(); if (commentText.EndsWith("*/", StringComparison.Ordinal)) { commentText = commentText.Substring(0, commentText.Length - 2); } if (commentText.StartsWith("/*", StringComparison.Ordinal)) { commentText = commentText.Substring(2); } commentText = commentText.Trim(); var newLine = Environment.NewLine; var lines = commentText.Split(new[] { newLine }, StringSplitOptions.None); foreach (var line in lines) { var trimmedLine = line.Trim(); // Note: we trim leading '*' characters in multi-line comments. // If the '*' was intentional, sorry, it's gone. if (trimmedLine.StartsWith("*", StringComparison.Ordinal)) { trimmedLine = trimmedLine.TrimStart('*'); trimmedLine = trimmedLine.TrimStart(null); } textBuilder.AppendLine(trimmedLine); } // remove last line break textBuilder.Remove(textBuilder.Length - newLine.Length, newLine.Length); return textBuilder.ToString(); } else { throw new InvalidOperationException(); } } public static string AsString(this IEnumerable<SyntaxTrivia> trivia) { Contract.ThrowIfNull(trivia); if (trivia.Any()) { var sb = new StringBuilder(); trivia.Select(t => t.ToFullString()).Do(s => sb.Append(s)); return sb.ToString(); } else { return string.Empty; } } public static int GetFullWidth(this IEnumerable<SyntaxTrivia> trivia) { Contract.ThrowIfNull(trivia); return trivia.Sum(t => t.FullWidth()); } public static SyntaxTriviaList AsTrivia(this string s) => SyntaxFactory.ParseLeadingTrivia(s ?? string.Empty); public static bool IsWhitespaceOrEndOfLine(this SyntaxTrivia trivia) => IsWhitespace(trivia) || IsEndOfLine(trivia); public static bool IsEndOfLine(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.EndOfLineTrivia; public static bool IsWhitespace(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.WhitespaceTrivia; public static SyntaxTrivia GetPreviousTrivia( this SyntaxTrivia trivia, SyntaxTree syntaxTree, CancellationToken cancellationToken, bool findInsideTrivia = false) { var span = trivia.FullSpan; if (span.Start == 0) { return default; } return syntaxTree.GetRoot(cancellationToken).FindTrivia(span.Start - 1, findInsideTrivia); } public static IEnumerable<SyntaxTrivia> FilterComments(this IEnumerable<SyntaxTrivia> trivia, bool addElasticMarker) { var previousIsSingleLineComment = false; foreach (var t in trivia) { if (previousIsSingleLineComment && t.IsEndOfLine()) { yield return t; } if (t.IsSingleOrMultiLineComment()) { yield return t; } previousIsSingleLineComment = t.IsSingleLineComment(); } if (addElasticMarker) { yield return SyntaxFactory.ElasticMarker; } } #if false public static int Width(this SyntaxTrivia trivia) { return trivia.Span.Length; } public static int FullWidth(this SyntaxTrivia trivia) { return trivia.FullSpan.Length; } #endif public static bool IsPragmaDirective(this SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes) { if (trivia.IsKind(SyntaxKind.PragmaWarningDirectiveTrivia)) { var pragmaWarning = (PragmaWarningDirectiveTriviaSyntax)trivia.GetStructure(); isDisable = pragmaWarning.DisableOrRestoreKeyword.IsKind(SyntaxKind.DisableKeyword); isActive = pragmaWarning.IsActive; errorCodes = pragmaWarning.ErrorCodes; return true; } isDisable = false; isActive = false; errorCodes = default; return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class SyntaxTriviaExtensions { public static bool MatchesKind(this SyntaxTrivia trivia, SyntaxKind kind) => trivia.Kind() == kind; public static bool MatchesKind(this SyntaxTrivia trivia, SyntaxKind kind1, SyntaxKind kind2) { var triviaKind = trivia.Kind(); return triviaKind == kind1 || triviaKind == kind2; } public static bool MatchesKind(this SyntaxTrivia trivia, params SyntaxKind[] kinds) => kinds.Contains(trivia.Kind()); public static bool IsSingleOrMultiLineComment(this SyntaxTrivia trivia) => trivia.IsKind(SyntaxKind.MultiLineCommentTrivia) || trivia.IsKind(SyntaxKind.SingleLineCommentTrivia); public static bool IsRegularComment(this SyntaxTrivia trivia) => trivia.IsSingleOrMultiLineComment() || trivia.IsShebangDirective(); public static bool IsWhitespaceOrSingleOrMultiLineComment(this SyntaxTrivia trivia) => trivia.IsWhitespace() || trivia.IsSingleOrMultiLineComment(); public static bool IsRegularOrDocComment(this SyntaxTrivia trivia) => trivia.IsRegularComment() || trivia.IsDocComment(); public static bool IsSingleLineComment(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.SingleLineCommentTrivia; public static bool IsMultiLineComment(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.MultiLineCommentTrivia; public static bool IsShebangDirective(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.ShebangDirectiveTrivia; public static bool IsCompleteMultiLineComment(this SyntaxTrivia trivia) { if (trivia.Kind() != SyntaxKind.MultiLineCommentTrivia) { return false; } var text = trivia.ToFullString(); return text.Length >= 4 && text[text.Length - 1] == '/' && text[text.Length - 2] == '*'; } public static bool IsDocComment(this SyntaxTrivia trivia) => trivia.IsSingleLineDocComment() || trivia.IsMultiLineDocComment(); public static bool IsSingleLineDocComment(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia; public static bool IsMultiLineDocComment(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia; public static string GetCommentText(this SyntaxTrivia trivia) { var commentText = trivia.ToString(); if (trivia.Kind() == SyntaxKind.SingleLineCommentTrivia) { if (commentText.StartsWith("//", StringComparison.Ordinal)) { commentText = commentText.Substring(2); } return commentText.TrimStart(null); } else if (trivia.Kind() == SyntaxKind.MultiLineCommentTrivia) { var textBuilder = new StringBuilder(); if (commentText.EndsWith("*/", StringComparison.Ordinal)) { commentText = commentText.Substring(0, commentText.Length - 2); } if (commentText.StartsWith("/*", StringComparison.Ordinal)) { commentText = commentText.Substring(2); } commentText = commentText.Trim(); var newLine = Environment.NewLine; var lines = commentText.Split(new[] { newLine }, StringSplitOptions.None); foreach (var line in lines) { var trimmedLine = line.Trim(); // Note: we trim leading '*' characters in multi-line comments. // If the '*' was intentional, sorry, it's gone. if (trimmedLine.StartsWith("*", StringComparison.Ordinal)) { trimmedLine = trimmedLine.TrimStart('*'); trimmedLine = trimmedLine.TrimStart(null); } textBuilder.AppendLine(trimmedLine); } // remove last line break textBuilder.Remove(textBuilder.Length - newLine.Length, newLine.Length); return textBuilder.ToString(); } else { throw new InvalidOperationException(); } } public static string AsString(this IEnumerable<SyntaxTrivia> trivia) { Contract.ThrowIfNull(trivia); if (trivia.Any()) { var sb = new StringBuilder(); trivia.Select(t => t.ToFullString()).Do(s => sb.Append(s)); return sb.ToString(); } else { return string.Empty; } } public static int GetFullWidth(this IEnumerable<SyntaxTrivia> trivia) { Contract.ThrowIfNull(trivia); return trivia.Sum(t => t.FullWidth()); } public static SyntaxTriviaList AsTrivia(this string s) => SyntaxFactory.ParseLeadingTrivia(s ?? string.Empty); public static bool IsWhitespaceOrEndOfLine(this SyntaxTrivia trivia) => IsWhitespace(trivia) || IsEndOfLine(trivia); public static bool IsEndOfLine(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.EndOfLineTrivia; public static bool IsWhitespace(this SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.WhitespaceTrivia; public static SyntaxTrivia GetPreviousTrivia( this SyntaxTrivia trivia, SyntaxTree syntaxTree, CancellationToken cancellationToken, bool findInsideTrivia = false) { var span = trivia.FullSpan; if (span.Start == 0) { return default; } return syntaxTree.GetRoot(cancellationToken).FindTrivia(span.Start - 1, findInsideTrivia); } public static IEnumerable<SyntaxTrivia> FilterComments(this IEnumerable<SyntaxTrivia> trivia, bool addElasticMarker) { var previousIsSingleLineComment = false; foreach (var t in trivia) { if (previousIsSingleLineComment && t.IsEndOfLine()) { yield return t; } if (t.IsSingleOrMultiLineComment()) { yield return t; } previousIsSingleLineComment = t.IsSingleLineComment(); } if (addElasticMarker) { yield return SyntaxFactory.ElasticMarker; } } #if false public static int Width(this SyntaxTrivia trivia) { return trivia.Span.Length; } public static int FullWidth(this SyntaxTrivia trivia) { return trivia.FullSpan.Length; } #endif public static bool IsPragmaDirective(this SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes) { if (trivia.IsKind(SyntaxKind.PragmaWarningDirectiveTrivia)) { var pragmaWarning = (PragmaWarningDirectiveTriviaSyntax)trivia.GetStructure(); isDisable = pragmaWarning.DisableOrRestoreKeyword.IsKind(SyntaxKind.DisableKeyword); isActive = pragmaWarning.IsActive; errorCodes = pragmaWarning.ErrorCodes; return true; } isDisable = false; isActive = false; errorCodes = default; return false; } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./docs/compilers/CSharp/System.TypedReference.md
System.TypedReference ===================== [This is a placeholder. We need some more documentation here] This is an old email conversation that gives some context about the interop support in the C# compiler. Ironically, the conversation suggests that we'll never document it! ------------------- Subject: RE: error CS0610: Field or property cannot be of type 'System.TypedReference' From: Eric Lippert To: Aleksey Tsingauz; Neal Gafter; Roslyn Compiler Dev Team Sent: Monday, January 24, 2011 9:42 AM Basically what’s going on here is we have some undocumented features which enable you to pass around a reference to a **variable** without knowing the type of the variable at compile time. The reason why we have this feature is to enable C-style “varargs” in the CLR; you might have a method that takes an unspecified number of arguments and some of those arguments might be references to variables. Because a `TypedReference` can contain the address of a stack-allocated variable, you’re not allowed to store them in fields, same as you’re not allowed to make a field of ref type. That way we know we’re never storing a reference to a “dead” stack variable. We have a bunch of goo in the native compiler to make sure that typed references (and a few other similarly magical types) are not used incorrectly; we’ll have to do the same thing in Roslyn at some point. None of this stuff is well documented. We have four undocumented language keywords that allow you to manipulate typed references; we have no intention as far as I know of ever documenting them. They are only there for rare situations where C# code needs to interoperate with a C-style method. Some various articles on these features that might give you more background if you’re interested: http://www.eggheadcafe.com/articles/20030114.asp http://stackoverflow.com/questions/4764573/why-is-typedreference-behind-the-scenes-its-so-fast-and-safe-almost-magical http://stackoverflow.com/questions/1711393/practical-uses-of-typedreference http://stackoverflow.com/questions/2064509/c-type-parameters-specification http://stackoverflow.com/questions/4046397/generic-variadic-parameters http://bartdesmet.net/blogs/bart/archive/2006/09/28/4473.aspx Cheers, Eric --------------------- From: Aleksey Tsingauz Sent: Sunday, January 23, 2011 11:00 PM To: Neal Gafter; Roslyn Compiler Dev Team Subject: RE: error CS0610: Field or property cannot be of type 'System.TypedReference'   I believe it is about ECMA-335 §8.2.1.1 Managed pointers and related types:   A **managed pointer** (§12.1.1.2), or **byref** (§8.6.1.3, §12.4.1.5.2), can point to a local variable, parameter, field of a compound type, or element of an array. However, when a call crosses a remoting boundary (see §12.5) a conforming implementation can use a copy-in/copy-out mechanism instead of a managed pointer. Thus programs shall not rely on the aliasing behavior of true pointers. Managed pointer types are only allowed for local variable (§8.6.1.3) and parameter signatures (§8.6.1.4); they cannot be used for field signatures (§8.6.1.2), as the element type of an array (§8.9.1), and boxing a value of managed pointer type is disallowed (§8.2.4). Using a managed pointer type for the return type of methods (§8.6.1.5) is not verifiable (§8.8). [Rationale: For performance reasons items on the GC heap may not contain references to the interior of other GC objects, this motivates the restrictions on fields and boxing. Further returning a managed pointer which references a local or parameter variable may cause the reference to outlive the variable, hence it is not verifiable . end rationale] There are three value types in the Base Class Library (see Partition IV Library): `System.TypedReference`, `System.RuntimeArgumentHandle`, and `System.ArgIterator`; which are treated specially by the CLI. The value type `System.TypedReference`, or *typed reference* or *typedref* , (§8.2.2, §8.6.1.3, §12.4.1.5.3) contains both a managed pointer to a location and a runtime representation of the type that can be stored at that location. Typed references have the same restrictions as byrefs. Typed references are created by the CIL instruction `mkrefany` (see Partition III). The value types `System.RuntimeArgumentHandle` and `System.ArgIterator` (see Partition IV and CIL instruction `arglist` in Partition III), contain pointers into the VES stack. They can be used for local variable and parameter signatures. The use of these types for fields, method return types, the element type of an array, or in boxing is not verifiable (§8.8). These two types are referred to as *byref-like* types. ---------------- From: Neal Gafter Sent: Sunday, January 23, 2011 8:37 PM To: Roslyn Compiler Dev Team Cc: Neal Gafter Subject: error CS0610: Field or property cannot be of type 'System.TypedReference'   What is this error all about?  Where is it documented?
System.TypedReference ===================== [This is a placeholder. We need some more documentation here] This is an old email conversation that gives some context about the interop support in the C# compiler. Ironically, the conversation suggests that we'll never document it! ------------------- Subject: RE: error CS0610: Field or property cannot be of type 'System.TypedReference' From: Eric Lippert To: Aleksey Tsingauz; Neal Gafter; Roslyn Compiler Dev Team Sent: Monday, January 24, 2011 9:42 AM Basically what’s going on here is we have some undocumented features which enable you to pass around a reference to a **variable** without knowing the type of the variable at compile time. The reason why we have this feature is to enable C-style “varargs” in the CLR; you might have a method that takes an unspecified number of arguments and some of those arguments might be references to variables. Because a `TypedReference` can contain the address of a stack-allocated variable, you’re not allowed to store them in fields, same as you’re not allowed to make a field of ref type. That way we know we’re never storing a reference to a “dead” stack variable. We have a bunch of goo in the native compiler to make sure that typed references (and a few other similarly magical types) are not used incorrectly; we’ll have to do the same thing in Roslyn at some point. None of this stuff is well documented. We have four undocumented language keywords that allow you to manipulate typed references; we have no intention as far as I know of ever documenting them. They are only there for rare situations where C# code needs to interoperate with a C-style method. Some various articles on these features that might give you more background if you’re interested: http://www.eggheadcafe.com/articles/20030114.asp http://stackoverflow.com/questions/4764573/why-is-typedreference-behind-the-scenes-its-so-fast-and-safe-almost-magical http://stackoverflow.com/questions/1711393/practical-uses-of-typedreference http://stackoverflow.com/questions/2064509/c-type-parameters-specification http://stackoverflow.com/questions/4046397/generic-variadic-parameters http://bartdesmet.net/blogs/bart/archive/2006/09/28/4473.aspx Cheers, Eric --------------------- From: Aleksey Tsingauz Sent: Sunday, January 23, 2011 11:00 PM To: Neal Gafter; Roslyn Compiler Dev Team Subject: RE: error CS0610: Field or property cannot be of type 'System.TypedReference'   I believe it is about ECMA-335 §8.2.1.1 Managed pointers and related types:   A **managed pointer** (§12.1.1.2), or **byref** (§8.6.1.3, §12.4.1.5.2), can point to a local variable, parameter, field of a compound type, or element of an array. However, when a call crosses a remoting boundary (see §12.5) a conforming implementation can use a copy-in/copy-out mechanism instead of a managed pointer. Thus programs shall not rely on the aliasing behavior of true pointers. Managed pointer types are only allowed for local variable (§8.6.1.3) and parameter signatures (§8.6.1.4); they cannot be used for field signatures (§8.6.1.2), as the element type of an array (§8.9.1), and boxing a value of managed pointer type is disallowed (§8.2.4). Using a managed pointer type for the return type of methods (§8.6.1.5) is not verifiable (§8.8). [Rationale: For performance reasons items on the GC heap may not contain references to the interior of other GC objects, this motivates the restrictions on fields and boxing. Further returning a managed pointer which references a local or parameter variable may cause the reference to outlive the variable, hence it is not verifiable . end rationale] There are three value types in the Base Class Library (see Partition IV Library): `System.TypedReference`, `System.RuntimeArgumentHandle`, and `System.ArgIterator`; which are treated specially by the CLI. The value type `System.TypedReference`, or *typed reference* or *typedref* , (§8.2.2, §8.6.1.3, §12.4.1.5.3) contains both a managed pointer to a location and a runtime representation of the type that can be stored at that location. Typed references have the same restrictions as byrefs. Typed references are created by the CIL instruction `mkrefany` (see Partition III). The value types `System.RuntimeArgumentHandle` and `System.ArgIterator` (see Partition IV and CIL instruction `arglist` in Partition III), contain pointers into the VES stack. They can be used for local variable and parameter signatures. The use of these types for fields, method return types, the element type of an array, or in boxing is not verifiable (§8.8). These two types are referred to as *byref-like* types. ---------------- From: Neal Gafter Sent: Sunday, January 23, 2011 8:37 PM To: Roslyn Compiler Dev Team Cc: Neal Gafter Subject: error CS0610: Field or property cannot be of type 'System.TypedReference'   What is this error all about?  Where is it documented?
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Portable/Symbols/Metadata/PE/TupleTypeDecoder.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.PooledObjects; using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE { /// <summary> /// In C#, tuples can be represented using tuple syntax and be given /// names. However, the underlying representation for tuples unifies /// to a single underlying tuple type, System.ValueTuple. Since the /// names aren't part of the underlying tuple type they have to be /// recorded somewhere else. /// /// Roslyn records tuple names in an attribute: the /// TupleElementNamesAttribute. The attribute contains a single string /// array which records the names of the tuple elements in a pre-order /// depth-first traversal. If the type contains nested parameters, /// they are also recorded in a pre-order depth-first traversal. /// <see cref="DecodeTupleTypesIfApplicable(TypeSymbol, EntityHandle, PEModuleSymbol)"/> /// can be used to extract tuple names and types from metadata and create /// a <see cref="NamedTypeSymbol"/> with attached names. /// /// <example> /// For instance, a method returning a tuple /// /// <code> /// (int x, int y) M() { ... } /// </code> /// /// will be encoded using an attribute on the return type as follows /// /// <code> /// [return: TupleElementNamesAttribute(new[] { "x", "y" })] /// System.ValueTuple&lt;int, int&gt; M() { ... } /// </code> /// </example> /// /// <example> /// For nested type parameters, we expand the tuple names in a pre-order /// traversal: /// /// <code> /// class C : BaseType&lt;((int e1, int e2) e3, int e4)&lt; { ... } /// </code> /// /// becomes /// /// <code> /// [TupleElementNamesAttribute(new[] { "e3", "e4", "e1", "e2" }); /// class C : BaseType&lt;System.ValueTuple&lt; /// System.ValueTuple&lt;int,int&gt;, int&gt; /// { ... } /// </code> /// </example> /// </summary> internal struct TupleTypeDecoder { private readonly ImmutableArray<string?> _elementNames; // Keep track of how many names we've "used" during decoding. Starts at // the back of the array and moves forward. private int _namesIndex; private bool _foundUsableErrorType; private bool _decodingFailed; private TupleTypeDecoder(ImmutableArray<string?> elementNames) { _elementNames = elementNames; _namesIndex = elementNames.IsDefault ? 0 : elementNames.Length; _decodingFailed = false; _foundUsableErrorType = false; } public static TypeSymbol DecodeTupleTypesIfApplicable( TypeSymbol metadataType, EntityHandle targetHandle, PEModuleSymbol containingModule) { ImmutableArray<string?> elementNames; var hasTupleElementNamesAttribute = containingModule .Module .HasTupleElementNamesAttribute(targetHandle, out elementNames); // If we have the TupleElementNamesAttribute, but no names, that's // bad metadata if (hasTupleElementNamesAttribute && elementNames.IsDefaultOrEmpty) { return new UnsupportedMetadataTypeSymbol(); } return DecodeTupleTypesInternal(metadataType, elementNames, hasTupleElementNamesAttribute); } public static TypeWithAnnotations DecodeTupleTypesIfApplicable( TypeWithAnnotations metadataType, EntityHandle targetHandle, PEModuleSymbol containingModule) { ImmutableArray<string?> elementNames; var hasTupleElementNamesAttribute = containingModule .Module .HasTupleElementNamesAttribute(targetHandle, out elementNames); // If we have the TupleElementNamesAttribute, but no names, that's // bad metadata if (hasTupleElementNamesAttribute && elementNames.IsDefaultOrEmpty) { return TypeWithAnnotations.Create(new UnsupportedMetadataTypeSymbol()); } TypeSymbol type = metadataType.Type; TypeSymbol decoded = DecodeTupleTypesInternal(type, elementNames, hasTupleElementNamesAttribute); return (object)decoded == (object)type ? metadataType : TypeWithAnnotations.Create(decoded, metadataType.NullableAnnotation, metadataType.CustomModifiers); } public static TypeSymbol DecodeTupleTypesIfApplicable( TypeSymbol metadataType, ImmutableArray<string?> elementNames) { return DecodeTupleTypesInternal(metadataType, elementNames, hasTupleElementNamesAttribute: !elementNames.IsDefaultOrEmpty); } private static TypeSymbol DecodeTupleTypesInternal(TypeSymbol metadataType, ImmutableArray<string?> elementNames, bool hasTupleElementNamesAttribute) { RoslynDebug.AssertNotNull(metadataType); var decoder = new TupleTypeDecoder(elementNames); var decoded = decoder.DecodeType(metadataType); if (!decoder._decodingFailed) { if (!hasTupleElementNamesAttribute || decoder._namesIndex == 0) { return decoded; } } // If not all of the names have been used, the metadata is bad if (decoder._foundUsableErrorType) { return metadataType; } // Bad metadata return new UnsupportedMetadataTypeSymbol(); } private TypeSymbol DecodeType(TypeSymbol type) { switch (type.Kind) { case SymbolKind.ErrorType: _foundUsableErrorType = true; return type; case SymbolKind.DynamicType: case SymbolKind.TypeParameter: return type; case SymbolKind.FunctionPointerType: return DecodeFunctionPointerType((FunctionPointerTypeSymbol)type); case SymbolKind.PointerType: return DecodePointerType((PointerTypeSymbol)type); case SymbolKind.NamedType: // We may have a tuple type from a substituted type symbol, // but it will be missing names from metadata, so we'll // need to re-create the type. // // Consider the declaration // // class C : BaseType<(int x, int y)> // // The process for decoding tuples in C looks at the BaseType, calls // DecodeOrThrow, then passes the decoded type to the TupleTypeDecoder. // However, DecodeOrThrow uses the AbstractTypeMap to construct a // SubstitutedTypeSymbol, which eagerly converts tuple-compatible // types to TupleTypeSymbols. Thus, by the time we get to the Decoder // all metadata instances of System.ValueTuple will have been // replaced with TupleTypeSymbols without names. // // Rather than fixing up after-the-fact it's possible that we could // flow up a SubstituteWith/Without tuple unification to the top level // of the type map and change DecodeOrThrow to call into the substitution // without unification instead. return DecodeNamedType((NamedTypeSymbol)type); case SymbolKind.ArrayType: return DecodeArrayType((ArrayTypeSymbol)type); default: throw ExceptionUtilities.UnexpectedValue(type.TypeKind); } } private PointerTypeSymbol DecodePointerType(PointerTypeSymbol type) { return type.WithPointedAtType(DecodeTypeInternal(type.PointedAtTypeWithAnnotations)); } private FunctionPointerTypeSymbol DecodeFunctionPointerType(FunctionPointerTypeSymbol type) { var parameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; var paramsModified = false; if (type.Signature.ParameterCount > 0) { var paramsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(type.Signature.ParameterCount); for (int i = type.Signature.ParameterCount - 1; i >= 0; i--) { var param = type.Signature.Parameters[i]; var decodedParam = DecodeTypeInternal(param.TypeWithAnnotations); paramsModified = paramsModified || !decodedParam.IsSameAs(param.TypeWithAnnotations); paramsBuilder.Add(decodedParam); } if (paramsModified) { paramsBuilder.ReverseContents(); parameterTypes = paramsBuilder.ToImmutableAndFree(); } else { parameterTypes = type.Signature.ParameterTypesWithAnnotations; paramsBuilder.Free(); } } var decodedReturnType = DecodeTypeInternal(type.Signature.ReturnTypeWithAnnotations); if (paramsModified || !decodedReturnType.IsSameAs(type.Signature.ReturnTypeWithAnnotations)) { return type.SubstituteTypeSymbol(decodedReturnType, parameterTypes, refCustomModifiers: default, paramRefCustomModifiers: default); } else { return type; } } private NamedTypeSymbol DecodeNamedType(NamedTypeSymbol type) { // First decode the type arguments var typeArgs = type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; var decodedArgs = DecodeTypeArguments(typeArgs); NamedTypeSymbol decodedType = type; // Now check the container NamedTypeSymbol containingType = type.ContainingType; NamedTypeSymbol? decodedContainingType; if (containingType is object && containingType.IsGenericType) { decodedContainingType = DecodeNamedType(containingType); Debug.Assert(decodedContainingType.IsGenericType); } else { decodedContainingType = containingType; } // Replace the type if necessary var containerChanged = !ReferenceEquals(decodedContainingType, containingType); var typeArgsChanged = typeArgs != decodedArgs; if (typeArgsChanged || containerChanged) { if (containerChanged) { decodedType = decodedType.OriginalDefinition.AsMember(decodedContainingType); // If the type is nested, e.g. Outer<T>.Inner<V>, then Inner is definitely // not a tuple, since we know all tuple-compatible types (System.ValueTuple) // are not nested types. Thus, it is safe to return without checking if // Inner is a tuple. return decodedType.ConstructIfGeneric(decodedArgs); } decodedType = type.ConstructedFrom.Construct(decodedArgs, unbound: false); } // Now decode into a tuple, if it is one if (decodedType.IsTupleType) { int tupleCardinality = decodedType.TupleElementTypesWithAnnotations.Length; if (tupleCardinality > 0) { var elementNames = EatElementNamesIfAvailable(tupleCardinality); Debug.Assert(elementNames.IsDefault || elementNames.Length == tupleCardinality); decodedType = NamedTypeSymbol.CreateTuple(decodedType, elementNames); } } return decodedType; } private ImmutableArray<TypeWithAnnotations> DecodeTypeArguments(ImmutableArray<TypeWithAnnotations> typeArgs) { if (typeArgs.IsEmpty) { return typeArgs; } var decodedArgs = ArrayBuilder<TypeWithAnnotations>.GetInstance(typeArgs.Length); var anyDecoded = false; // Visit the type arguments in reverse for (int i = typeArgs.Length - 1; i >= 0; i--) { TypeWithAnnotations typeArg = typeArgs[i]; TypeWithAnnotations decoded = DecodeTypeInternal(typeArg); anyDecoded |= !decoded.IsSameAs(typeArg); decodedArgs.Add(decoded); } if (!anyDecoded) { decodedArgs.Free(); return typeArgs; } decodedArgs.ReverseContents(); return decodedArgs.ToImmutableAndFree(); } private ArrayTypeSymbol DecodeArrayType(ArrayTypeSymbol type) { TypeWithAnnotations decodedElementType = DecodeTypeInternal(type.ElementTypeWithAnnotations); return type.WithElementType(decodedElementType); } private TypeWithAnnotations DecodeTypeInternal(TypeWithAnnotations typeWithAnnotations) { TypeSymbol type = typeWithAnnotations.Type; TypeSymbol decoded = DecodeType(type); return ReferenceEquals(decoded, type) ? typeWithAnnotations : TypeWithAnnotations.Create(decoded, typeWithAnnotations.NullableAnnotation, typeWithAnnotations.CustomModifiers); } private ImmutableArray<string?> EatElementNamesIfAvailable(int numberOfElements) { Debug.Assert(numberOfElements > 0); // If we don't have any element names there's nothing to eat if (_elementNames.IsDefault) { return _elementNames; } // We've gone past the end of the names -- bad metadata if (numberOfElements > _namesIndex) { // We'll want to continue decoding without consuming more names to see if there are any error types _namesIndex = 0; _decodingFailed = true; return default; } // Check to see if all the elements are null var start = _namesIndex - numberOfElements; _namesIndex = start; bool allNull = true; for (int i = 0; i < numberOfElements; i++) { if (_elementNames[start + i] != null) { allNull = false; break; } } if (allNull) { return default; } return ImmutableArray.Create(_elementNames, start, numberOfElements); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.PooledObjects; using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE { /// <summary> /// In C#, tuples can be represented using tuple syntax and be given /// names. However, the underlying representation for tuples unifies /// to a single underlying tuple type, System.ValueTuple. Since the /// names aren't part of the underlying tuple type they have to be /// recorded somewhere else. /// /// Roslyn records tuple names in an attribute: the /// TupleElementNamesAttribute. The attribute contains a single string /// array which records the names of the tuple elements in a pre-order /// depth-first traversal. If the type contains nested parameters, /// they are also recorded in a pre-order depth-first traversal. /// <see cref="DecodeTupleTypesIfApplicable(TypeSymbol, EntityHandle, PEModuleSymbol)"/> /// can be used to extract tuple names and types from metadata and create /// a <see cref="NamedTypeSymbol"/> with attached names. /// /// <example> /// For instance, a method returning a tuple /// /// <code> /// (int x, int y) M() { ... } /// </code> /// /// will be encoded using an attribute on the return type as follows /// /// <code> /// [return: TupleElementNamesAttribute(new[] { "x", "y" })] /// System.ValueTuple&lt;int, int&gt; M() { ... } /// </code> /// </example> /// /// <example> /// For nested type parameters, we expand the tuple names in a pre-order /// traversal: /// /// <code> /// class C : BaseType&lt;((int e1, int e2) e3, int e4)&lt; { ... } /// </code> /// /// becomes /// /// <code> /// [TupleElementNamesAttribute(new[] { "e3", "e4", "e1", "e2" }); /// class C : BaseType&lt;System.ValueTuple&lt; /// System.ValueTuple&lt;int,int&gt;, int&gt; /// { ... } /// </code> /// </example> /// </summary> internal struct TupleTypeDecoder { private readonly ImmutableArray<string?> _elementNames; // Keep track of how many names we've "used" during decoding. Starts at // the back of the array and moves forward. private int _namesIndex; private bool _foundUsableErrorType; private bool _decodingFailed; private TupleTypeDecoder(ImmutableArray<string?> elementNames) { _elementNames = elementNames; _namesIndex = elementNames.IsDefault ? 0 : elementNames.Length; _decodingFailed = false; _foundUsableErrorType = false; } public static TypeSymbol DecodeTupleTypesIfApplicable( TypeSymbol metadataType, EntityHandle targetHandle, PEModuleSymbol containingModule) { ImmutableArray<string?> elementNames; var hasTupleElementNamesAttribute = containingModule .Module .HasTupleElementNamesAttribute(targetHandle, out elementNames); // If we have the TupleElementNamesAttribute, but no names, that's // bad metadata if (hasTupleElementNamesAttribute && elementNames.IsDefaultOrEmpty) { return new UnsupportedMetadataTypeSymbol(); } return DecodeTupleTypesInternal(metadataType, elementNames, hasTupleElementNamesAttribute); } public static TypeWithAnnotations DecodeTupleTypesIfApplicable( TypeWithAnnotations metadataType, EntityHandle targetHandle, PEModuleSymbol containingModule) { ImmutableArray<string?> elementNames; var hasTupleElementNamesAttribute = containingModule .Module .HasTupleElementNamesAttribute(targetHandle, out elementNames); // If we have the TupleElementNamesAttribute, but no names, that's // bad metadata if (hasTupleElementNamesAttribute && elementNames.IsDefaultOrEmpty) { return TypeWithAnnotations.Create(new UnsupportedMetadataTypeSymbol()); } TypeSymbol type = metadataType.Type; TypeSymbol decoded = DecodeTupleTypesInternal(type, elementNames, hasTupleElementNamesAttribute); return (object)decoded == (object)type ? metadataType : TypeWithAnnotations.Create(decoded, metadataType.NullableAnnotation, metadataType.CustomModifiers); } public static TypeSymbol DecodeTupleTypesIfApplicable( TypeSymbol metadataType, ImmutableArray<string?> elementNames) { return DecodeTupleTypesInternal(metadataType, elementNames, hasTupleElementNamesAttribute: !elementNames.IsDefaultOrEmpty); } private static TypeSymbol DecodeTupleTypesInternal(TypeSymbol metadataType, ImmutableArray<string?> elementNames, bool hasTupleElementNamesAttribute) { RoslynDebug.AssertNotNull(metadataType); var decoder = new TupleTypeDecoder(elementNames); var decoded = decoder.DecodeType(metadataType); if (!decoder._decodingFailed) { if (!hasTupleElementNamesAttribute || decoder._namesIndex == 0) { return decoded; } } // If not all of the names have been used, the metadata is bad if (decoder._foundUsableErrorType) { return metadataType; } // Bad metadata return new UnsupportedMetadataTypeSymbol(); } private TypeSymbol DecodeType(TypeSymbol type) { switch (type.Kind) { case SymbolKind.ErrorType: _foundUsableErrorType = true; return type; case SymbolKind.DynamicType: case SymbolKind.TypeParameter: return type; case SymbolKind.FunctionPointerType: return DecodeFunctionPointerType((FunctionPointerTypeSymbol)type); case SymbolKind.PointerType: return DecodePointerType((PointerTypeSymbol)type); case SymbolKind.NamedType: // We may have a tuple type from a substituted type symbol, // but it will be missing names from metadata, so we'll // need to re-create the type. // // Consider the declaration // // class C : BaseType<(int x, int y)> // // The process for decoding tuples in C looks at the BaseType, calls // DecodeOrThrow, then passes the decoded type to the TupleTypeDecoder. // However, DecodeOrThrow uses the AbstractTypeMap to construct a // SubstitutedTypeSymbol, which eagerly converts tuple-compatible // types to TupleTypeSymbols. Thus, by the time we get to the Decoder // all metadata instances of System.ValueTuple will have been // replaced with TupleTypeSymbols without names. // // Rather than fixing up after-the-fact it's possible that we could // flow up a SubstituteWith/Without tuple unification to the top level // of the type map and change DecodeOrThrow to call into the substitution // without unification instead. return DecodeNamedType((NamedTypeSymbol)type); case SymbolKind.ArrayType: return DecodeArrayType((ArrayTypeSymbol)type); default: throw ExceptionUtilities.UnexpectedValue(type.TypeKind); } } private PointerTypeSymbol DecodePointerType(PointerTypeSymbol type) { return type.WithPointedAtType(DecodeTypeInternal(type.PointedAtTypeWithAnnotations)); } private FunctionPointerTypeSymbol DecodeFunctionPointerType(FunctionPointerTypeSymbol type) { var parameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; var paramsModified = false; if (type.Signature.ParameterCount > 0) { var paramsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(type.Signature.ParameterCount); for (int i = type.Signature.ParameterCount - 1; i >= 0; i--) { var param = type.Signature.Parameters[i]; var decodedParam = DecodeTypeInternal(param.TypeWithAnnotations); paramsModified = paramsModified || !decodedParam.IsSameAs(param.TypeWithAnnotations); paramsBuilder.Add(decodedParam); } if (paramsModified) { paramsBuilder.ReverseContents(); parameterTypes = paramsBuilder.ToImmutableAndFree(); } else { parameterTypes = type.Signature.ParameterTypesWithAnnotations; paramsBuilder.Free(); } } var decodedReturnType = DecodeTypeInternal(type.Signature.ReturnTypeWithAnnotations); if (paramsModified || !decodedReturnType.IsSameAs(type.Signature.ReturnTypeWithAnnotations)) { return type.SubstituteTypeSymbol(decodedReturnType, parameterTypes, refCustomModifiers: default, paramRefCustomModifiers: default); } else { return type; } } private NamedTypeSymbol DecodeNamedType(NamedTypeSymbol type) { // First decode the type arguments var typeArgs = type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; var decodedArgs = DecodeTypeArguments(typeArgs); NamedTypeSymbol decodedType = type; // Now check the container NamedTypeSymbol containingType = type.ContainingType; NamedTypeSymbol? decodedContainingType; if (containingType is object && containingType.IsGenericType) { decodedContainingType = DecodeNamedType(containingType); Debug.Assert(decodedContainingType.IsGenericType); } else { decodedContainingType = containingType; } // Replace the type if necessary var containerChanged = !ReferenceEquals(decodedContainingType, containingType); var typeArgsChanged = typeArgs != decodedArgs; if (typeArgsChanged || containerChanged) { if (containerChanged) { decodedType = decodedType.OriginalDefinition.AsMember(decodedContainingType); // If the type is nested, e.g. Outer<T>.Inner<V>, then Inner is definitely // not a tuple, since we know all tuple-compatible types (System.ValueTuple) // are not nested types. Thus, it is safe to return without checking if // Inner is a tuple. return decodedType.ConstructIfGeneric(decodedArgs); } decodedType = type.ConstructedFrom.Construct(decodedArgs, unbound: false); } // Now decode into a tuple, if it is one if (decodedType.IsTupleType) { int tupleCardinality = decodedType.TupleElementTypesWithAnnotations.Length; if (tupleCardinality > 0) { var elementNames = EatElementNamesIfAvailable(tupleCardinality); Debug.Assert(elementNames.IsDefault || elementNames.Length == tupleCardinality); decodedType = NamedTypeSymbol.CreateTuple(decodedType, elementNames); } } return decodedType; } private ImmutableArray<TypeWithAnnotations> DecodeTypeArguments(ImmutableArray<TypeWithAnnotations> typeArgs) { if (typeArgs.IsEmpty) { return typeArgs; } var decodedArgs = ArrayBuilder<TypeWithAnnotations>.GetInstance(typeArgs.Length); var anyDecoded = false; // Visit the type arguments in reverse for (int i = typeArgs.Length - 1; i >= 0; i--) { TypeWithAnnotations typeArg = typeArgs[i]; TypeWithAnnotations decoded = DecodeTypeInternal(typeArg); anyDecoded |= !decoded.IsSameAs(typeArg); decodedArgs.Add(decoded); } if (!anyDecoded) { decodedArgs.Free(); return typeArgs; } decodedArgs.ReverseContents(); return decodedArgs.ToImmutableAndFree(); } private ArrayTypeSymbol DecodeArrayType(ArrayTypeSymbol type) { TypeWithAnnotations decodedElementType = DecodeTypeInternal(type.ElementTypeWithAnnotations); return type.WithElementType(decodedElementType); } private TypeWithAnnotations DecodeTypeInternal(TypeWithAnnotations typeWithAnnotations) { TypeSymbol type = typeWithAnnotations.Type; TypeSymbol decoded = DecodeType(type); return ReferenceEquals(decoded, type) ? typeWithAnnotations : TypeWithAnnotations.Create(decoded, typeWithAnnotations.NullableAnnotation, typeWithAnnotations.CustomModifiers); } private ImmutableArray<string?> EatElementNamesIfAvailable(int numberOfElements) { Debug.Assert(numberOfElements > 0); // If we don't have any element names there's nothing to eat if (_elementNames.IsDefault) { return _elementNames; } // We've gone past the end of the names -- bad metadata if (numberOfElements > _namesIndex) { // We'll want to continue decoding without consuming more names to see if there are any error types _namesIndex = 0; _decodingFailed = true; return default; } // Check to see if all the elements are null var start = _namesIndex - numberOfElements; _namesIndex = start; bool allNull = true; for (int i = 0; i < numberOfElements; i++) { if (_elementNames[start + i] != null) { allNull = false; break; } } if (allNull) { return default; } return ImmutableArray.Create(_elementNames, start, numberOfElements); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/MemberInfo/ModuleImpl.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Diagnostics; using Microsoft.VisualStudio.Debugger.Metadata; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal sealed class ModuleImpl : Module { internal readonly System.Reflection.Module Module; internal ModuleImpl(System.Reflection.Module module) { Debug.Assert(module != null); this.Module = module; } public override Type[] FindTypes(TypeFilter filter, object filterCriteria) { throw new NotImplementedException(); } public override IList<CustomAttributeData> GetCustomAttributesData() { throw new NotImplementedException(); } public override Type GetType(string className, bool throwOnError, bool ignoreCase) { throw new NotImplementedException(); } public override Type[] GetTypes() { throw new NotImplementedException(); } public override Guid ModuleVersionId { get { return this.Module.ModuleVersionId; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Diagnostics; using Microsoft.VisualStudio.Debugger.Metadata; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal sealed class ModuleImpl : Module { internal readonly System.Reflection.Module Module; internal ModuleImpl(System.Reflection.Module module) { Debug.Assert(module != null); this.Module = module; } public override Type[] FindTypes(TypeFilter filter, object filterCriteria) { throw new NotImplementedException(); } public override IList<CustomAttributeData> GetCustomAttributesData() { throw new NotImplementedException(); } public override Type GetType(string className, bool throwOnError, bool ignoreCase) { throw new NotImplementedException(); } public override Type[] GetTypes() { throw new NotImplementedException(); } public override Guid ModuleVersionId { get { return this.Module.ModuleVersionId; } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/Core/Portable/Shared/Extensions/ISymbolExtensions_2.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Shared.Extensions { internal static partial class ISymbolExtensions { public static bool IsImplicitValueParameter([NotNullWhen(returnValue: true)] this ISymbol? symbol) { if (symbol is IParameterSymbol && symbol.IsImplicitlyDeclared) { if (symbol.ContainingSymbol is IMethodSymbol method) { if (method.MethodKind == MethodKind.EventAdd || method.MethodKind == MethodKind.EventRemove || method.MethodKind == MethodKind.PropertySet) { // the name is value in C#, and Value in VB return symbol.Name == "value" || symbol.Name == "Value"; } } } 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.Shared.Extensions { internal static partial class ISymbolExtensions { public static bool IsImplicitValueParameter([NotNullWhen(returnValue: true)] this ISymbol? symbol) { if (symbol is IParameterSymbol && symbol.IsImplicitlyDeclared) { if (symbol.ContainingSymbol is IMethodSymbol method) { if (method.MethodKind == MethodKind.EventAdd || method.MethodKind == MethodKind.EventRemove || method.MethodKind == MethodKind.PropertySet) { // the name is value in C#, and Value in VB return symbol.Name == "value" || symbol.Name == "Value"; } } } return false; } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/CSharp/EventHookup/EventHookupSessionManager_EventHookupSession.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup { internal sealed partial class EventHookupSessionManager { /// <summary> /// A session begins when an '=' is typed after a '+' and requires determining whether the /// += is being used to add an event handler to an event. If it is, then we also determine /// a candidate name for the event handler. /// </summary> internal class EventHookupSession : ForegroundThreadAffinitizedObject { public readonly Task<string> GetEventNameTask; private readonly CancellationTokenSource _cancellationTokenSource; private readonly ITrackingPoint _trackingPoint; private readonly ITrackingSpan _trackingSpan; private readonly ITextView _textView; private readonly ITextBuffer _subjectBuffer; public event Action Dismissed = () => { }; // For testing purposes only! Should always be null except in tests. internal Mutex TESTSessionHookupMutex = null; public ITrackingPoint TrackingPoint { get { AssertIsForeground(); return _trackingPoint; } } public ITrackingSpan TrackingSpan { get { AssertIsForeground(); return _trackingSpan; } } public ITextView TextView { get { AssertIsForeground(); return _textView; } } public ITextBuffer SubjectBuffer { get { AssertIsForeground(); return _subjectBuffer; } } public void Cancel() { AssertIsForeground(); _cancellationTokenSource.Cancel(); } public EventHookupSession( EventHookupSessionManager eventHookupSessionManager, EventHookupCommandHandler commandHandler, ITextView textView, ITextBuffer subjectBuffer, IAsynchronousOperationListener asyncListener, Mutex testSessionHookupMutex) : base(eventHookupSessionManager.ThreadingContext) { AssertIsForeground(); _cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = _cancellationTokenSource.Token; _textView = textView; _subjectBuffer = subjectBuffer; this.TESTSessionHookupMutex = testSessionHookupMutex; var document = textView.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null && document.Project.Solution.Workspace.CanApplyChange(ApplyChangesKind.ChangeDocument)) { var position = textView.GetCaretPoint(subjectBuffer).Value.Position; _trackingPoint = textView.TextSnapshot.CreateTrackingPoint(position, PointTrackingMode.Negative); _trackingSpan = textView.TextSnapshot.CreateTrackingSpan(new Span(position, 1), SpanTrackingMode.EdgeInclusive); var asyncToken = asyncListener.BeginAsyncOperation(GetType().Name + ".Start"); this.GetEventNameTask = Task.Factory.SafeStartNewFromAsync( () => DetermineIfEventHookupAndGetHandlerNameAsync(document, position, cancellationToken), cancellationToken, TaskScheduler.Default); var continuedTask = this.GetEventNameTask.SafeContinueWithFromAsync( async t => { await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken); if (t.Result != null) { commandHandler.EventHookupSessionManager.EventHookupFoundInSession(this); } }, cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); continuedTask.CompletesAsyncOperation(asyncToken); } else { _trackingPoint = textView.TextSnapshot.CreateTrackingPoint(0, PointTrackingMode.Negative); _trackingSpan = textView.TextSnapshot.CreateTrackingSpan(new Span(), SpanTrackingMode.EdgeInclusive); this.GetEventNameTask = SpecializedTasks.Null<string>(); eventHookupSessionManager.CancelAndDismissExistingSessions(); } } private async Task<string> DetermineIfEventHookupAndGetHandlerNameAsync(Document document, int position, CancellationToken cancellationToken) { AssertIsBackground(); // For test purposes only! if (TESTSessionHookupMutex != null) { TESTSessionHookupMutex.WaitOne(); TESTSessionHookupMutex.ReleaseMutex(); } using (Logger.LogBlock(FunctionId.EventHookup_Determine_If_Event_Hookup, cancellationToken)) { var plusEqualsToken = await GetPlusEqualsTokenInsideAddAssignExpressionAsync(document, position, cancellationToken).ConfigureAwait(false); if (plusEqualsToken == null) { return null; } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var eventSymbol = GetEventSymbol(semanticModel, plusEqualsToken.Value, cancellationToken); if (eventSymbol == null) { return null; } var namingRule = await document.GetApplicableNamingRuleAsync( new SymbolKindOrTypeKind(MethodKind.Ordinary), new DeclarationModifiers(isStatic: plusEqualsToken.Value.Parent.IsInStaticContext()), Accessibility.Private, cancellationToken).ConfigureAwait(false); return GetEventHandlerName( eventSymbol, plusEqualsToken.Value, semanticModel, document.GetLanguageService<ISyntaxFactsService>(), namingRule); } } private async Task<SyntaxToken?> GetPlusEqualsTokenInsideAddAssignExpressionAsync(Document document, int position, CancellationToken cancellationToken) { AssertIsBackground(); var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); if (token.Kind() != SyntaxKind.PlusEqualsToken) { return null; } if (!token.Parent.IsKind(SyntaxKind.AddAssignmentExpression)) { return null; } return token; } private IEventSymbol GetEventSymbol(SemanticModel semanticModel, SyntaxToken plusEqualsToken, CancellationToken cancellationToken) { AssertIsBackground(); if (!(plusEqualsToken.Parent is AssignmentExpressionSyntax parentToken)) { return null; } var symbol = semanticModel.GetSymbolInfo(parentToken.Left, cancellationToken).Symbol; if (symbol == null) { return null; } return symbol as IEventSymbol; } private string GetEventHandlerName( IEventSymbol eventSymbol, SyntaxToken plusEqualsToken, SemanticModel semanticModel, ISyntaxFactsService syntaxFactsService, NamingRule namingRule) { AssertIsBackground(); var objectPart = GetNameObjectPart(eventSymbol, plusEqualsToken, semanticModel, syntaxFactsService); var basename = namingRule.NamingStyle.CreateName(ImmutableArray.Create( string.Format("{0}_{1}", objectPart, eventSymbol.Name))); var reservedNames = semanticModel.LookupSymbols(plusEqualsToken.SpanStart).Select(m => m.Name); return NameGenerator.EnsureUniqueness(basename, reservedNames); } /// <summary> /// Take another look at the LHS of the += node -- we need to figure out a default name /// for the event handler, and that's usually based on the object (which is usually a /// field of 'this', but not always) to which the event belongs. So, if the event is /// something like 'button1.Click' or 'this.listBox1.Select', we want the names /// 'button1' and 'listBox1' respectively. If the field belongs to 'this', then we use /// the name of this class, as we do if we can't make any sense out of the parse tree. /// </summary> private string GetNameObjectPart(IEventSymbol eventSymbol, SyntaxToken plusEqualsToken, SemanticModel semanticModel, ISyntaxFactsService syntaxFactsService) { AssertIsBackground(); var parentToken = plusEqualsToken.Parent as AssignmentExpressionSyntax; if (parentToken.Left is MemberAccessExpressionSyntax memberAccessExpression) { // This is expected -- it means the last thing is(probably) the event name. We // already have that in eventSymbol. What we need is the LHS of that dot. var lhs = memberAccessExpression.Expression; if (lhs is MemberAccessExpressionSyntax lhsMemberAccessExpression) { // Okay, cool. The name we're after is in the RHS of this dot. return lhsMemberAccessExpression.Name.ToString(); } if (lhs is NameSyntax lhsNameSyntax) { // Even easier -- the LHS of the dot is the name itself return lhsNameSyntax.ToString(); } } // If we didn't find an object name above, then the object name is the name of this class. // Note: For generic, it's ok(it's even a good idea) to exclude type variables, // because the name is only used as a prefix for the method name. var typeDeclaration = syntaxFactsService.GetContainingTypeDeclaration( semanticModel.SyntaxTree.GetRoot(), plusEqualsToken.SpanStart) as BaseTypeDeclarationSyntax; return typeDeclaration != null ? typeDeclaration.Identifier.Text : eventSymbol.ContainingType.Name; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup { internal sealed partial class EventHookupSessionManager { /// <summary> /// A session begins when an '=' is typed after a '+' and requires determining whether the /// += is being used to add an event handler to an event. If it is, then we also determine /// a candidate name for the event handler. /// </summary> internal class EventHookupSession : ForegroundThreadAffinitizedObject { public readonly Task<string> GetEventNameTask; private readonly CancellationTokenSource _cancellationTokenSource; private readonly ITrackingPoint _trackingPoint; private readonly ITrackingSpan _trackingSpan; private readonly ITextView _textView; private readonly ITextBuffer _subjectBuffer; public event Action Dismissed = () => { }; // For testing purposes only! Should always be null except in tests. internal Mutex TESTSessionHookupMutex = null; public ITrackingPoint TrackingPoint { get { AssertIsForeground(); return _trackingPoint; } } public ITrackingSpan TrackingSpan { get { AssertIsForeground(); return _trackingSpan; } } public ITextView TextView { get { AssertIsForeground(); return _textView; } } public ITextBuffer SubjectBuffer { get { AssertIsForeground(); return _subjectBuffer; } } public void Cancel() { AssertIsForeground(); _cancellationTokenSource.Cancel(); } public EventHookupSession( EventHookupSessionManager eventHookupSessionManager, EventHookupCommandHandler commandHandler, ITextView textView, ITextBuffer subjectBuffer, IAsynchronousOperationListener asyncListener, Mutex testSessionHookupMutex) : base(eventHookupSessionManager.ThreadingContext) { AssertIsForeground(); _cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = _cancellationTokenSource.Token; _textView = textView; _subjectBuffer = subjectBuffer; this.TESTSessionHookupMutex = testSessionHookupMutex; var document = textView.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null && document.Project.Solution.Workspace.CanApplyChange(ApplyChangesKind.ChangeDocument)) { var position = textView.GetCaretPoint(subjectBuffer).Value.Position; _trackingPoint = textView.TextSnapshot.CreateTrackingPoint(position, PointTrackingMode.Negative); _trackingSpan = textView.TextSnapshot.CreateTrackingSpan(new Span(position, 1), SpanTrackingMode.EdgeInclusive); var asyncToken = asyncListener.BeginAsyncOperation(GetType().Name + ".Start"); this.GetEventNameTask = Task.Factory.SafeStartNewFromAsync( () => DetermineIfEventHookupAndGetHandlerNameAsync(document, position, cancellationToken), cancellationToken, TaskScheduler.Default); var continuedTask = this.GetEventNameTask.SafeContinueWithFromAsync( async t => { await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken); if (t.Result != null) { commandHandler.EventHookupSessionManager.EventHookupFoundInSession(this); } }, cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); continuedTask.CompletesAsyncOperation(asyncToken); } else { _trackingPoint = textView.TextSnapshot.CreateTrackingPoint(0, PointTrackingMode.Negative); _trackingSpan = textView.TextSnapshot.CreateTrackingSpan(new Span(), SpanTrackingMode.EdgeInclusive); this.GetEventNameTask = SpecializedTasks.Null<string>(); eventHookupSessionManager.CancelAndDismissExistingSessions(); } } private async Task<string> DetermineIfEventHookupAndGetHandlerNameAsync(Document document, int position, CancellationToken cancellationToken) { AssertIsBackground(); // For test purposes only! if (TESTSessionHookupMutex != null) { TESTSessionHookupMutex.WaitOne(); TESTSessionHookupMutex.ReleaseMutex(); } using (Logger.LogBlock(FunctionId.EventHookup_Determine_If_Event_Hookup, cancellationToken)) { var plusEqualsToken = await GetPlusEqualsTokenInsideAddAssignExpressionAsync(document, position, cancellationToken).ConfigureAwait(false); if (plusEqualsToken == null) { return null; } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var eventSymbol = GetEventSymbol(semanticModel, plusEqualsToken.Value, cancellationToken); if (eventSymbol == null) { return null; } var namingRule = await document.GetApplicableNamingRuleAsync( new SymbolKindOrTypeKind(MethodKind.Ordinary), new DeclarationModifiers(isStatic: plusEqualsToken.Value.Parent.IsInStaticContext()), Accessibility.Private, cancellationToken).ConfigureAwait(false); return GetEventHandlerName( eventSymbol, plusEqualsToken.Value, semanticModel, document.GetLanguageService<ISyntaxFactsService>(), namingRule); } } private async Task<SyntaxToken?> GetPlusEqualsTokenInsideAddAssignExpressionAsync(Document document, int position, CancellationToken cancellationToken) { AssertIsBackground(); var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); if (token.Kind() != SyntaxKind.PlusEqualsToken) { return null; } if (!token.Parent.IsKind(SyntaxKind.AddAssignmentExpression)) { return null; } return token; } private IEventSymbol GetEventSymbol(SemanticModel semanticModel, SyntaxToken plusEqualsToken, CancellationToken cancellationToken) { AssertIsBackground(); if (!(plusEqualsToken.Parent is AssignmentExpressionSyntax parentToken)) { return null; } var symbol = semanticModel.GetSymbolInfo(parentToken.Left, cancellationToken).Symbol; if (symbol == null) { return null; } return symbol as IEventSymbol; } private string GetEventHandlerName( IEventSymbol eventSymbol, SyntaxToken plusEqualsToken, SemanticModel semanticModel, ISyntaxFactsService syntaxFactsService, NamingRule namingRule) { AssertIsBackground(); var objectPart = GetNameObjectPart(eventSymbol, plusEqualsToken, semanticModel, syntaxFactsService); var basename = namingRule.NamingStyle.CreateName(ImmutableArray.Create( string.Format("{0}_{1}", objectPart, eventSymbol.Name))); var reservedNames = semanticModel.LookupSymbols(plusEqualsToken.SpanStart).Select(m => m.Name); return NameGenerator.EnsureUniqueness(basename, reservedNames); } /// <summary> /// Take another look at the LHS of the += node -- we need to figure out a default name /// for the event handler, and that's usually based on the object (which is usually a /// field of 'this', but not always) to which the event belongs. So, if the event is /// something like 'button1.Click' or 'this.listBox1.Select', we want the names /// 'button1' and 'listBox1' respectively. If the field belongs to 'this', then we use /// the name of this class, as we do if we can't make any sense out of the parse tree. /// </summary> private string GetNameObjectPart(IEventSymbol eventSymbol, SyntaxToken plusEqualsToken, SemanticModel semanticModel, ISyntaxFactsService syntaxFactsService) { AssertIsBackground(); var parentToken = plusEqualsToken.Parent as AssignmentExpressionSyntax; if (parentToken.Left is MemberAccessExpressionSyntax memberAccessExpression) { // This is expected -- it means the last thing is(probably) the event name. We // already have that in eventSymbol. What we need is the LHS of that dot. var lhs = memberAccessExpression.Expression; if (lhs is MemberAccessExpressionSyntax lhsMemberAccessExpression) { // Okay, cool. The name we're after is in the RHS of this dot. return lhsMemberAccessExpression.Name.ToString(); } if (lhs is NameSyntax lhsNameSyntax) { // Even easier -- the LHS of the dot is the name itself return lhsNameSyntax.ToString(); } } // If we didn't find an object name above, then the object name is the name of this class. // Note: For generic, it's ok(it's even a good idea) to exclude type variables, // because the name is only used as a prefix for the method name. var typeDeclaration = syntaxFactsService.GetContainingTypeDeclaration( semanticModel.SyntaxTree.GetRoot(), plusEqualsToken.SpanStart) as BaseTypeDeclarationSyntax; return typeDeclaration != null ? typeDeclaration.Identifier.Text : eventSymbol.ContainingType.Name; } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/Core/Portable/DiaSymReader/Writer/SymUnmanagedWriterImpl.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace Microsoft.DiaSymReader { internal sealed class SymUnmanagedWriterImpl : SymUnmanagedWriter { private static readonly object s_zeroInt32 = 0; private ISymUnmanagedWriter5 _symWriter; private readonly ComMemoryStream _pdbStream; private readonly List<ISymUnmanagedDocumentWriter> _documentWriters; private readonly string _symWriterModuleName; private bool _disposed; internal SymUnmanagedWriterImpl(ComMemoryStream pdbStream, ISymUnmanagedWriter5 symWriter, string symWriterModuleName) { Debug.Assert(pdbStream != null); Debug.Assert(symWriter != null); Debug.Assert(symWriterModuleName != null); _pdbStream = pdbStream; _symWriter = symWriter; _documentWriters = new List<ISymUnmanagedDocumentWriter>(); _symWriterModuleName = symWriterModuleName; } private ISymUnmanagedWriter5 GetSymWriter() => _symWriter ?? throw (_disposed ? new ObjectDisposedException(nameof(SymUnmanagedWriterImpl)) : new InvalidOperationException()); private ISymUnmanagedWriter8 GetSymWriter8() => GetSymWriter() is ISymUnmanagedWriter8 symWriter8 ? symWriter8 : throw PdbWritingException(new NotSupportedException()); private Exception PdbWritingException(Exception inner) => new SymUnmanagedWriterException(inner, _symWriterModuleName); /// <summary> /// Writes the content to the given stream. The writer is disposed and can't be used for further writing. /// </summary> public override void WriteTo(Stream stream) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } // SymWriter flushes data to the native stream on close. // Closing the writer also ensures no further modifications. CloseSymWriter(); try { _pdbStream.CopyTo(stream); } catch (Exception ex) { throw PdbWritingException(ex); // TODO } } public override void Dispose() { DisposeImpl(); GC.SuppressFinalize(this); } ~SymUnmanagedWriterImpl() { DisposeImpl(); } private void DisposeImpl() { try { CloseSymWriter(); } catch { // Dispose shall not throw } _disposed = true; } private void CloseSymWriter() { var symWriter = Interlocked.Exchange(ref _symWriter, null); if (symWriter == null) { return; } try { symWriter.Close(); } catch (Exception ex) { throw PdbWritingException(ex); } finally { // We leave releasing SymWriter and document writer COM objects the to GC -- // we write to an in-memory stream hence no files are being locked. // We need to keep these alive until the symWriter is closed because the // symWriter seems to have a un-ref-counted reference to them. _documentWriters.Clear(); } } public override IEnumerable<ArraySegment<byte>> GetUnderlyingData() { // Commit, so that all data are flushed to the underlying stream. GetSymWriter().Commit(); return _pdbStream.GetChunks(); } public override int DocumentTableCapacity { get => _documentWriters.Capacity; set { if (value > _documentWriters.Count) { _documentWriters.Capacity = value; } } } public override int DefineDocument(string name, Guid language, Guid vendor, Guid type, Guid algorithmId, ReadOnlySpan<byte> checksum, ReadOnlySpan<byte> source) { if (name == null) { throw new ArgumentNullException(nameof(name)); } var symWriter = GetSymWriter(); int index = _documentWriters.Count; ISymUnmanagedDocumentWriter documentWriter; try { documentWriter = symWriter.DefineDocument(name, ref language, ref vendor, ref type); } catch (Exception ex) { throw PdbWritingException(ex); } _documentWriters.Add(documentWriter); if (algorithmId != default(Guid) && checksum.Length > 0) { try { unsafe { fixed (byte* bytes = checksum) { documentWriter.SetCheckSum(algorithmId, (uint)checksum.Length, bytes); } } } catch (Exception ex) { throw PdbWritingException(ex); } } if (source != null) { try { unsafe { fixed (byte* bytes = source) { documentWriter.SetSource((uint)source.Length, bytes); } } } catch (Exception ex) { throw PdbWritingException(ex); } } return index; } public override void DefineSequencePoints(int documentIndex, int count, int[] offsets, int[] startLines, int[] startColumns, int[] endLines, int[] endColumns) { if (documentIndex < 0 || documentIndex >= _documentWriters.Count) { throw new ArgumentOutOfRangeException(nameof(documentIndex)); } if (offsets == null) throw new ArgumentNullException(nameof(offsets)); if (startLines == null) throw new ArgumentNullException(nameof(startLines)); if (startColumns == null) throw new ArgumentNullException(nameof(startColumns)); if (endLines == null) throw new ArgumentNullException(nameof(endLines)); if (endColumns == null) throw new ArgumentNullException(nameof(endColumns)); if (count < 0 || count > startLines.Length || count > startColumns.Length || count > endLines.Length || count > endColumns.Length) { throw new ArgumentOutOfRangeException(nameof(count)); } var symWriter = GetSymWriter(); try { symWriter.DefineSequencePoints( _documentWriters[documentIndex], count, offsets, startLines, startColumns, endLines, endColumns); } catch (Exception ex) { throw PdbWritingException(ex); } } public override void OpenMethod(int methodToken) { var symWriter = GetSymWriter(); try { symWriter.OpenMethod(unchecked((uint)methodToken)); } catch (Exception ex) { throw PdbWritingException(ex); } } public override void CloseMethod() { var symWriter = GetSymWriter(); try { symWriter.CloseMethod(); } catch (Exception ex) { throw PdbWritingException(ex); } } public override void OpenScope(int startOffset) { var symWriter = GetSymWriter(); try { symWriter.OpenScope(startOffset); } catch (Exception ex) { throw PdbWritingException(ex); } } public override void CloseScope(int endOffset) { var symWriter = GetSymWriter(); try { symWriter.CloseScope(endOffset); } catch (Exception ex) { throw PdbWritingException(ex); } } public override void DefineLocalVariable(int index, string name, int attributes, int localSignatureToken) { var symWriter = GetSymWriter(); try { const uint ADDR_IL_OFFSET = 1; symWriter.DefineLocalVariable2(name, attributes, localSignatureToken, ADDR_IL_OFFSET, index, 0, 0, 0, 0); } catch (Exception ex) { throw PdbWritingException(ex); } } public override bool DefineLocalConstant(string name, object value, int constantSignatureToken) { var symWriter = GetSymWriter(); switch (value) { case string str: return DefineLocalStringConstant(symWriter, name, str, constantSignatureToken); case DateTime dateTime: // Note: Do not use DefineConstant as it doesn't set the local signature token, which is required in order to avoid callbacks to IMetadataEmit. // Marshal.GetNativeVariantForObject would create a variant with type VT_DATE and value equal to the // number of days since 1899/12/30. However, ConstantValue::VariantFromConstant in the native VB // compiler actually created a variant with type VT_DATE and value equal to the tick count. // http://blogs.msdn.com/b/ericlippert/archive/2003/09/16/eric-s-complete-guide-to-vt-date.aspx try { symWriter.DefineConstant2(name, new VariantStructure(dateTime), constantSignatureToken); } catch (Exception ex) { throw PdbWritingException(ex); } return true; default: try { // ISymUnmanagedWriter2.DefineConstant2 throws an ArgumentException // if you pass in null - Dev10 appears to use 0 instead. // (See EMITTER::VariantFromConstVal) DefineLocalConstantImpl(symWriter, name, value ?? s_zeroInt32, constantSignatureToken); } catch (Exception ex) { throw PdbWritingException(ex); } return true; } } private unsafe void DefineLocalConstantImpl(ISymUnmanagedWriter5 symWriter, string name, object value, int constantSignatureToken) { VariantStructure variant = new VariantStructure(); #pragma warning disable CS0618 // Type or member is obsolete Marshal.GetNativeVariantForObject(value, new IntPtr(&variant)); #pragma warning restore CS0618 // Type or member is obsolete symWriter.DefineConstant2(name, variant, constantSignatureToken); } private bool DefineLocalStringConstant(ISymUnmanagedWriter5 symWriter, string name, string value, int constantSignatureToken) { Debug.Assert(value != null); int encodedLength; // ISymUnmanagedWriter2 doesn't handle unicode strings with unmatched unicode surrogates. // We use the .NET UTF8 encoder to replace unmatched unicode surrogates with unicode replacement character. if (!IsValidUnicodeString(value)) { byte[] bytes = Encoding.UTF8.GetBytes(value); encodedLength = bytes.Length; value = Encoding.UTF8.GetString(bytes, 0, bytes.Length); } else { encodedLength = Encoding.UTF8.GetByteCount(value); } // +1 for terminating NUL character encodedLength++; // If defining a string constant and it is too long (length limit is not documented by the API), DefineConstant2 throws an ArgumentException. // However, diasymreader doesn't calculate the length correctly in presence of NUL characters in the string. // Until that's fixed we need to check the limit ourselves. See http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/178988 if (encodedLength > 2032) { return false; } try { DefineLocalConstantImpl(symWriter, name, value, constantSignatureToken); } catch (ArgumentException) { // writing the constant value into the PDB failed because the string value was most probably too long. // We will report a warning for this issue and continue writing the PDB. // The effect on the debug experience is that the symbol for the constant will not be shown in the local // window of the debugger. Nor will the user be able to bind to it in expressions in the EE. //The triage team has deemed this new warning undesirable. The effects are not significant. The warning //is showing up in the DevDiv build more often than expected. We never warned on it before and nobody cared. //The proposed warning is not actionable with no source location. return false; } catch (Exception ex) { throw PdbWritingException(ex); } return true; } private static bool IsValidUnicodeString(string str) { int i = 0; while (i < str.Length) { char c = str[i++]; // (high surrogate, low surrogate) makes a valid pair, anything else is invalid: if (char.IsHighSurrogate(c)) { if (i < str.Length && char.IsLowSurrogate(str[i])) { i++; } else { // high surrogate not followed by low surrogate return false; } } else if (char.IsLowSurrogate(c)) { // previous character wasn't a high surrogate return false; } } return true; } public override void UsingNamespace(string importString) { if (importString == null) { throw new ArgumentNullException(nameof(importString)); } var symWriter = GetSymWriter(); try { symWriter.UsingNamespace(importString); } catch (Exception ex) { throw PdbWritingException(ex); } } public override void SetAsyncInfo( int moveNextMethodToken, int kickoffMethodToken, int catchHandlerOffset, ReadOnlySpan<int> yieldOffsets, ReadOnlySpan<int> resumeOffsets) { if (yieldOffsets == null) throw new ArgumentNullException(nameof(yieldOffsets)); if (resumeOffsets == null) throw new ArgumentNullException(nameof(resumeOffsets)); if (yieldOffsets.Length != resumeOffsets.Length) { throw new ArgumentOutOfRangeException(nameof(yieldOffsets)); } if (GetSymWriter() is ISymUnmanagedAsyncMethodPropertiesWriter asyncMethodPropertyWriter) { int count = yieldOffsets.Length; if (count > 0) { var methods = new int[count]; for (int i = 0; i < count; i++) { methods[i] = moveNextMethodToken; } try { unsafe { fixed (int* yieldPtr = yieldOffsets) fixed (int* resumePtr = resumeOffsets) fixed (int* methodsPtr = methods) { asyncMethodPropertyWriter.DefineAsyncStepInfo(count, yieldPtr, resumePtr, methodsPtr); } } } catch (Exception ex) { throw PdbWritingException(ex); } } try { if (catchHandlerOffset >= 0) { asyncMethodPropertyWriter.DefineCatchHandlerILOffset(catchHandlerOffset); } asyncMethodPropertyWriter.DefineKickoffMethod(kickoffMethodToken); } catch (Exception ex) { throw PdbWritingException(ex); } } } public override unsafe void DefineCustomMetadata(byte[] metadata) { if (metadata == null) { throw new ArgumentNullException(nameof(metadata)); } if (metadata.Length == 0) { return; } var symWriter = GetSymWriter(); try { fixed (byte* pb = metadata) { // parent parameter is not used, it must be zero or the current method token passed to OpenMethod. symWriter.SetSymAttribute(0, "MD2", metadata.Length, pb); } } catch (Exception ex) { throw PdbWritingException(ex); } } public override void SetEntryPoint(int entryMethodToken) { var symWriter = GetSymWriter(); try { symWriter.SetUserEntryPoint(entryMethodToken); } catch (Exception ex) { throw PdbWritingException(ex); } } public override void UpdateSignature(Guid guid, uint stamp, int age) { var symWriter = GetSymWriter8(); try { symWriter.UpdateSignature(guid, stamp, age); } catch (Exception ex) { throw PdbWritingException(ex); } } public override unsafe void SetSourceServerData(byte[] data) { if (data == null) { throw new ArgumentNullException(nameof(data)); } if (data.Length == 0) { return; } var symWriter = GetSymWriter8(); try { fixed (byte* dataPtr = data) { symWriter.SetSourceServerData(dataPtr, data.Length); } } catch (Exception ex) { throw PdbWritingException(ex); } } public override unsafe void SetSourceLinkData(byte[] data) { if (data == null) { throw new ArgumentNullException(nameof(data)); } if (data.Length == 0) { return; } var symWriter = GetSymWriter8(); try { fixed (byte* dataPtr = data) { symWriter.SetSourceLinkData(dataPtr, data.Length); } } catch (Exception ex) { throw PdbWritingException(ex); } } public override void OpenTokensToSourceSpansMap() { var symWriter = GetSymWriter(); try { symWriter.OpenMapTokensToSourceSpans(); } catch (Exception ex) { throw PdbWritingException(ex); } } public override void MapTokenToSourceSpan(int token, int documentIndex, int startLine, int startColumn, int endLine, int endColumn) { if (documentIndex < 0 || documentIndex >= _documentWriters.Count) { throw new ArgumentOutOfRangeException(nameof(documentIndex)); } var symWriter = GetSymWriter(); try { symWriter.MapTokenToSourceSpan( token, _documentWriters[documentIndex], startLine, startColumn, endLine, endColumn); } catch (Exception ex) { throw PdbWritingException(ex); } } public override void CloseTokensToSourceSpansMap() { var symWriter = GetSymWriter(); try { symWriter.CloseMapTokensToSourceSpans(); } catch (Exception ex) { throw PdbWritingException(ex); } } public override unsafe void GetSignature(out Guid guid, out uint stamp, out int age) { var symWriter = GetSymWriter(); // See symwrite.cpp - the data byte[] doesn't depend on the content of metadata tables or IL. // The writer only sets two values of the ImageDebugDirectory struct. // // IMAGE_DEBUG_DIRECTORY *pIDD // // if ( pIDD == NULL ) return E_INVALIDARG; // memset( pIDD, 0, sizeof( *pIDD ) ); // pIDD->Type = IMAGE_DEBUG_TYPE_CODEVIEW; // pIDD->SizeOfData = cTheData; var debugDir = new ImageDebugDirectory(); uint dataLength; try { symWriter.GetDebugInfo(ref debugDir, 0, out dataLength, null); } catch (Exception ex) { throw PdbWritingException(ex); } byte[] data = new byte[dataLength]; fixed (byte* pb = data) { try { symWriter.GetDebugInfo(ref debugDir, dataLength, out dataLength, pb); } catch (Exception ex) { throw PdbWritingException(ex); } } // Data has the following structure: // struct RSDSI // { // DWORD dwSig; // "RSDS" // GUID guidSig; // GUID // DWORD age; // age // char szPDB[0]; // zero-terminated UTF8 file name passed to the writer // }; const int GuidSize = 16; var guidBytes = new byte[GuidSize]; Buffer.BlockCopy(data, 4, guidBytes, 0, guidBytes.Length); guid = new Guid(guidBytes); // Retrieve the timestamp the PDB writer generates when creating a new PDB stream. // Note that ImageDebugDirectory.TimeDateStamp is not set by GetDebugInfo, // we need to go through IPdbWriter interface to get it. ((IPdbWriter)symWriter).GetSignatureAge(out stamp, out age); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace Microsoft.DiaSymReader { internal sealed class SymUnmanagedWriterImpl : SymUnmanagedWriter { private static readonly object s_zeroInt32 = 0; private ISymUnmanagedWriter5 _symWriter; private readonly ComMemoryStream _pdbStream; private readonly List<ISymUnmanagedDocumentWriter> _documentWriters; private readonly string _symWriterModuleName; private bool _disposed; internal SymUnmanagedWriterImpl(ComMemoryStream pdbStream, ISymUnmanagedWriter5 symWriter, string symWriterModuleName) { Debug.Assert(pdbStream != null); Debug.Assert(symWriter != null); Debug.Assert(symWriterModuleName != null); _pdbStream = pdbStream; _symWriter = symWriter; _documentWriters = new List<ISymUnmanagedDocumentWriter>(); _symWriterModuleName = symWriterModuleName; } private ISymUnmanagedWriter5 GetSymWriter() => _symWriter ?? throw (_disposed ? new ObjectDisposedException(nameof(SymUnmanagedWriterImpl)) : new InvalidOperationException()); private ISymUnmanagedWriter8 GetSymWriter8() => GetSymWriter() is ISymUnmanagedWriter8 symWriter8 ? symWriter8 : throw PdbWritingException(new NotSupportedException()); private Exception PdbWritingException(Exception inner) => new SymUnmanagedWriterException(inner, _symWriterModuleName); /// <summary> /// Writes the content to the given stream. The writer is disposed and can't be used for further writing. /// </summary> public override void WriteTo(Stream stream) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } // SymWriter flushes data to the native stream on close. // Closing the writer also ensures no further modifications. CloseSymWriter(); try { _pdbStream.CopyTo(stream); } catch (Exception ex) { throw PdbWritingException(ex); // TODO } } public override void Dispose() { DisposeImpl(); GC.SuppressFinalize(this); } ~SymUnmanagedWriterImpl() { DisposeImpl(); } private void DisposeImpl() { try { CloseSymWriter(); } catch { // Dispose shall not throw } _disposed = true; } private void CloseSymWriter() { var symWriter = Interlocked.Exchange(ref _symWriter, null); if (symWriter == null) { return; } try { symWriter.Close(); } catch (Exception ex) { throw PdbWritingException(ex); } finally { // We leave releasing SymWriter and document writer COM objects the to GC -- // we write to an in-memory stream hence no files are being locked. // We need to keep these alive until the symWriter is closed because the // symWriter seems to have a un-ref-counted reference to them. _documentWriters.Clear(); } } public override IEnumerable<ArraySegment<byte>> GetUnderlyingData() { // Commit, so that all data are flushed to the underlying stream. GetSymWriter().Commit(); return _pdbStream.GetChunks(); } public override int DocumentTableCapacity { get => _documentWriters.Capacity; set { if (value > _documentWriters.Count) { _documentWriters.Capacity = value; } } } public override int DefineDocument(string name, Guid language, Guid vendor, Guid type, Guid algorithmId, ReadOnlySpan<byte> checksum, ReadOnlySpan<byte> source) { if (name == null) { throw new ArgumentNullException(nameof(name)); } var symWriter = GetSymWriter(); int index = _documentWriters.Count; ISymUnmanagedDocumentWriter documentWriter; try { documentWriter = symWriter.DefineDocument(name, ref language, ref vendor, ref type); } catch (Exception ex) { throw PdbWritingException(ex); } _documentWriters.Add(documentWriter); if (algorithmId != default(Guid) && checksum.Length > 0) { try { unsafe { fixed (byte* bytes = checksum) { documentWriter.SetCheckSum(algorithmId, (uint)checksum.Length, bytes); } } } catch (Exception ex) { throw PdbWritingException(ex); } } if (source != null) { try { unsafe { fixed (byte* bytes = source) { documentWriter.SetSource((uint)source.Length, bytes); } } } catch (Exception ex) { throw PdbWritingException(ex); } } return index; } public override void DefineSequencePoints(int documentIndex, int count, int[] offsets, int[] startLines, int[] startColumns, int[] endLines, int[] endColumns) { if (documentIndex < 0 || documentIndex >= _documentWriters.Count) { throw new ArgumentOutOfRangeException(nameof(documentIndex)); } if (offsets == null) throw new ArgumentNullException(nameof(offsets)); if (startLines == null) throw new ArgumentNullException(nameof(startLines)); if (startColumns == null) throw new ArgumentNullException(nameof(startColumns)); if (endLines == null) throw new ArgumentNullException(nameof(endLines)); if (endColumns == null) throw new ArgumentNullException(nameof(endColumns)); if (count < 0 || count > startLines.Length || count > startColumns.Length || count > endLines.Length || count > endColumns.Length) { throw new ArgumentOutOfRangeException(nameof(count)); } var symWriter = GetSymWriter(); try { symWriter.DefineSequencePoints( _documentWriters[documentIndex], count, offsets, startLines, startColumns, endLines, endColumns); } catch (Exception ex) { throw PdbWritingException(ex); } } public override void OpenMethod(int methodToken) { var symWriter = GetSymWriter(); try { symWriter.OpenMethod(unchecked((uint)methodToken)); } catch (Exception ex) { throw PdbWritingException(ex); } } public override void CloseMethod() { var symWriter = GetSymWriter(); try { symWriter.CloseMethod(); } catch (Exception ex) { throw PdbWritingException(ex); } } public override void OpenScope(int startOffset) { var symWriter = GetSymWriter(); try { symWriter.OpenScope(startOffset); } catch (Exception ex) { throw PdbWritingException(ex); } } public override void CloseScope(int endOffset) { var symWriter = GetSymWriter(); try { symWriter.CloseScope(endOffset); } catch (Exception ex) { throw PdbWritingException(ex); } } public override void DefineLocalVariable(int index, string name, int attributes, int localSignatureToken) { var symWriter = GetSymWriter(); try { const uint ADDR_IL_OFFSET = 1; symWriter.DefineLocalVariable2(name, attributes, localSignatureToken, ADDR_IL_OFFSET, index, 0, 0, 0, 0); } catch (Exception ex) { throw PdbWritingException(ex); } } public override bool DefineLocalConstant(string name, object value, int constantSignatureToken) { var symWriter = GetSymWriter(); switch (value) { case string str: return DefineLocalStringConstant(symWriter, name, str, constantSignatureToken); case DateTime dateTime: // Note: Do not use DefineConstant as it doesn't set the local signature token, which is required in order to avoid callbacks to IMetadataEmit. // Marshal.GetNativeVariantForObject would create a variant with type VT_DATE and value equal to the // number of days since 1899/12/30. However, ConstantValue::VariantFromConstant in the native VB // compiler actually created a variant with type VT_DATE and value equal to the tick count. // http://blogs.msdn.com/b/ericlippert/archive/2003/09/16/eric-s-complete-guide-to-vt-date.aspx try { symWriter.DefineConstant2(name, new VariantStructure(dateTime), constantSignatureToken); } catch (Exception ex) { throw PdbWritingException(ex); } return true; default: try { // ISymUnmanagedWriter2.DefineConstant2 throws an ArgumentException // if you pass in null - Dev10 appears to use 0 instead. // (See EMITTER::VariantFromConstVal) DefineLocalConstantImpl(symWriter, name, value ?? s_zeroInt32, constantSignatureToken); } catch (Exception ex) { throw PdbWritingException(ex); } return true; } } private unsafe void DefineLocalConstantImpl(ISymUnmanagedWriter5 symWriter, string name, object value, int constantSignatureToken) { VariantStructure variant = new VariantStructure(); #pragma warning disable CS0618 // Type or member is obsolete Marshal.GetNativeVariantForObject(value, new IntPtr(&variant)); #pragma warning restore CS0618 // Type or member is obsolete symWriter.DefineConstant2(name, variant, constantSignatureToken); } private bool DefineLocalStringConstant(ISymUnmanagedWriter5 symWriter, string name, string value, int constantSignatureToken) { Debug.Assert(value != null); int encodedLength; // ISymUnmanagedWriter2 doesn't handle unicode strings with unmatched unicode surrogates. // We use the .NET UTF8 encoder to replace unmatched unicode surrogates with unicode replacement character. if (!IsValidUnicodeString(value)) { byte[] bytes = Encoding.UTF8.GetBytes(value); encodedLength = bytes.Length; value = Encoding.UTF8.GetString(bytes, 0, bytes.Length); } else { encodedLength = Encoding.UTF8.GetByteCount(value); } // +1 for terminating NUL character encodedLength++; // If defining a string constant and it is too long (length limit is not documented by the API), DefineConstant2 throws an ArgumentException. // However, diasymreader doesn't calculate the length correctly in presence of NUL characters in the string. // Until that's fixed we need to check the limit ourselves. See http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/178988 if (encodedLength > 2032) { return false; } try { DefineLocalConstantImpl(symWriter, name, value, constantSignatureToken); } catch (ArgumentException) { // writing the constant value into the PDB failed because the string value was most probably too long. // We will report a warning for this issue and continue writing the PDB. // The effect on the debug experience is that the symbol for the constant will not be shown in the local // window of the debugger. Nor will the user be able to bind to it in expressions in the EE. //The triage team has deemed this new warning undesirable. The effects are not significant. The warning //is showing up in the DevDiv build more often than expected. We never warned on it before and nobody cared. //The proposed warning is not actionable with no source location. return false; } catch (Exception ex) { throw PdbWritingException(ex); } return true; } private static bool IsValidUnicodeString(string str) { int i = 0; while (i < str.Length) { char c = str[i++]; // (high surrogate, low surrogate) makes a valid pair, anything else is invalid: if (char.IsHighSurrogate(c)) { if (i < str.Length && char.IsLowSurrogate(str[i])) { i++; } else { // high surrogate not followed by low surrogate return false; } } else if (char.IsLowSurrogate(c)) { // previous character wasn't a high surrogate return false; } } return true; } public override void UsingNamespace(string importString) { if (importString == null) { throw new ArgumentNullException(nameof(importString)); } var symWriter = GetSymWriter(); try { symWriter.UsingNamespace(importString); } catch (Exception ex) { throw PdbWritingException(ex); } } public override void SetAsyncInfo( int moveNextMethodToken, int kickoffMethodToken, int catchHandlerOffset, ReadOnlySpan<int> yieldOffsets, ReadOnlySpan<int> resumeOffsets) { if (yieldOffsets == null) throw new ArgumentNullException(nameof(yieldOffsets)); if (resumeOffsets == null) throw new ArgumentNullException(nameof(resumeOffsets)); if (yieldOffsets.Length != resumeOffsets.Length) { throw new ArgumentOutOfRangeException(nameof(yieldOffsets)); } if (GetSymWriter() is ISymUnmanagedAsyncMethodPropertiesWriter asyncMethodPropertyWriter) { int count = yieldOffsets.Length; if (count > 0) { var methods = new int[count]; for (int i = 0; i < count; i++) { methods[i] = moveNextMethodToken; } try { unsafe { fixed (int* yieldPtr = yieldOffsets) fixed (int* resumePtr = resumeOffsets) fixed (int* methodsPtr = methods) { asyncMethodPropertyWriter.DefineAsyncStepInfo(count, yieldPtr, resumePtr, methodsPtr); } } } catch (Exception ex) { throw PdbWritingException(ex); } } try { if (catchHandlerOffset >= 0) { asyncMethodPropertyWriter.DefineCatchHandlerILOffset(catchHandlerOffset); } asyncMethodPropertyWriter.DefineKickoffMethod(kickoffMethodToken); } catch (Exception ex) { throw PdbWritingException(ex); } } } public override unsafe void DefineCustomMetadata(byte[] metadata) { if (metadata == null) { throw new ArgumentNullException(nameof(metadata)); } if (metadata.Length == 0) { return; } var symWriter = GetSymWriter(); try { fixed (byte* pb = metadata) { // parent parameter is not used, it must be zero or the current method token passed to OpenMethod. symWriter.SetSymAttribute(0, "MD2", metadata.Length, pb); } } catch (Exception ex) { throw PdbWritingException(ex); } } public override void SetEntryPoint(int entryMethodToken) { var symWriter = GetSymWriter(); try { symWriter.SetUserEntryPoint(entryMethodToken); } catch (Exception ex) { throw PdbWritingException(ex); } } public override void UpdateSignature(Guid guid, uint stamp, int age) { var symWriter = GetSymWriter8(); try { symWriter.UpdateSignature(guid, stamp, age); } catch (Exception ex) { throw PdbWritingException(ex); } } public override unsafe void SetSourceServerData(byte[] data) { if (data == null) { throw new ArgumentNullException(nameof(data)); } if (data.Length == 0) { return; } var symWriter = GetSymWriter8(); try { fixed (byte* dataPtr = data) { symWriter.SetSourceServerData(dataPtr, data.Length); } } catch (Exception ex) { throw PdbWritingException(ex); } } public override unsafe void SetSourceLinkData(byte[] data) { if (data == null) { throw new ArgumentNullException(nameof(data)); } if (data.Length == 0) { return; } var symWriter = GetSymWriter8(); try { fixed (byte* dataPtr = data) { symWriter.SetSourceLinkData(dataPtr, data.Length); } } catch (Exception ex) { throw PdbWritingException(ex); } } public override void OpenTokensToSourceSpansMap() { var symWriter = GetSymWriter(); try { symWriter.OpenMapTokensToSourceSpans(); } catch (Exception ex) { throw PdbWritingException(ex); } } public override void MapTokenToSourceSpan(int token, int documentIndex, int startLine, int startColumn, int endLine, int endColumn) { if (documentIndex < 0 || documentIndex >= _documentWriters.Count) { throw new ArgumentOutOfRangeException(nameof(documentIndex)); } var symWriter = GetSymWriter(); try { symWriter.MapTokenToSourceSpan( token, _documentWriters[documentIndex], startLine, startColumn, endLine, endColumn); } catch (Exception ex) { throw PdbWritingException(ex); } } public override void CloseTokensToSourceSpansMap() { var symWriter = GetSymWriter(); try { symWriter.CloseMapTokensToSourceSpans(); } catch (Exception ex) { throw PdbWritingException(ex); } } public override unsafe void GetSignature(out Guid guid, out uint stamp, out int age) { var symWriter = GetSymWriter(); // See symwrite.cpp - the data byte[] doesn't depend on the content of metadata tables or IL. // The writer only sets two values of the ImageDebugDirectory struct. // // IMAGE_DEBUG_DIRECTORY *pIDD // // if ( pIDD == NULL ) return E_INVALIDARG; // memset( pIDD, 0, sizeof( *pIDD ) ); // pIDD->Type = IMAGE_DEBUG_TYPE_CODEVIEW; // pIDD->SizeOfData = cTheData; var debugDir = new ImageDebugDirectory(); uint dataLength; try { symWriter.GetDebugInfo(ref debugDir, 0, out dataLength, null); } catch (Exception ex) { throw PdbWritingException(ex); } byte[] data = new byte[dataLength]; fixed (byte* pb = data) { try { symWriter.GetDebugInfo(ref debugDir, dataLength, out dataLength, pb); } catch (Exception ex) { throw PdbWritingException(ex); } } // Data has the following structure: // struct RSDSI // { // DWORD dwSig; // "RSDS" // GUID guidSig; // GUID // DWORD age; // age // char szPDB[0]; // zero-terminated UTF8 file name passed to the writer // }; const int GuidSize = 16; var guidBytes = new byte[GuidSize]; Buffer.BlockCopy(data, 4, guidBytes, 0, guidBytes.Length); guid = new Guid(guidBytes); // Retrieve the timestamp the PDB writer generates when creating a new PDB stream. // Note that ImageDebugDirectory.TimeDateStamp is not set by GetDebugInfo, // we need to go through IPdbWriter interface to get it. ((IPdbWriter)symWriter).GetSignatureAge(out stamp, out age); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.pt-BR.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="pt-BR" original="../CSharpVSResources.resx"> <body> <trans-unit id="Add_missing_using_directives_on_paste"> <source>Add missing using directives on paste</source> <target state="translated">Adicionar as diretivas using ausentes ao colar</target> <note>'using' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Allow_bank_line_after_colon_in_constructor_initializer"> <source>Allow blank line after colon in constructor initializer</source> <target state="translated">Permitir uma linha em branco após os dois-pontos no inicializador do construtor</target> <note /> </trans-unit> <trans-unit id="Allow_blank_lines_between_consecutive_braces"> <source>Allow blank lines between consecutive braces</source> <target state="translated">Permitir linhas em branco entre chaves consecutivas</target> <note /> </trans-unit> <trans-unit id="Allow_embedded_statements_on_same_line"> <source>Allow embedded statements on same line</source> <target state="translated">Permitir instruções inseridas na mesma linha</target> <note /> </trans-unit> <trans-unit id="Apply_all_csharp_formatting_rules_indentation_wrapping_spacing"> <source>Apply all C# formatting rules (indentation, wrapping, spacing)</source> <target state="translated">Aplicar todas as regras de formatação de C# (recuo, quebra de linha, espaçamento)</target> <note /> </trans-unit> <trans-unit id="Automatically_complete_statement_on_semicolon"> <source>Automatically complete statement on semicolon</source> <target state="translated">Concluir a instrução automaticamente no ponto e vírgula</target> <note /> </trans-unit> <trans-unit id="Automatically_show_completion_list_in_argument_lists"> <source>Automatically show completion list in argument lists</source> <target state="translated">Mostrar automaticamente a lista de conclusão nas listas de argumentos</target> <note /> </trans-unit> <trans-unit id="Block_scoped"> <source>Block scoped</source> <target state="new">Block scoped</target> <note /> </trans-unit> <trans-unit id="CSharp"> <source>C#</source> <target state="translated">C#</target> <note /> </trans-unit> <trans-unit id="CSharp_Coding_Conventions"> <source>C# Coding Conventions</source> <target state="translated">Convenções de Codificação em C#</target> <note /> </trans-unit> <trans-unit id="CSharp_Formatting_Rules"> <source>C# Formatting Rules</source> <target state="translated">Regras de Formatação de C#</target> <note /> </trans-unit> <trans-unit id="Completion"> <source>Completion</source> <target state="translated">Conclusão</target> <note /> </trans-unit> <trans-unit id="Discard"> <source>Discard</source> <target state="translated">Descartar</target> <note /> </trans-unit> <trans-unit id="Edit_color_scheme"> <source>Edit color scheme</source> <target state="translated">Editar o esquema de cores</target> <note /> </trans-unit> <trans-unit id="File_scoped"> <source>File scoped</source> <target state="new">File scoped</target> <note /> </trans-unit> <trans-unit id="Format_document_settings"> <source>Format Document Settings (Experiment) </source> <target state="translated">Formatar Configurações do Documento (Experimento)</target> <note /> </trans-unit> <trans-unit id="General"> <source>General</source> <target state="translated">Geral</target> <note>Title of the control group on the General Formatting options page</note> </trans-unit> <trans-unit id="In_relational_binary_operators"> <source>In relational operators: &lt; &gt; &lt;= &gt;= is as == !=</source> <target state="translated">Em operadores relacionais: &lt; &gt; &lt;= &gt;= is as == !=</target> <note>'is' and 'as' are C# keywords and should not be localized</note> </trans-unit> <trans-unit id="Insert_slash_slash_at_the_start_of_new_lines_when_writing_slash_slash_comments"> <source>Insert // at the start of new lines when writing // comments</source> <target state="translated">Inserir // no início de novas linhas ao escrever comentários de //</target> <note /> </trans-unit> <trans-unit id="Inside_namespace"> <source>Inside namespace</source> <target state="translated">Namespace interno</target> <note>'namespace' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Outside_namespace"> <source>Outside namespace</source> <target state="translated">Namespace externo</target> <note>'namespace' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Pattern_matching_preferences_colon"> <source>Pattern matching preferences:</source> <target state="translated">Preferências de correspondência de padrões:</target> <note /> </trans-unit> <trans-unit id="Perform_additional_code_cleanup_during_formatting"> <source>Perform additional code cleanup during formatting</source> <target state="translated">Executar limpeza de código adicional durante a formatação</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_object_collection_array_and_with_initializers"> <source>Place open brace on new line for object, collection, array, and with initializers</source> <target state="translated">Colocar uma chave de abertura em uma nova linha para inicializadores de objeto, coleção, matriz e with</target> <note>{Locked="with"}</note> </trans-unit> <trans-unit id="Prefer_implicit_object_creation_when_type_is_apparent"> <source>Prefer implicit object creation when type is apparent</source> <target state="translated">Preferir a criação de objeto implícito quando o tipo for aparente</target> <note /> </trans-unit> <trans-unit id="Prefer_is_null_for_reference_equality_checks"> <source>Prefer 'is null' for reference equality checks</source> <target state="translated">Preferir 'is null' para as verificações de igualdade de referência</target> <note>'is null' is a C# string and should not be localized.</note> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching"> <source>Prefer pattern matching</source> <target state="translated">Preferir a correspondência de padrões</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_mixed_type_check"> <source>Prefer pattern matching over mixed type check</source> <target state="translated">Preferir a correspondência de padrões em vez da verificação de tipo misto</target> <note /> </trans-unit> <trans-unit id="Prefer_switch_expression"> <source>Prefer switch expression</source> <target state="translated">Preferir a expressão switch</target> <note /> </trans-unit> <trans-unit id="Preferred_using_directive_placement"> <source>Preferred 'using' directive placement</source> <target state="translated">Posicionamento da diretiva 'using' preferencial</target> <note>'using' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Remove_unnecessary_usings"> <source>Remove unnecessary usings</source> <target state="translated">Remover Usos Desnecessários</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_new_expressions"> <source>Show hints for 'new' expressions</source> <target state="translated">Mostrar as dicas para as expressões 'new'</target> <note /> </trans-unit> <trans-unit id="Show_items_from_unimported_namespaces"> <source>Show items from unimported namespaces</source> <target state="translated">Mostrar os itens de namespaces não importados</target> <note /> </trans-unit> <trans-unit id="Show_remarks_in_Quick_Info"> <source>Show remarks in Quick Info</source> <target state="translated">Mostrar os comentários nas Informações Rápidas</target> <note /> </trans-unit> <trans-unit id="Sort_usings"> <source>Sort usings</source> <target state="translated">Classificar usos</target> <note /> </trans-unit> <trans-unit id="Suggest_usings_for_types_in_dotnet_framework_assemblies"> <source>Suggest usings for types in .NET Framework assemblies</source> <target state="translated">Sugerir usings para tipos nos assemblies do .NET Framework</target> <note /> </trans-unit> <trans-unit id="Surround_With"> <source>Surround With</source> <target state="translated">Envolver com</target> <note /> </trans-unit> <trans-unit id="Insert_Snippet"> <source>Insert Snippet</source> <target state="translated">Inserir Snippet</target> <note /> </trans-unit> <trans-unit id="Automatically_format_block_on_close_brace"> <source>Automatically format _block on }</source> <target state="translated">Formatar automaticamente _bloco em }</target> <note /> </trans-unit> <trans-unit id="Automatically_format_on_paste"> <source>Automatically format on _paste</source> <target state="translated">Formatar automaticamente após _colar</target> <note /> </trans-unit> <trans-unit id="Automatically_format_statement_on_semicolon"> <source>Automatically format _statement on ;</source> <target state="translated">Formatar automaticamente _instrução em;</target> <note /> </trans-unit> <trans-unit id="Place_members_in_anonymous_types_on_new_line"> <source>Place members in anonymous types on new line</source> <target state="translated">Colocar membros em tipos anônimos em nova linha</target> <note /> </trans-unit> <trans-unit id="Leave_block_on_single_line"> <source>Leave block on single line</source> <target state="translated">Deixar bloco em uma linha única</target> <note /> </trans-unit> <trans-unit id="Place_catch_on_new_line"> <source>Place "catch" on new line</source> <target state="translated">Colocar "catch" em nova linha</target> <note /> </trans-unit> <trans-unit id="Place_else_on_new_line"> <source>Place "else" on new line</source> <target state="translated">Colocar "else" em nova linha</target> <note /> </trans-unit> <trans-unit id="Indent_block_contents"> <source>Indent block contents</source> <target state="translated">Recuar conteúdo do bloco</target> <note /> </trans-unit> <trans-unit id="Indent_open_and_close_braces"> <source>Indent open and close braces</source> <target state="translated">Recuar chaves de abertura e fechamento</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents"> <source>Indent case contents</source> <target state="translated">Recuar conteúdo de case</target> <note /> </trans-unit> <trans-unit id="Indent_case_labels"> <source>Indent case labels</source> <target state="translated">Recuar rótulos case</target> <note /> </trans-unit> <trans-unit id="Place_finally_on_new_line"> <source>Place "finally" on new line</source> <target state="translated">Colocar "finally" em nova linha</target> <note /> </trans-unit> <trans-unit id="Place_goto_labels_in_leftmost_column"> <source>Place goto labels in leftmost column</source> <target state="translated">Posicionar rótulos goto na coluna mais à esquerda</target> <note /> </trans-unit> <trans-unit id="Indent_labels_normally"> <source>Indent labels normally</source> <target state="translated">Recuar rótulos normalmente</target> <note /> </trans-unit> <trans-unit id="Place_goto_labels_one_indent_less_than_current"> <source>Place goto labels one indent less than current</source> <target state="translated">Colocar rótulos goto um recuo a menos do que o atual</target> <note /> </trans-unit> <trans-unit id="Label_Indentation"> <source>Label Indentation</source> <target state="translated">Recuo do Rótulo</target> <note /> </trans-unit> <trans-unit id="Place_members_in_object_initializers_on_new_line"> <source>Place members in object initializers on new line</source> <target state="translated">Colocar membros em inicializadores de objetos em nova linha</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_methods"> <source>Place open brace on new line for anonymous methods</source> <target state="translated">Colocar chave de abertura em nova linha para métodos anônimos</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_types"> <source>Place open brace on new line for anonymous types</source> <target state="translated">Colocar chave de abertura em nova linha para tipos anônimos</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_control_blocks"> <source>Place open brace on new line for control blocks</source> <target state="translated">Colocar chave de abertura em nova linha para blocos de controle</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_lambda_expression"> <source>Place open brace on new line for lambda expression</source> <target state="translated">Colocar chave de abertura em nova linha para expressão lambda</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_methods_local_functions"> <source>Place open brace on new line for methods and local functions</source> <target state="translated">Colocar chave de abertura na nova linha para métodos e funções locais</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_types"> <source>Place open brace on new line for types</source> <target state="translated">Colocar chave de abertura em nova linha para tipos</target> <note /> </trans-unit> <trans-unit id="Place_query_expression_clauses_on_new_line"> <source>Place query expression clauses on new line</source> <target state="translated">Colocar cláusulas de expressão de consulta na nova linha</target> <note /> </trans-unit> <trans-unit id="Leave_statements_and_member_declarations_on_the_same_line"> <source>Leave statements and member declarations on the same line</source> <target state="translated">Deixar instruções e declarações de membros na mesma linha</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_and_after_binary_operators"> <source>Insert space before and after binary operators</source> <target state="translated">Inserir espaço antes e depois de operadores binários</target> <note /> </trans-unit> <trans-unit id="Ignore_spaces_around_binary_operators"> <source>Ignore spaces around binary operators</source> <target state="translated">Ignorar espaços em torno de operadores binários</target> <note /> </trans-unit> <trans-unit id="Remove_spaces_before_and_after_binary_operators"> <source>Remove spaces before and after binary operators</source> <target state="translated">Remover espaços antes e depois de operadores binários</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_colon_for_base_or_interface_in_type_declaration"> <source>Insert space after colon for base or interface in type declaration</source> <target state="translated">Inserir espaço após dois-pontos para base ou interface na declaração de tipo</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_comma"> <source>Insert space after comma</source> <target state="translated">Inserir espaço após vírgula</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_dot"> <source>Insert space after dot</source> <target state="translated">Inserir espaço após ponto</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_semicolon_in_for_statement"> <source>Insert space after semicolon in "for" statement</source> <target state="translated">Inserir espaço após ponto e vírgula em instruções "for"</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_colon_for_base_or_interface_in_type_declaration"> <source>Insert space before colon for base or interface in type declaration</source> <target state="translated">Inserir espaço antes de dois-pontos para base ou interface na declaração de tipo</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_comma"> <source>Insert space before comma</source> <target state="translated">Inserir espaço antes da vírgula</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_dot"> <source>Insert space before dot</source> <target state="translated">Inserir espaço antes do ponto</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_semicolon_in_for_statement"> <source>Insert space before semicolon in "for" statement</source> <target state="translated">Inserir espaço antes de ponto e vírgula em instruções "for"</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_argument_list_parentheses"> <source>Insert space within argument list parentheses</source> <target state="translated">Inserir espaço dentro dos parênteses da lista de argumentos</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_argument_list_parentheses"> <source>Insert space within empty argument list parentheses</source> <target state="translated">Inserir espaço dentro dos parênteses da lista de argumentos vazia</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis1"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">Inserir espaço entre o nome do método e o parêntese inicial</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_parameter_list_parentheses"> <source>Insert space within empty parameter list parentheses</source> <target state="translated">Inserir espaço no parênteses da lista de parâmetros vazia</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis2"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">Inserir espaço entre o nome do método e o parêntese inicial</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parameter_list_parentheses"> <source>Insert space within parameter list parentheses</source> <target state="translated">Inserir espaço dentro dos parênteses da lista de parâmetros</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_keywords_in_control_flow_statements"> <source>Insert space after keywords in control flow statements</source> <target state="translated">Inserir espaço após palavras-chave em instruções de fluxo de controle</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_expressions"> <source>Insert space within parentheses of expressions</source> <target state="translated">Inserir espaços dentro dos parênteses das expressões</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_cast"> <source>Insert space after cast</source> <target state="translated">Inserir espaço após conversão</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_parentheses_of_control_flow_statements"> <source>Insert spaces within parentheses of control flow statements</source> <target state="translated">Inserir espaços dentro dos parênteses das instruções de fluxo de controle</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_type_casts"> <source>Insert space within parentheses of type casts</source> <target state="translated">Inserir espaço dentro dos parênteses das conversões de tipo</target> <note /> </trans-unit> <trans-unit id="Ignore_spaces_in_declaration_statements"> <source>Ignore spaces in declaration statements</source> <target state="translated">Ignorar espaços em instruções de declaração</target> <note /> </trans-unit> <trans-unit id="Set_other_spacing_options"> <source>Set other spacing options</source> <target state="translated">Definir outras opções de espaçamento</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_brackets"> <source>Set spacing for brackets</source> <target state="translated">Definir espaçamento para colchetes</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_delimiters"> <source>Set spacing for delimiters</source> <target state="translated">Definir espaçamento para delimitadores</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_method_calls"> <source>Set spacing for method calls</source> <target state="translated">Definir espaçamento para chamadas de método</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_method_declarations"> <source>Set spacing for method declarations</source> <target state="translated">Definir espaçamento para declarações de método</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_operators"> <source>Set spacing for operators</source> <target state="translated">Definir espaçamento para operadores</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_square_brackets"> <source>Insert spaces within square brackets</source> <target state="translated">Inserir espaços dentro de colchetes</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_open_square_bracket"> <source>Insert space before open square bracket</source> <target state="translated">Inserir espaço antes do colchete de abertura</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_square_brackets"> <source>Insert space within empty square brackets</source> <target state="translated">Inserir espaço dentro de colchetes vazios</target> <note /> </trans-unit> <trans-unit id="New_line_options_for_braces"> <source>New line options for braces</source> <target state="translated">Novas opções de linha para chaves</target> <note /> </trans-unit> <trans-unit id="New_line_options_for_expressions"> <source>New line options for expressions</source> <target state="translated">Novas opções de linha para expressões</target> <note /> </trans-unit> <trans-unit id="New_line_options_for_keywords"> <source>New line options for keywords</source> <target state="translated">Novas opções de linha para palavras-chaves</target> <note /> </trans-unit> <trans-unit id="Unused_local"> <source>Unused local</source> <target state="translated">Local não usado</target> <note /> </trans-unit> <trans-unit id="Use_var_when_generating_locals"> <source>Use 'var' when generating locals</source> <target state="translated">Usar "var" ao gerar locais</target> <note /> </trans-unit> <trans-unit id="Show_procedure_line_separators"> <source>_Show procedure line separators</source> <target state="translated">_Mostrar separadores de linha de procedimento</target> <note /> </trans-unit> <trans-unit id="Don_t_put_ref_or_out_on_custom_struct"> <source>_Don't put ref or out on custom struct</source> <target state="translated">_Não colocar ref nem out no struct personalizado</target> <note /> </trans-unit> <trans-unit id="Editor_Help"> <source>Editor Help</source> <target state="translated">Ajuda do Editor</target> <note /> </trans-unit> <trans-unit id="Highlight_related_keywords_under_cursor"> <source>Highlight related _keywords under cursor</source> <target state="translated">Realçar _palavras-chave relacionadas usando o cursor</target> <note /> </trans-unit> <trans-unit id="Highlight_references_to_symbol_under_cursor"> <source>_Highlight references to symbol under cursor</source> <target state="translated">_Realçar referências a símbolo sob o cursor</target> <note /> </trans-unit> <trans-unit id="Enter_outlining_mode_when_files_open"> <source>Enter _outlining mode when files open</source> <target state="translated">Entrar no modo de _estrutura de tópicos ao abrir arquivos</target> <note /> </trans-unit> <trans-unit id="Extract_Method"> <source>Extract Method</source> <target state="translated">Extrair Método</target> <note /> </trans-unit> <trans-unit id="Generate_XML_documentation_comments_for"> <source>_Generate XML documentation comments for ///</source> <target state="translated">_Gerar comentário da documentação XML ///</target> <note /> </trans-unit> <trans-unit id="Highlighting"> <source>Highlighting</source> <target state="translated">Destaque</target> <note /> </trans-unit> <trans-unit id="Insert_at_the_start_of_new_lines_when_writing_comments"> <source>_Insert * at the start of new lines when writing /* */ comments</source> <target state="translated">_Insira um * no início das novas linhas ao escrever /* */ comentários</target> <note /> </trans-unit> <trans-unit id="Optimize_for_solution_size"> <source>Optimize for solution size</source> <target state="translated">Otimizar para o tamanho de solução</target> <note /> </trans-unit> <trans-unit id="Large"> <source>Large</source> <target state="translated">Grande</target> <note /> </trans-unit> <trans-unit id="Regular"> <source>Regular</source> <target state="translated">Normal</target> <note /> </trans-unit> <trans-unit id="Small"> <source>Small</source> <target state="translated">Pequeno</target> <note /> </trans-unit> <trans-unit id="Using_Directives"> <source>Using Directives</source> <target state="translated">Usando Diretivas</target> <note /> </trans-unit> <trans-unit id="Performance"> <source>Performance</source> <target state="translated">Desempenho</target> <note /> </trans-unit> <trans-unit id="Place_System_directives_first_when_sorting_usings"> <source>_Place 'System' directives first when sorting usings</source> <target state="translated">_Colocar as diretivas 'System' primeiro ao classificar usos</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">_Mostrar lista de conclusão depois que um caractere é digitado</target> <note /> </trans-unit> <trans-unit id="Place_keywords_in_completion_lists"> <source>Place _keywords in completion lists</source> <target state="translated">Colocar _palavras-chave em listas de conclusão</target> <note /> </trans-unit> <trans-unit id="Place_code_snippets_in_completion_lists"> <source>Place _code snippets in completion lists</source> <target state="translated">Colocar snippets de _código em listas de conclusão</target> <note /> </trans-unit> <trans-unit id="Selection_In_Completion_List"> <source>Selection In Completion List</source> <target state="translated">Seleção na Lista de Conclusão</target> <note /> </trans-unit> <trans-unit id="Show_preview_for_rename_tracking"> <source>Show preview for rename _tracking</source> <target state="translated">Mostrar visualização para acompanhamento de _renomeação</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_property_indexer_and_event_accessors"> <source>Place open brace on new line for property, indexer, and event accessors</source> <target state="translated">Colocar chave de abertura em nova linha para acessadores de eventos, propriedades e indexadores</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_properties_indexers_and_events"> <source>Place open brace on new line for properties, indexers, and events</source> <target state="translated">Colocar chave de abertura em nova linha para propriedades, indexadores e eventos</target> <note /> </trans-unit> <trans-unit id="Suggest_usings_for_types_in_NuGet_packages"> <source>Suggest usings for types in _NuGet packages</source> <target state="translated">Sugerir usos para tipos nos pacotes _NuGet</target> <note /> </trans-unit> <trans-unit id="Type_Inference_preferences_colon"> <source>Type Inference preferences:</source> <target state="translated">Preferências de Inferência de Tipos:</target> <note /> </trans-unit> <trans-unit id="For_built_in_types"> <source>For built-in types</source> <target state="translated">Para tipos internos</target> <note /> </trans-unit> <trans-unit id="Elsewhere"> <source>Elsewhere</source> <target state="translated">Em outro lugar</target> <note /> </trans-unit> <trans-unit id="When_on_multiple_lines"> <source>When on multiple lines</source> <target state="translated">Quando estiver em várias linhas</target> <note /> </trans-unit> <trans-unit id="When_variable_type_is_apparent"> <source>When variable type is apparent</source> <target state="translated">Quando o tipo de variável é aparente</target> <note /> </trans-unit> <trans-unit id="Qualify_event_access_with_this"> <source>Qualify event access with 'this'</source> <target state="translated">Qualificar acesso do evento com 'this'</target> <note /> </trans-unit> <trans-unit id="Qualify_field_access_with_this"> <source>Qualify field access with 'this'</source> <target state="translated">Qualificar acesso do campo com 'this'</target> <note /> </trans-unit> <trans-unit id="Qualify_method_access_with_this"> <source>Qualify method access with 'this'</source> <target state="translated">Qualificar acesso do método com 'this'</target> <note /> </trans-unit> <trans-unit id="Qualify_property_access_with_this"> <source>Qualify property access with 'this'</source> <target state="translated">Qualificar acesso da propriedade com 'this'</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_type"> <source>Prefer explicit type</source> <target state="translated">Preferir tipo explícito</target> <note /> </trans-unit> <trans-unit id="Prefer_this"> <source>Prefer 'this.'</source> <target state="translated">Preferir 'this'.</target> <note /> </trans-unit> <trans-unit id="Prefer_var"> <source>Prefer 'var'</source> <target state="translated">Preferir 'var'</target> <note /> </trans-unit> <trans-unit id="this_preferences_colon"> <source>'this.' preferences:</source> <target state="translated">'Preferências de 'this.':</target> <note /> </trans-unit> <trans-unit id="using_preferences_colon"> <source>'using' preferences:</source> <target state="translated">Preferências de 'using':</target> <note>'using' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="var_preferences_colon"> <source>'var' preferences:</source> <target state="translated">'Preferências de 'var':</target> <note /> </trans-unit> <trans-unit id="Do_not_prefer_this"> <source>Do not prefer 'this.'</source> <target state="translated">Não preferir 'this'.</target> <note /> </trans-unit> <trans-unit id="predefined_type_preferences_colon"> <source>predefined type preferences:</source> <target state="translated">Preferências de tipo predefinidas:</target> <note /> </trans-unit> <trans-unit id="Split_string_literals_on_enter"> <source>Split string literals on _enter</source> <target state="translated">Dividir sequências literais em _enter</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">_Realçar partes correspondentes dos itens da lista de conclusão</target> <note /> </trans-unit> <trans-unit id="Show_completion_item_filters"> <source>Show completion item _filters</source> <target state="translated">Mostrar _filtros de itens de conclusão</target> <note /> </trans-unit> <trans-unit id="Enter_key_behavior_colon"> <source>Enter key behavior:</source> <target state="translated">Insira o comportamento da tecla:</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">_Só adicionar nova linha ao inserir depois do final de uma palavra totalmente digitada</target> <note /> </trans-unit> <trans-unit id="Always_add_new_line_on_enter"> <source>_Always add new line on enter</source> <target state="translated">_Sempre adicionar nova linha ao inserir</target> <note /> </trans-unit> <trans-unit id="Never_add_new_line_on_enter"> <source>_Never add new line on enter</source> <target state="translated">_Nunca adicionar nova linha ao inserir</target> <note /> </trans-unit> <trans-unit id="Always_include_snippets"> <source>Always include snippets</source> <target state="translated">Sempre incluir snippets</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">Incluir snippets quando ?-Tab for digitado após um identificador</target> <note /> </trans-unit> <trans-unit id="Never_include_snippets"> <source>Never include snippets</source> <target state="translated">Nunca incluir snippets</target> <note /> </trans-unit> <trans-unit id="Snippets_behavior"> <source>Snippets behavior</source> <target state="translated">Comportamento de snippets</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">Mostrar lista de conclusão após um caractere ser _excluído</target> <note /> </trans-unit> <trans-unit id="null_checking_colon"> <source>'null' checking:</source> <target state="translated">'verificação 'null':</target> <note /> </trans-unit> <trans-unit id="Prefer_throw_expression"> <source>Prefer throw-expression</source> <target state="translated">Preferir expressão throw</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_delegate_call"> <source>Prefer conditional delegate call</source> <target state="translated">Preferir chamada de representante condicional</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_is_with_cast_check"> <source>Prefer pattern matching over 'is' with 'cast' check</source> <target state="translated">Preferir a correspondência de padrões 'is' com a seleção 'cast'</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_as_with_null_check"> <source>Prefer pattern matching over 'as' with 'null' check</source> <target state="translated">Preferir a correspondência de padrões 'as' com a seleção 'null'</target> <note /> </trans-unit> <trans-unit id="Prefer_block_body"> <source>Prefer block body</source> <target state="translated">Preferir o corpo do bloco</target> <note /> </trans-unit> <trans-unit id="Prefer_expression_body"> <source>Prefer expression body</source> <target state="translated">Preferir o corpo da expressão</target> <note /> </trans-unit> <trans-unit id="Automatically_format_on_return"> <source>Automatically format on return</source> <target state="translated">Formatar automaticamente no retorno</target> <note /> </trans-unit> <trans-unit id="Automatically_format_when_typing"> <source>Automatically format when typing</source> <target state="translated">Formatar automaticamente ao digitar</target> <note /> </trans-unit> <trans-unit id="Never"> <source>Never</source> <target state="translated">Nunca</target> <note /> </trans-unit> <trans-unit id="When_on_single_line"> <source>When on single line</source> <target state="translated">Quando em linha única</target> <note /> </trans-unit> <trans-unit id="When_possible"> <source>When possible</source> <target state="translated">Quando possível</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents_when_block"> <source>Indent case contents (when block)</source> <target state="translated">Recuar conteúdo de caso (quando bloquear)</target> <note /> </trans-unit> <trans-unit id="Fade_out_unused_usings"> <source>Fade out unused usings</source> <target state="translated">Esmaecer usos não utilizados</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">Relatar espaços reservados inválidos em chamadas 'String.Format'</target> <note /> </trans-unit> <trans-unit id="Separate_using_directive_groups"> <source>Separate using directive groups</source> <target state="translated">Separar usando grupos de diretiva</target> <note /> </trans-unit> <trans-unit id="Show_name_suggestions"> <source>Show name s_uggestions</source> <target state="translated">Mostrar s_ugestões de nomes</target> <note /> </trans-unit> <trans-unit id="In_arithmetic_binary_operators"> <source>In arithmetic operators: * / % + - &lt;&lt; &gt;&gt; &amp; ^ |</source> <target state="translated">Em operadores aritméticos: * / % + - &lt;&lt; &gt;&gt; &amp; ^ |</target> <note /> </trans-unit> <trans-unit id="In_other_binary_operators"> <source>In other binary operators: &amp;&amp; || ?? and or</source> <target state="translated">Em outros operadores binários: &amp;&amp; || ?? and or</target> <note>'and' and 'or' are C# keywords and should not be localized</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="pt-BR" original="../CSharpVSResources.resx"> <body> <trans-unit id="Add_missing_using_directives_on_paste"> <source>Add missing using directives on paste</source> <target state="translated">Adicionar as diretivas using ausentes ao colar</target> <note>'using' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Allow_bank_line_after_colon_in_constructor_initializer"> <source>Allow blank line after colon in constructor initializer</source> <target state="translated">Permitir uma linha em branco após os dois-pontos no inicializador do construtor</target> <note /> </trans-unit> <trans-unit id="Allow_blank_lines_between_consecutive_braces"> <source>Allow blank lines between consecutive braces</source> <target state="translated">Permitir linhas em branco entre chaves consecutivas</target> <note /> </trans-unit> <trans-unit id="Allow_embedded_statements_on_same_line"> <source>Allow embedded statements on same line</source> <target state="translated">Permitir instruções inseridas na mesma linha</target> <note /> </trans-unit> <trans-unit id="Apply_all_csharp_formatting_rules_indentation_wrapping_spacing"> <source>Apply all C# formatting rules (indentation, wrapping, spacing)</source> <target state="translated">Aplicar todas as regras de formatação de C# (recuo, quebra de linha, espaçamento)</target> <note /> </trans-unit> <trans-unit id="Automatically_complete_statement_on_semicolon"> <source>Automatically complete statement on semicolon</source> <target state="translated">Concluir a instrução automaticamente no ponto e vírgula</target> <note /> </trans-unit> <trans-unit id="Automatically_show_completion_list_in_argument_lists"> <source>Automatically show completion list in argument lists</source> <target state="translated">Mostrar automaticamente a lista de conclusão nas listas de argumentos</target> <note /> </trans-unit> <trans-unit id="Block_scoped"> <source>Block scoped</source> <target state="new">Block scoped</target> <note /> </trans-unit> <trans-unit id="CSharp"> <source>C#</source> <target state="translated">C#</target> <note /> </trans-unit> <trans-unit id="CSharp_Coding_Conventions"> <source>C# Coding Conventions</source> <target state="translated">Convenções de Codificação em C#</target> <note /> </trans-unit> <trans-unit id="CSharp_Formatting_Rules"> <source>C# Formatting Rules</source> <target state="translated">Regras de Formatação de C#</target> <note /> </trans-unit> <trans-unit id="Completion"> <source>Completion</source> <target state="translated">Conclusão</target> <note /> </trans-unit> <trans-unit id="Discard"> <source>Discard</source> <target state="translated">Descartar</target> <note /> </trans-unit> <trans-unit id="Edit_color_scheme"> <source>Edit color scheme</source> <target state="translated">Editar o esquema de cores</target> <note /> </trans-unit> <trans-unit id="File_scoped"> <source>File scoped</source> <target state="new">File scoped</target> <note /> </trans-unit> <trans-unit id="Format_document_settings"> <source>Format Document Settings (Experiment) </source> <target state="translated">Formatar Configurações do Documento (Experimento)</target> <note /> </trans-unit> <trans-unit id="General"> <source>General</source> <target state="translated">Geral</target> <note>Title of the control group on the General Formatting options page</note> </trans-unit> <trans-unit id="In_relational_binary_operators"> <source>In relational operators: &lt; &gt; &lt;= &gt;= is as == !=</source> <target state="translated">Em operadores relacionais: &lt; &gt; &lt;= &gt;= is as == !=</target> <note>'is' and 'as' are C# keywords and should not be localized</note> </trans-unit> <trans-unit id="Insert_slash_slash_at_the_start_of_new_lines_when_writing_slash_slash_comments"> <source>Insert // at the start of new lines when writing // comments</source> <target state="translated">Inserir // no início de novas linhas ao escrever comentários de //</target> <note /> </trans-unit> <trans-unit id="Inside_namespace"> <source>Inside namespace</source> <target state="translated">Namespace interno</target> <note>'namespace' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Outside_namespace"> <source>Outside namespace</source> <target state="translated">Namespace externo</target> <note>'namespace' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Pattern_matching_preferences_colon"> <source>Pattern matching preferences:</source> <target state="translated">Preferências de correspondência de padrões:</target> <note /> </trans-unit> <trans-unit id="Perform_additional_code_cleanup_during_formatting"> <source>Perform additional code cleanup during formatting</source> <target state="translated">Executar limpeza de código adicional durante a formatação</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_object_collection_array_and_with_initializers"> <source>Place open brace on new line for object, collection, array, and with initializers</source> <target state="translated">Colocar uma chave de abertura em uma nova linha para inicializadores de objeto, coleção, matriz e with</target> <note>{Locked="with"}</note> </trans-unit> <trans-unit id="Prefer_implicit_object_creation_when_type_is_apparent"> <source>Prefer implicit object creation when type is apparent</source> <target state="translated">Preferir a criação de objeto implícito quando o tipo for aparente</target> <note /> </trans-unit> <trans-unit id="Prefer_is_null_for_reference_equality_checks"> <source>Prefer 'is null' for reference equality checks</source> <target state="translated">Preferir 'is null' para as verificações de igualdade de referência</target> <note>'is null' is a C# string and should not be localized.</note> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching"> <source>Prefer pattern matching</source> <target state="translated">Preferir a correspondência de padrões</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_mixed_type_check"> <source>Prefer pattern matching over mixed type check</source> <target state="translated">Preferir a correspondência de padrões em vez da verificação de tipo misto</target> <note /> </trans-unit> <trans-unit id="Prefer_switch_expression"> <source>Prefer switch expression</source> <target state="translated">Preferir a expressão switch</target> <note /> </trans-unit> <trans-unit id="Preferred_using_directive_placement"> <source>Preferred 'using' directive placement</source> <target state="translated">Posicionamento da diretiva 'using' preferencial</target> <note>'using' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Remove_unnecessary_usings"> <source>Remove unnecessary usings</source> <target state="translated">Remover Usos Desnecessários</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_new_expressions"> <source>Show hints for 'new' expressions</source> <target state="translated">Mostrar as dicas para as expressões 'new'</target> <note /> </trans-unit> <trans-unit id="Show_items_from_unimported_namespaces"> <source>Show items from unimported namespaces</source> <target state="translated">Mostrar os itens de namespaces não importados</target> <note /> </trans-unit> <trans-unit id="Show_remarks_in_Quick_Info"> <source>Show remarks in Quick Info</source> <target state="translated">Mostrar os comentários nas Informações Rápidas</target> <note /> </trans-unit> <trans-unit id="Sort_usings"> <source>Sort usings</source> <target state="translated">Classificar usos</target> <note /> </trans-unit> <trans-unit id="Suggest_usings_for_types_in_dotnet_framework_assemblies"> <source>Suggest usings for types in .NET Framework assemblies</source> <target state="translated">Sugerir usings para tipos nos assemblies do .NET Framework</target> <note /> </trans-unit> <trans-unit id="Surround_With"> <source>Surround With</source> <target state="translated">Envolver com</target> <note /> </trans-unit> <trans-unit id="Insert_Snippet"> <source>Insert Snippet</source> <target state="translated">Inserir Snippet</target> <note /> </trans-unit> <trans-unit id="Automatically_format_block_on_close_brace"> <source>Automatically format _block on }</source> <target state="translated">Formatar automaticamente _bloco em }</target> <note /> </trans-unit> <trans-unit id="Automatically_format_on_paste"> <source>Automatically format on _paste</source> <target state="translated">Formatar automaticamente após _colar</target> <note /> </trans-unit> <trans-unit id="Automatically_format_statement_on_semicolon"> <source>Automatically format _statement on ;</source> <target state="translated">Formatar automaticamente _instrução em;</target> <note /> </trans-unit> <trans-unit id="Place_members_in_anonymous_types_on_new_line"> <source>Place members in anonymous types on new line</source> <target state="translated">Colocar membros em tipos anônimos em nova linha</target> <note /> </trans-unit> <trans-unit id="Leave_block_on_single_line"> <source>Leave block on single line</source> <target state="translated">Deixar bloco em uma linha única</target> <note /> </trans-unit> <trans-unit id="Place_catch_on_new_line"> <source>Place "catch" on new line</source> <target state="translated">Colocar "catch" em nova linha</target> <note /> </trans-unit> <trans-unit id="Place_else_on_new_line"> <source>Place "else" on new line</source> <target state="translated">Colocar "else" em nova linha</target> <note /> </trans-unit> <trans-unit id="Indent_block_contents"> <source>Indent block contents</source> <target state="translated">Recuar conteúdo do bloco</target> <note /> </trans-unit> <trans-unit id="Indent_open_and_close_braces"> <source>Indent open and close braces</source> <target state="translated">Recuar chaves de abertura e fechamento</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents"> <source>Indent case contents</source> <target state="translated">Recuar conteúdo de case</target> <note /> </trans-unit> <trans-unit id="Indent_case_labels"> <source>Indent case labels</source> <target state="translated">Recuar rótulos case</target> <note /> </trans-unit> <trans-unit id="Place_finally_on_new_line"> <source>Place "finally" on new line</source> <target state="translated">Colocar "finally" em nova linha</target> <note /> </trans-unit> <trans-unit id="Place_goto_labels_in_leftmost_column"> <source>Place goto labels in leftmost column</source> <target state="translated">Posicionar rótulos goto na coluna mais à esquerda</target> <note /> </trans-unit> <trans-unit id="Indent_labels_normally"> <source>Indent labels normally</source> <target state="translated">Recuar rótulos normalmente</target> <note /> </trans-unit> <trans-unit id="Place_goto_labels_one_indent_less_than_current"> <source>Place goto labels one indent less than current</source> <target state="translated">Colocar rótulos goto um recuo a menos do que o atual</target> <note /> </trans-unit> <trans-unit id="Label_Indentation"> <source>Label Indentation</source> <target state="translated">Recuo do Rótulo</target> <note /> </trans-unit> <trans-unit id="Place_members_in_object_initializers_on_new_line"> <source>Place members in object initializers on new line</source> <target state="translated">Colocar membros em inicializadores de objetos em nova linha</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_methods"> <source>Place open brace on new line for anonymous methods</source> <target state="translated">Colocar chave de abertura em nova linha para métodos anônimos</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_anonymous_types"> <source>Place open brace on new line for anonymous types</source> <target state="translated">Colocar chave de abertura em nova linha para tipos anônimos</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_control_blocks"> <source>Place open brace on new line for control blocks</source> <target state="translated">Colocar chave de abertura em nova linha para blocos de controle</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_lambda_expression"> <source>Place open brace on new line for lambda expression</source> <target state="translated">Colocar chave de abertura em nova linha para expressão lambda</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_methods_local_functions"> <source>Place open brace on new line for methods and local functions</source> <target state="translated">Colocar chave de abertura na nova linha para métodos e funções locais</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_types"> <source>Place open brace on new line for types</source> <target state="translated">Colocar chave de abertura em nova linha para tipos</target> <note /> </trans-unit> <trans-unit id="Place_query_expression_clauses_on_new_line"> <source>Place query expression clauses on new line</source> <target state="translated">Colocar cláusulas de expressão de consulta na nova linha</target> <note /> </trans-unit> <trans-unit id="Leave_statements_and_member_declarations_on_the_same_line"> <source>Leave statements and member declarations on the same line</source> <target state="translated">Deixar instruções e declarações de membros na mesma linha</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_and_after_binary_operators"> <source>Insert space before and after binary operators</source> <target state="translated">Inserir espaço antes e depois de operadores binários</target> <note /> </trans-unit> <trans-unit id="Ignore_spaces_around_binary_operators"> <source>Ignore spaces around binary operators</source> <target state="translated">Ignorar espaços em torno de operadores binários</target> <note /> </trans-unit> <trans-unit id="Remove_spaces_before_and_after_binary_operators"> <source>Remove spaces before and after binary operators</source> <target state="translated">Remover espaços antes e depois de operadores binários</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_colon_for_base_or_interface_in_type_declaration"> <source>Insert space after colon for base or interface in type declaration</source> <target state="translated">Inserir espaço após dois-pontos para base ou interface na declaração de tipo</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_comma"> <source>Insert space after comma</source> <target state="translated">Inserir espaço após vírgula</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_dot"> <source>Insert space after dot</source> <target state="translated">Inserir espaço após ponto</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_semicolon_in_for_statement"> <source>Insert space after semicolon in "for" statement</source> <target state="translated">Inserir espaço após ponto e vírgula em instruções "for"</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_colon_for_base_or_interface_in_type_declaration"> <source>Insert space before colon for base or interface in type declaration</source> <target state="translated">Inserir espaço antes de dois-pontos para base ou interface na declaração de tipo</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_comma"> <source>Insert space before comma</source> <target state="translated">Inserir espaço antes da vírgula</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_dot"> <source>Insert space before dot</source> <target state="translated">Inserir espaço antes do ponto</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_semicolon_in_for_statement"> <source>Insert space before semicolon in "for" statement</source> <target state="translated">Inserir espaço antes de ponto e vírgula em instruções "for"</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_argument_list_parentheses"> <source>Insert space within argument list parentheses</source> <target state="translated">Inserir espaço dentro dos parênteses da lista de argumentos</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_argument_list_parentheses"> <source>Insert space within empty argument list parentheses</source> <target state="translated">Inserir espaço dentro dos parênteses da lista de argumentos vazia</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis1"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">Inserir espaço entre o nome do método e o parêntese inicial</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_parameter_list_parentheses"> <source>Insert space within empty parameter list parentheses</source> <target state="translated">Inserir espaço no parênteses da lista de parâmetros vazia</target> <note /> </trans-unit> <trans-unit id="Insert_space_between_method_name_and_its_opening_parenthesis2"> <source>Insert space between method name and its opening parenthesis</source> <target state="translated">Inserir espaço entre o nome do método e o parêntese inicial</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parameter_list_parentheses"> <source>Insert space within parameter list parentheses</source> <target state="translated">Inserir espaço dentro dos parênteses da lista de parâmetros</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_keywords_in_control_flow_statements"> <source>Insert space after keywords in control flow statements</source> <target state="translated">Inserir espaço após palavras-chave em instruções de fluxo de controle</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_expressions"> <source>Insert space within parentheses of expressions</source> <target state="translated">Inserir espaços dentro dos parênteses das expressões</target> <note /> </trans-unit> <trans-unit id="Insert_space_after_cast"> <source>Insert space after cast</source> <target state="translated">Inserir espaço após conversão</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_parentheses_of_control_flow_statements"> <source>Insert spaces within parentheses of control flow statements</source> <target state="translated">Inserir espaços dentro dos parênteses das instruções de fluxo de controle</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_parentheses_of_type_casts"> <source>Insert space within parentheses of type casts</source> <target state="translated">Inserir espaço dentro dos parênteses das conversões de tipo</target> <note /> </trans-unit> <trans-unit id="Ignore_spaces_in_declaration_statements"> <source>Ignore spaces in declaration statements</source> <target state="translated">Ignorar espaços em instruções de declaração</target> <note /> </trans-unit> <trans-unit id="Set_other_spacing_options"> <source>Set other spacing options</source> <target state="translated">Definir outras opções de espaçamento</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_brackets"> <source>Set spacing for brackets</source> <target state="translated">Definir espaçamento para colchetes</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_delimiters"> <source>Set spacing for delimiters</source> <target state="translated">Definir espaçamento para delimitadores</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_method_calls"> <source>Set spacing for method calls</source> <target state="translated">Definir espaçamento para chamadas de método</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_method_declarations"> <source>Set spacing for method declarations</source> <target state="translated">Definir espaçamento para declarações de método</target> <note /> </trans-unit> <trans-unit id="Set_spacing_for_operators"> <source>Set spacing for operators</source> <target state="translated">Definir espaçamento para operadores</target> <note /> </trans-unit> <trans-unit id="Insert_spaces_within_square_brackets"> <source>Insert spaces within square brackets</source> <target state="translated">Inserir espaços dentro de colchetes</target> <note /> </trans-unit> <trans-unit id="Insert_space_before_open_square_bracket"> <source>Insert space before open square bracket</source> <target state="translated">Inserir espaço antes do colchete de abertura</target> <note /> </trans-unit> <trans-unit id="Insert_space_within_empty_square_brackets"> <source>Insert space within empty square brackets</source> <target state="translated">Inserir espaço dentro de colchetes vazios</target> <note /> </trans-unit> <trans-unit id="New_line_options_for_braces"> <source>New line options for braces</source> <target state="translated">Novas opções de linha para chaves</target> <note /> </trans-unit> <trans-unit id="New_line_options_for_expressions"> <source>New line options for expressions</source> <target state="translated">Novas opções de linha para expressões</target> <note /> </trans-unit> <trans-unit id="New_line_options_for_keywords"> <source>New line options for keywords</source> <target state="translated">Novas opções de linha para palavras-chaves</target> <note /> </trans-unit> <trans-unit id="Unused_local"> <source>Unused local</source> <target state="translated">Local não usado</target> <note /> </trans-unit> <trans-unit id="Use_var_when_generating_locals"> <source>Use 'var' when generating locals</source> <target state="translated">Usar "var" ao gerar locais</target> <note /> </trans-unit> <trans-unit id="Show_procedure_line_separators"> <source>_Show procedure line separators</source> <target state="translated">_Mostrar separadores de linha de procedimento</target> <note /> </trans-unit> <trans-unit id="Don_t_put_ref_or_out_on_custom_struct"> <source>_Don't put ref or out on custom struct</source> <target state="translated">_Não colocar ref nem out no struct personalizado</target> <note /> </trans-unit> <trans-unit id="Editor_Help"> <source>Editor Help</source> <target state="translated">Ajuda do Editor</target> <note /> </trans-unit> <trans-unit id="Highlight_related_keywords_under_cursor"> <source>Highlight related _keywords under cursor</source> <target state="translated">Realçar _palavras-chave relacionadas usando o cursor</target> <note /> </trans-unit> <trans-unit id="Highlight_references_to_symbol_under_cursor"> <source>_Highlight references to symbol under cursor</source> <target state="translated">_Realçar referências a símbolo sob o cursor</target> <note /> </trans-unit> <trans-unit id="Enter_outlining_mode_when_files_open"> <source>Enter _outlining mode when files open</source> <target state="translated">Entrar no modo de _estrutura de tópicos ao abrir arquivos</target> <note /> </trans-unit> <trans-unit id="Extract_Method"> <source>Extract Method</source> <target state="translated">Extrair Método</target> <note /> </trans-unit> <trans-unit id="Generate_XML_documentation_comments_for"> <source>_Generate XML documentation comments for ///</source> <target state="translated">_Gerar comentário da documentação XML ///</target> <note /> </trans-unit> <trans-unit id="Highlighting"> <source>Highlighting</source> <target state="translated">Destaque</target> <note /> </trans-unit> <trans-unit id="Insert_at_the_start_of_new_lines_when_writing_comments"> <source>_Insert * at the start of new lines when writing /* */ comments</source> <target state="translated">_Insira um * no início das novas linhas ao escrever /* */ comentários</target> <note /> </trans-unit> <trans-unit id="Optimize_for_solution_size"> <source>Optimize for solution size</source> <target state="translated">Otimizar para o tamanho de solução</target> <note /> </trans-unit> <trans-unit id="Large"> <source>Large</source> <target state="translated">Grande</target> <note /> </trans-unit> <trans-unit id="Regular"> <source>Regular</source> <target state="translated">Normal</target> <note /> </trans-unit> <trans-unit id="Small"> <source>Small</source> <target state="translated">Pequeno</target> <note /> </trans-unit> <trans-unit id="Using_Directives"> <source>Using Directives</source> <target state="translated">Usando Diretivas</target> <note /> </trans-unit> <trans-unit id="Performance"> <source>Performance</source> <target state="translated">Desempenho</target> <note /> </trans-unit> <trans-unit id="Place_System_directives_first_when_sorting_usings"> <source>_Place 'System' directives first when sorting usings</source> <target state="translated">_Colocar as diretivas 'System' primeiro ao classificar usos</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">_Mostrar lista de conclusão depois que um caractere é digitado</target> <note /> </trans-unit> <trans-unit id="Place_keywords_in_completion_lists"> <source>Place _keywords in completion lists</source> <target state="translated">Colocar _palavras-chave em listas de conclusão</target> <note /> </trans-unit> <trans-unit id="Place_code_snippets_in_completion_lists"> <source>Place _code snippets in completion lists</source> <target state="translated">Colocar snippets de _código em listas de conclusão</target> <note /> </trans-unit> <trans-unit id="Selection_In_Completion_List"> <source>Selection In Completion List</source> <target state="translated">Seleção na Lista de Conclusão</target> <note /> </trans-unit> <trans-unit id="Show_preview_for_rename_tracking"> <source>Show preview for rename _tracking</source> <target state="translated">Mostrar visualização para acompanhamento de _renomeação</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_property_indexer_and_event_accessors"> <source>Place open brace on new line for property, indexer, and event accessors</source> <target state="translated">Colocar chave de abertura em nova linha para acessadores de eventos, propriedades e indexadores</target> <note /> </trans-unit> <trans-unit id="Place_open_brace_on_new_line_for_properties_indexers_and_events"> <source>Place open brace on new line for properties, indexers, and events</source> <target state="translated">Colocar chave de abertura em nova linha para propriedades, indexadores e eventos</target> <note /> </trans-unit> <trans-unit id="Suggest_usings_for_types_in_NuGet_packages"> <source>Suggest usings for types in _NuGet packages</source> <target state="translated">Sugerir usos para tipos nos pacotes _NuGet</target> <note /> </trans-unit> <trans-unit id="Type_Inference_preferences_colon"> <source>Type Inference preferences:</source> <target state="translated">Preferências de Inferência de Tipos:</target> <note /> </trans-unit> <trans-unit id="For_built_in_types"> <source>For built-in types</source> <target state="translated">Para tipos internos</target> <note /> </trans-unit> <trans-unit id="Elsewhere"> <source>Elsewhere</source> <target state="translated">Em outro lugar</target> <note /> </trans-unit> <trans-unit id="When_on_multiple_lines"> <source>When on multiple lines</source> <target state="translated">Quando estiver em várias linhas</target> <note /> </trans-unit> <trans-unit id="When_variable_type_is_apparent"> <source>When variable type is apparent</source> <target state="translated">Quando o tipo de variável é aparente</target> <note /> </trans-unit> <trans-unit id="Qualify_event_access_with_this"> <source>Qualify event access with 'this'</source> <target state="translated">Qualificar acesso do evento com 'this'</target> <note /> </trans-unit> <trans-unit id="Qualify_field_access_with_this"> <source>Qualify field access with 'this'</source> <target state="translated">Qualificar acesso do campo com 'this'</target> <note /> </trans-unit> <trans-unit id="Qualify_method_access_with_this"> <source>Qualify method access with 'this'</source> <target state="translated">Qualificar acesso do método com 'this'</target> <note /> </trans-unit> <trans-unit id="Qualify_property_access_with_this"> <source>Qualify property access with 'this'</source> <target state="translated">Qualificar acesso da propriedade com 'this'</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_type"> <source>Prefer explicit type</source> <target state="translated">Preferir tipo explícito</target> <note /> </trans-unit> <trans-unit id="Prefer_this"> <source>Prefer 'this.'</source> <target state="translated">Preferir 'this'.</target> <note /> </trans-unit> <trans-unit id="Prefer_var"> <source>Prefer 'var'</source> <target state="translated">Preferir 'var'</target> <note /> </trans-unit> <trans-unit id="this_preferences_colon"> <source>'this.' preferences:</source> <target state="translated">'Preferências de 'this.':</target> <note /> </trans-unit> <trans-unit id="using_preferences_colon"> <source>'using' preferences:</source> <target state="translated">Preferências de 'using':</target> <note>'using' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="var_preferences_colon"> <source>'var' preferences:</source> <target state="translated">'Preferências de 'var':</target> <note /> </trans-unit> <trans-unit id="Do_not_prefer_this"> <source>Do not prefer 'this.'</source> <target state="translated">Não preferir 'this'.</target> <note /> </trans-unit> <trans-unit id="predefined_type_preferences_colon"> <source>predefined type preferences:</source> <target state="translated">Preferências de tipo predefinidas:</target> <note /> </trans-unit> <trans-unit id="Split_string_literals_on_enter"> <source>Split string literals on _enter</source> <target state="translated">Dividir sequências literais em _enter</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">_Realçar partes correspondentes dos itens da lista de conclusão</target> <note /> </trans-unit> <trans-unit id="Show_completion_item_filters"> <source>Show completion item _filters</source> <target state="translated">Mostrar _filtros de itens de conclusão</target> <note /> </trans-unit> <trans-unit id="Enter_key_behavior_colon"> <source>Enter key behavior:</source> <target state="translated">Insira o comportamento da tecla:</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">_Só adicionar nova linha ao inserir depois do final de uma palavra totalmente digitada</target> <note /> </trans-unit> <trans-unit id="Always_add_new_line_on_enter"> <source>_Always add new line on enter</source> <target state="translated">_Sempre adicionar nova linha ao inserir</target> <note /> </trans-unit> <trans-unit id="Never_add_new_line_on_enter"> <source>_Never add new line on enter</source> <target state="translated">_Nunca adicionar nova linha ao inserir</target> <note /> </trans-unit> <trans-unit id="Always_include_snippets"> <source>Always include snippets</source> <target state="translated">Sempre incluir snippets</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">Incluir snippets quando ?-Tab for digitado após um identificador</target> <note /> </trans-unit> <trans-unit id="Never_include_snippets"> <source>Never include snippets</source> <target state="translated">Nunca incluir snippets</target> <note /> </trans-unit> <trans-unit id="Snippets_behavior"> <source>Snippets behavior</source> <target state="translated">Comportamento de snippets</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">Mostrar lista de conclusão após um caractere ser _excluído</target> <note /> </trans-unit> <trans-unit id="null_checking_colon"> <source>'null' checking:</source> <target state="translated">'verificação 'null':</target> <note /> </trans-unit> <trans-unit id="Prefer_throw_expression"> <source>Prefer throw-expression</source> <target state="translated">Preferir expressão throw</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_delegate_call"> <source>Prefer conditional delegate call</source> <target state="translated">Preferir chamada de representante condicional</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_is_with_cast_check"> <source>Prefer pattern matching over 'is' with 'cast' check</source> <target state="translated">Preferir a correspondência de padrões 'is' com a seleção 'cast'</target> <note /> </trans-unit> <trans-unit id="Prefer_pattern_matching_over_as_with_null_check"> <source>Prefer pattern matching over 'as' with 'null' check</source> <target state="translated">Preferir a correspondência de padrões 'as' com a seleção 'null'</target> <note /> </trans-unit> <trans-unit id="Prefer_block_body"> <source>Prefer block body</source> <target state="translated">Preferir o corpo do bloco</target> <note /> </trans-unit> <trans-unit id="Prefer_expression_body"> <source>Prefer expression body</source> <target state="translated">Preferir o corpo da expressão</target> <note /> </trans-unit> <trans-unit id="Automatically_format_on_return"> <source>Automatically format on return</source> <target state="translated">Formatar automaticamente no retorno</target> <note /> </trans-unit> <trans-unit id="Automatically_format_when_typing"> <source>Automatically format when typing</source> <target state="translated">Formatar automaticamente ao digitar</target> <note /> </trans-unit> <trans-unit id="Never"> <source>Never</source> <target state="translated">Nunca</target> <note /> </trans-unit> <trans-unit id="When_on_single_line"> <source>When on single line</source> <target state="translated">Quando em linha única</target> <note /> </trans-unit> <trans-unit id="When_possible"> <source>When possible</source> <target state="translated">Quando possível</target> <note /> </trans-unit> <trans-unit id="Indent_case_contents_when_block"> <source>Indent case contents (when block)</source> <target state="translated">Recuar conteúdo de caso (quando bloquear)</target> <note /> </trans-unit> <trans-unit id="Fade_out_unused_usings"> <source>Fade out unused usings</source> <target state="translated">Esmaecer usos não utilizados</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">Relatar espaços reservados inválidos em chamadas 'String.Format'</target> <note /> </trans-unit> <trans-unit id="Separate_using_directive_groups"> <source>Separate using directive groups</source> <target state="translated">Separar usando grupos de diretiva</target> <note /> </trans-unit> <trans-unit id="Show_name_suggestions"> <source>Show name s_uggestions</source> <target state="translated">Mostrar s_ugestões de nomes</target> <note /> </trans-unit> <trans-unit id="In_arithmetic_binary_operators"> <source>In arithmetic operators: * / % + - &lt;&lt; &gt;&gt; &amp; ^ |</source> <target state="translated">Em operadores aritméticos: * / % + - &lt;&lt; &gt;&gt; &amp; ^ |</target> <note /> </trans-unit> <trans-unit id="In_other_binary_operators"> <source>In other binary operators: &amp;&amp; || ?? and or</source> <target state="translated">Em outros operadores binários: &amp;&amp; || ?? and or</target> <note>'and' and 'or' are C# keywords and should not be localized</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxTokenListTests.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.VisualBasic.UnitTests Public Class SyntaxTokenListTests <Fact> Public Sub Extensions() Dim list = SyntaxFactory.TokenList( SyntaxFactory.Token(SyntaxKind.AddHandlerKeyword), SyntaxFactory.Literal("x"), SyntaxFactory.Token(SyntaxKind.DotToken)) Assert.Equal(0, list.IndexOf(SyntaxKind.AddHandlerKeyword)) Assert.True(list.Any(SyntaxKind.AddHandlerKeyword)) Assert.Equal(1, List.IndexOf(SyntaxKind.StringLiteralToken)) Assert.True(List.Any(SyntaxKind.StringLiteralToken)) Assert.Equal(2, List.IndexOf(SyntaxKind.DotToken)) Assert.True(List.Any(SyntaxKind.DotToken)) Assert.Equal(-1, list.IndexOf(SyntaxKind.NothingKeyword)) Assert.False(list.Any(SyntaxKind.NothingKeyword)) 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.VisualBasic.UnitTests Public Class SyntaxTokenListTests <Fact> Public Sub Extensions() Dim list = SyntaxFactory.TokenList( SyntaxFactory.Token(SyntaxKind.AddHandlerKeyword), SyntaxFactory.Literal("x"), SyntaxFactory.Token(SyntaxKind.DotToken)) Assert.Equal(0, list.IndexOf(SyntaxKind.AddHandlerKeyword)) Assert.True(list.Any(SyntaxKind.AddHandlerKeyword)) Assert.Equal(1, List.IndexOf(SyntaxKind.StringLiteralToken)) Assert.True(List.Any(SyntaxKind.StringLiteralToken)) Assert.Equal(2, List.IndexOf(SyntaxKind.DotToken)) Assert.True(List.Any(SyntaxKind.DotToken)) Assert.Equal(-1, list.IndexOf(SyntaxKind.NothingKeyword)) Assert.False(list.Any(SyntaxKind.NothingKeyword)) End Sub End Class End Namespace
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/Test/EditAndContinue/EmitSolutionUpdateResultsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { [UseExportProvider] public class EmitSolutionUpdateResultsTests { [Fact] public async Task GetHotReloadDiagnostics() { using var workspace = new TestWorkspace(composition: FeaturesTestCompositions.Features); var sourcePath = Path.Combine(TempRoot.Root, "x", "a.cs"); var razorPath = Path.Combine(TempRoot.Root, "a.razor"); var document = workspace.CurrentSolution. AddProject("proj", "proj", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Standard)). AddDocument(sourcePath, SourceText.From("class C {}", Encoding.UTF8), filePath: Path.Combine(TempRoot.Root, sourcePath)); var solution = document.Project.Solution; var diagnosticData = ImmutableArray.Create( new DiagnosticData( id: "CS0001", category: "Test", message: "warning", enuMessageForBingSearch: "test2 message format", severity: DiagnosticSeverity.Warning, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, warningLevel: 0, customTags: ImmutableArray.Create("Test2"), properties: ImmutableDictionary<string, string?>.Empty, document.Project.Id, new DiagnosticDataLocation(document.Id, new TextSpan(1, 2), "a.cs", 0, 0, 0, 5, "a.razor", 10, 10, 10, 15), language: "C#", title: "title", description: "description", helpLink: "http://link"), new DiagnosticData( id: "CS0012", category: "Test", message: "error", enuMessageForBingSearch: "test2 message format", severity: DiagnosticSeverity.Error, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, warningLevel: 0, customTags: ImmutableArray.Create("Test2"), properties: ImmutableDictionary<string, string?>.Empty, document.Project.Id, new DiagnosticDataLocation(document.Id, new TextSpan(1, 2), originalFilePath: sourcePath, 0, 0, 0, 5, mappedFilePath: @"..\a.razor", 10, 10, 10, 15), language: "C#", title: "title", description: "description", helpLink: "http://link")); var rudeEdits = ImmutableArray.Create( (document.Id, ImmutableArray.Create(new RudeEditDiagnostic(RudeEditKind.Insert, TextSpan.FromBounds(1, 10), 123, new[] { "a" }))), (document.Id, ImmutableArray.Create(new RudeEditDiagnostic(RudeEditKind.Delete, TextSpan.FromBounds(1, 10), 123, new[] { "b" })))); var actual = await EmitSolutionUpdateResults.GetHotReloadDiagnosticsAsync(solution, diagnosticData, rudeEdits, CancellationToken.None); AssertEx.Equal(new[] { $@"Error CS0012: {razorPath} (10,10)-(10,15): error", $@"Error ENC0021: {sourcePath} (0,1)-(0,10): {string.Format(FeaturesResources.Adding_0_requires_restarting_the_application, "a")}", $@"Error ENC0033: {sourcePath} (0,1)-(0,10): {string.Format(FeaturesResources.Deleting_0_requires_restarting_the_application, "b")}" }, actual.Select(d => $"{d.Severity} {d.Id}: {d.FilePath} {d.Span.GetDebuggerDisplay()}: {d.Message}")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { [UseExportProvider] public class EmitSolutionUpdateResultsTests { [Fact] public async Task GetHotReloadDiagnostics() { using var workspace = new TestWorkspace(composition: FeaturesTestCompositions.Features); var sourcePath = Path.Combine(TempRoot.Root, "x", "a.cs"); var razorPath = Path.Combine(TempRoot.Root, "a.razor"); var document = workspace.CurrentSolution. AddProject("proj", "proj", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Standard)). AddDocument(sourcePath, SourceText.From("class C {}", Encoding.UTF8), filePath: Path.Combine(TempRoot.Root, sourcePath)); var solution = document.Project.Solution; var diagnosticData = ImmutableArray.Create( new DiagnosticData( id: "CS0001", category: "Test", message: "warning", enuMessageForBingSearch: "test2 message format", severity: DiagnosticSeverity.Warning, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, warningLevel: 0, customTags: ImmutableArray.Create("Test2"), properties: ImmutableDictionary<string, string?>.Empty, document.Project.Id, new DiagnosticDataLocation(document.Id, new TextSpan(1, 2), "a.cs", 0, 0, 0, 5, "a.razor", 10, 10, 10, 15), language: "C#", title: "title", description: "description", helpLink: "http://link"), new DiagnosticData( id: "CS0012", category: "Test", message: "error", enuMessageForBingSearch: "test2 message format", severity: DiagnosticSeverity.Error, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, warningLevel: 0, customTags: ImmutableArray.Create("Test2"), properties: ImmutableDictionary<string, string?>.Empty, document.Project.Id, new DiagnosticDataLocation(document.Id, new TextSpan(1, 2), originalFilePath: sourcePath, 0, 0, 0, 5, mappedFilePath: @"..\a.razor", 10, 10, 10, 15), language: "C#", title: "title", description: "description", helpLink: "http://link")); var rudeEdits = ImmutableArray.Create( (document.Id, ImmutableArray.Create(new RudeEditDiagnostic(RudeEditKind.Insert, TextSpan.FromBounds(1, 10), 123, new[] { "a" }))), (document.Id, ImmutableArray.Create(new RudeEditDiagnostic(RudeEditKind.Delete, TextSpan.FromBounds(1, 10), 123, new[] { "b" })))); var actual = await EmitSolutionUpdateResults.GetHotReloadDiagnosticsAsync(solution, diagnosticData, rudeEdits, CancellationToken.None); AssertEx.Equal(new[] { $@"Error CS0012: {razorPath} (10,10)-(10,15): error", $@"Error ENC0021: {sourcePath} (0,1)-(0,10): {string.Format(FeaturesResources.Adding_0_requires_restarting_the_application, "a")}", $@"Error ENC0033: {sourcePath} (0,1)-(0,10): {string.Format(FeaturesResources.Deleting_0_requires_restarting_the_application, "b")}" }, actual.Select(d => $"{d.Severity} {d.Id}: {d.FilePath} {d.Span.GetDebuggerDisplay()}: {d.Message}")); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/StaticKeywordRecommenderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations Public Class StaticKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StaticInMethodBodyTest() VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "Static") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StaticInLambdaTest() VerifyRecommendationsContain(<MethodBody> Dim x = Sub() | End Sub</MethodBody>, "Static") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StaticAfterStatementTest() VerifyRecommendationsContain(<MethodBody> Dim x |</MethodBody>, "Static") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StaticNotInsideSingleLineLambdaTest() VerifyRecommendationsMissing(<MethodBody> Dim x = Sub() | </MethodBody>, "Static") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations Public Class StaticKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StaticInMethodBodyTest() VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "Static") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StaticInLambdaTest() VerifyRecommendationsContain(<MethodBody> Dim x = Sub() | End Sub</MethodBody>, "Static") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StaticAfterStatementTest() VerifyRecommendationsContain(<MethodBody> Dim x |</MethodBody>, "Static") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub StaticNotInsideSingleLineLambdaTest() VerifyRecommendationsMissing(<MethodBody> Dim x = Sub() | </MethodBody>, "Static") End Sub End Class End Namespace
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./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
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/VisualBasic/Portable/BoundTree/BoundYieldStatement.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundYieldStatement ''' <summary> ''' Suppresses RValue validation when constructing the node. ''' Must be used _only_ when performing lambda inference where RValue inconsistency on this node is intentionally allowed. ''' If such node makes into a regular bound tree it will be eventually rewritten (all Yields are rewritten at some point) ''' and that will trigger validation. ''' </summary> Friend Sub New(syntax As SyntaxNode, expression As BoundExpression, hasErrors As Boolean, returnTypeIsBeingInferred As Boolean) MyBase.New(BoundKind.YieldStatement, syntax, hasErrors OrElse expression.NonNullAndHasErrors()) Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)") Me._Expression = expression #If DEBUG Then If Not returnTypeIsBeingInferred Then Validate() End If #End If End Sub #If DEBUG Then Private Sub Validate() Expression.AssertRValue() End Sub #End If 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 Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundYieldStatement ''' <summary> ''' Suppresses RValue validation when constructing the node. ''' Must be used _only_ when performing lambda inference where RValue inconsistency on this node is intentionally allowed. ''' If such node makes into a regular bound tree it will be eventually rewritten (all Yields are rewritten at some point) ''' and that will trigger validation. ''' </summary> Friend Sub New(syntax As SyntaxNode, expression As BoundExpression, hasErrors As Boolean, returnTypeIsBeingInferred As Boolean) MyBase.New(BoundKind.YieldStatement, syntax, hasErrors OrElse expression.NonNullAndHasErrors()) Debug.Assert(expression IsNot Nothing, "Field 'expression' cannot be null (use Null=""allow"" in BoundNodes.xml to remove this check)") Me._Expression = expression #If DEBUG Then If Not returnTypeIsBeingInferred Then Validate() End If #End If End Sub #If DEBUG Then Private Sub Validate() Expression.AssertRValue() End Sub #End If End Class End Namespace
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/Core/Impl/CodeModel/GlobalNodeKey.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal struct GlobalNodeKey { public readonly SyntaxNodeKey NodeKey; public readonly SyntaxPath Path; public GlobalNodeKey(SyntaxNodeKey nodeKey, SyntaxPath path) { this.NodeKey = nodeKey; this.Path = path; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal struct GlobalNodeKey { public readonly SyntaxNodeKey NodeKey; public readonly SyntaxPath Path; public GlobalNodeKey(SyntaxNodeKey nodeKey, SyntaxPath path) { this.NodeKey = nodeKey; this.Path = path; } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/Core/Portable/Syntax/SyntaxTriviaList.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a read-only list of <see cref="SyntaxTrivia"/>. /// </summary> [StructLayout(LayoutKind.Auto)] public readonly partial struct SyntaxTriviaList : IEquatable<SyntaxTriviaList>, IReadOnlyList<SyntaxTrivia> { public static SyntaxTriviaList Empty => default(SyntaxTriviaList); internal SyntaxTriviaList(in SyntaxToken token, GreenNode? node, int position, int index = 0) { Token = token; Node = node; Position = position; Index = index; } internal SyntaxTriviaList(in SyntaxToken token, GreenNode? node) { Token = token; Node = node; Position = token.Position; Index = 0; } public SyntaxTriviaList(SyntaxTrivia trivia) { Token = default(SyntaxToken); Node = trivia.UnderlyingNode; Position = 0; Index = 0; } /// <summary> /// Creates a list of trivia. /// </summary> /// <param name="trivias">An array of trivia.</param> public SyntaxTriviaList(params SyntaxTrivia[] trivias) : this(default, CreateNode(trivias), 0, 0) { } /// <summary> /// Creates a list of trivia. /// </summary> /// <param name="trivias">A sequence of trivia.</param> public SyntaxTriviaList(IEnumerable<SyntaxTrivia>? trivias) : this(default, SyntaxTriviaListBuilder.Create(trivias).Node, 0, 0) { } private static GreenNode? CreateNode(SyntaxTrivia[]? trivias) { if (trivias == null) { return null; } var builder = new SyntaxTriviaListBuilder(trivias.Length); builder.Add(trivias); return builder.ToList().Node; } internal SyntaxToken Token { get; } internal GreenNode? Node { get; } internal int Position { get; } internal int Index { get; } public int Count { get { return Node == null ? 0 : (Node.IsList ? Node.SlotCount : 1); } } public SyntaxTrivia ElementAt(int index) { return this[index]; } /// <summary> /// Gets the trivia at the specified index. /// </summary> /// <param name="index">The zero-based index of the trivia to get.</param> /// <returns>The token at the specified index.</returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="index" /> is less than 0.-or-<paramref name="index" /> is equal to or greater than <see cref="Count" />. </exception> public SyntaxTrivia this[int index] { get { if (Node != null) { if (Node.IsList) { if (unchecked((uint)index < (uint)Node.SlotCount)) { return new SyntaxTrivia(Token, Node.GetSlot(index), Position + Node.GetSlotOffset(index), Index + index); } } else if (index == 0) { return new SyntaxTrivia(Token, Node, Position, Index); } } throw new ArgumentOutOfRangeException(nameof(index)); } } /// <summary> /// The absolute span of the list elements in characters, including the leading and trailing trivia of the first and last elements. /// </summary> public TextSpan FullSpan { get { if (Node == null) { return default(TextSpan); } return new TextSpan(this.Position, Node.FullWidth); } } /// <summary> /// The absolute span of the list elements in characters, not including the leading and trailing trivia of the first and last elements. /// </summary> public TextSpan Span { get { if (Node == null) { return default(TextSpan); } return TextSpan.FromBounds(Position + Node.GetLeadingTriviaWidth(), Position + Node.FullWidth - Node.GetTrailingTriviaWidth()); } } /// <summary> /// Returns the first trivia in the list. /// </summary> /// <returns>The first trivia in the list.</returns> /// <exception cref="InvalidOperationException">The list is empty.</exception> public SyntaxTrivia First() { if (Any()) { return this[0]; } throw new InvalidOperationException(); } /// <summary> /// Returns the last trivia in the list. /// </summary> /// <returns>The last trivia in the list.</returns> /// <exception cref="InvalidOperationException">The list is empty.</exception> public SyntaxTrivia Last() { if (Any()) { return this[this.Count - 1]; } throw new InvalidOperationException(); } /// <summary> /// Does this list have any items. /// </summary> public bool Any() { return Node != null; } /// <summary> /// Returns a list which contains all elements of <see cref="SyntaxTriviaList"/> in reversed order. /// </summary> /// <returns><see cref="Reversed"/> which contains all elements of <see cref="SyntaxTriviaList"/> in reversed order</returns> public Reversed Reverse() { return new Reversed(this); } public Enumerator GetEnumerator() { return new Enumerator(in this); } public int IndexOf(SyntaxTrivia triviaInList) { for (int i = 0, n = this.Count; i < n; i++) { var trivia = this[i]; if (trivia == triviaInList) { return i; } } return -1; } internal int IndexOf(int rawKind) { for (int i = 0, n = this.Count; i < n; i++) { if (this[i].RawKind == rawKind) { return i; } } return -1; } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the specified trivia added to the end. /// </summary> /// <param name="trivia">The trivia to add.</param> public SyntaxTriviaList Add(SyntaxTrivia trivia) { return Insert(this.Count, trivia); } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the specified trivia added to the end. /// </summary> /// <param name="trivia">The trivia to add.</param> public SyntaxTriviaList AddRange(IEnumerable<SyntaxTrivia> trivia) { return InsertRange(this.Count, trivia); } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the specified trivia inserted at the index. /// </summary> /// <param name="index">The index in the list to insert the trivia at.</param> /// <param name="trivia">The trivia to insert.</param> public SyntaxTriviaList Insert(int index, SyntaxTrivia trivia) { if (trivia == default(SyntaxTrivia)) { throw new ArgumentOutOfRangeException(nameof(trivia)); } return InsertRange(index, new[] { trivia }); } private static readonly ObjectPool<SyntaxTriviaListBuilder> s_builderPool = new ObjectPool<SyntaxTriviaListBuilder>(() => SyntaxTriviaListBuilder.Create()); private static SyntaxTriviaListBuilder GetBuilder() => s_builderPool.Allocate(); private static void ClearAndFreeBuilder(SyntaxTriviaListBuilder builder) { // It's possible someone might create a list with a huge amount of trivia // in it. We don't want to hold onto such items forever. So only cache // reasonably sized lists. In IDE testing, around 99% of all trivia lists // were 16 or less elements. const int MaxBuilderCount = 16; if (builder.Count <= MaxBuilderCount) { builder.Clear(); s_builderPool.Free(builder); } } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the specified trivia inserted at the index. /// </summary> /// <param name="index">The index in the list to insert the trivia at.</param> /// <param name="trivia">The trivia to insert.</param> public SyntaxTriviaList InsertRange(int index, IEnumerable<SyntaxTrivia> trivia) { var thisCount = this.Count; if (index < 0 || index > thisCount) { throw new ArgumentOutOfRangeException(nameof(index)); } if (trivia == null) { throw new ArgumentNullException(nameof(trivia)); } // Just return ourselves if we're not being asked to add anything. var triviaCollection = trivia as ICollection<SyntaxTrivia>; if (triviaCollection != null && triviaCollection.Count == 0) { return this; } var builder = GetBuilder(); try { for (int i = 0; i < index; i++) { builder.Add(this[i]); } builder.AddRange(trivia); for (int i = index; i < thisCount; i++) { builder.Add(this[i]); } return builder.Count == thisCount ? this : builder.ToList(); } finally { ClearAndFreeBuilder(builder); } } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the element at the specified index removed. /// </summary> /// <param name="index">The index identifying the element to remove.</param> public SyntaxTriviaList RemoveAt(int index) { if (index < 0 || index >= this.Count) { throw new ArgumentOutOfRangeException(nameof(index)); } var list = this.ToList(); list.RemoveAt(index); return new SyntaxTriviaList(default(SyntaxToken), GreenNode.CreateList(list, static n => n.RequiredUnderlyingNode), 0, 0); } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the specified element removed. /// </summary> /// <param name="triviaInList">The trivia element to remove.</param> public SyntaxTriviaList Remove(SyntaxTrivia triviaInList) { var index = this.IndexOf(triviaInList); if (index >= 0 && index < this.Count) { return this.RemoveAt(index); } return this; } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the specified element replaced with new trivia. /// </summary> /// <param name="triviaInList">The trivia element to replace.</param> /// <param name="newTrivia">The trivia to replace the element with.</param> public SyntaxTriviaList Replace(SyntaxTrivia triviaInList, SyntaxTrivia newTrivia) { if (newTrivia == default(SyntaxTrivia)) { throw new ArgumentOutOfRangeException(nameof(newTrivia)); } return ReplaceRange(triviaInList, new[] { newTrivia }); } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the specified element replaced with new trivia. /// </summary> /// <param name="triviaInList">The trivia element to replace.</param> /// <param name="newTrivia">The trivia to replace the element with.</param> public SyntaxTriviaList ReplaceRange(SyntaxTrivia triviaInList, IEnumerable<SyntaxTrivia> newTrivia) { var index = this.IndexOf(triviaInList); if (index >= 0 && index < this.Count) { var list = this.ToList(); list.RemoveAt(index); list.InsertRange(index, newTrivia); return new SyntaxTriviaList(default(SyntaxToken), GreenNode.CreateList(list, static n => n.RequiredUnderlyingNode), 0, 0); } throw new ArgumentOutOfRangeException(nameof(triviaInList)); } // for debugging private SyntaxTrivia[] Nodes => this.ToArray(); IEnumerator<SyntaxTrivia> IEnumerable<SyntaxTrivia>.GetEnumerator() { if (Node == null) { return SpecializedCollections.EmptyEnumerator<SyntaxTrivia>(); } return new EnumeratorImpl(in this); } IEnumerator IEnumerable.GetEnumerator() { if (Node == null) { return SpecializedCollections.EmptyEnumerator<SyntaxTrivia>(); } return new EnumeratorImpl(in this); } /// <summary> /// get the green node at the specific slot /// </summary> private GreenNode? GetGreenNodeAt(int i) { Debug.Assert(Node is object); return GetGreenNodeAt(Node, i); } private static GreenNode? GetGreenNodeAt(GreenNode node, int i) { Debug.Assert(node.IsList || (i == 0 && !node.IsList)); return node.IsList ? node.GetSlot(i) : node; } public bool Equals(SyntaxTriviaList other) { return Node == other.Node && Index == other.Index && Token.Equals(other.Token); } public static bool operator ==(SyntaxTriviaList left, SyntaxTriviaList right) { return left.Equals(right); } public static bool operator !=(SyntaxTriviaList left, SyntaxTriviaList right) { return !left.Equals(right); } public override bool Equals(object? obj) { return (obj is SyntaxTriviaList list) && Equals(list); } public override int GetHashCode() { return Hash.Combine(Token.GetHashCode(), Hash.Combine(Node, Index)); } /// <summary> /// Copy <paramref name="count"/> number of items starting at <paramref name="offset"/> from this list into <paramref name="array"/> starting at <paramref name="arrayOffset"/>. /// </summary> internal void CopyTo(int offset, SyntaxTrivia[] array, int arrayOffset, int count) { if (offset < 0 || count < 0 || this.Count < offset + count) { throw new IndexOutOfRangeException(); } if (count == 0) { return; } // get first one without creating any red node var first = this[offset]; array[arrayOffset] = first; // calculate trivia position from the first ourselves from now on var position = first.Position; var current = first; for (int i = 1; i < count; i++) { position += current.FullWidth; current = new SyntaxTrivia(Token, GetGreenNodeAt(offset + i), position, Index + i); array[arrayOffset + i] = current; } } public override string ToString() { return Node != null ? Node.ToString() : string.Empty; } public string ToFullString() { return Node != null ? Node.ToFullString() : string.Empty; } public static SyntaxTriviaList Create(SyntaxTrivia trivia) { return new SyntaxTriviaList(trivia); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a read-only list of <see cref="SyntaxTrivia"/>. /// </summary> [StructLayout(LayoutKind.Auto)] public readonly partial struct SyntaxTriviaList : IEquatable<SyntaxTriviaList>, IReadOnlyList<SyntaxTrivia> { public static SyntaxTriviaList Empty => default(SyntaxTriviaList); internal SyntaxTriviaList(in SyntaxToken token, GreenNode? node, int position, int index = 0) { Token = token; Node = node; Position = position; Index = index; } internal SyntaxTriviaList(in SyntaxToken token, GreenNode? node) { Token = token; Node = node; Position = token.Position; Index = 0; } public SyntaxTriviaList(SyntaxTrivia trivia) { Token = default(SyntaxToken); Node = trivia.UnderlyingNode; Position = 0; Index = 0; } /// <summary> /// Creates a list of trivia. /// </summary> /// <param name="trivias">An array of trivia.</param> public SyntaxTriviaList(params SyntaxTrivia[] trivias) : this(default, CreateNode(trivias), 0, 0) { } /// <summary> /// Creates a list of trivia. /// </summary> /// <param name="trivias">A sequence of trivia.</param> public SyntaxTriviaList(IEnumerable<SyntaxTrivia>? trivias) : this(default, SyntaxTriviaListBuilder.Create(trivias).Node, 0, 0) { } private static GreenNode? CreateNode(SyntaxTrivia[]? trivias) { if (trivias == null) { return null; } var builder = new SyntaxTriviaListBuilder(trivias.Length); builder.Add(trivias); return builder.ToList().Node; } internal SyntaxToken Token { get; } internal GreenNode? Node { get; } internal int Position { get; } internal int Index { get; } public int Count { get { return Node == null ? 0 : (Node.IsList ? Node.SlotCount : 1); } } public SyntaxTrivia ElementAt(int index) { return this[index]; } /// <summary> /// Gets the trivia at the specified index. /// </summary> /// <param name="index">The zero-based index of the trivia to get.</param> /// <returns>The token at the specified index.</returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="index" /> is less than 0.-or-<paramref name="index" /> is equal to or greater than <see cref="Count" />. </exception> public SyntaxTrivia this[int index] { get { if (Node != null) { if (Node.IsList) { if (unchecked((uint)index < (uint)Node.SlotCount)) { return new SyntaxTrivia(Token, Node.GetSlot(index), Position + Node.GetSlotOffset(index), Index + index); } } else if (index == 0) { return new SyntaxTrivia(Token, Node, Position, Index); } } throw new ArgumentOutOfRangeException(nameof(index)); } } /// <summary> /// The absolute span of the list elements in characters, including the leading and trailing trivia of the first and last elements. /// </summary> public TextSpan FullSpan { get { if (Node == null) { return default(TextSpan); } return new TextSpan(this.Position, Node.FullWidth); } } /// <summary> /// The absolute span of the list elements in characters, not including the leading and trailing trivia of the first and last elements. /// </summary> public TextSpan Span { get { if (Node == null) { return default(TextSpan); } return TextSpan.FromBounds(Position + Node.GetLeadingTriviaWidth(), Position + Node.FullWidth - Node.GetTrailingTriviaWidth()); } } /// <summary> /// Returns the first trivia in the list. /// </summary> /// <returns>The first trivia in the list.</returns> /// <exception cref="InvalidOperationException">The list is empty.</exception> public SyntaxTrivia First() { if (Any()) { return this[0]; } throw new InvalidOperationException(); } /// <summary> /// Returns the last trivia in the list. /// </summary> /// <returns>The last trivia in the list.</returns> /// <exception cref="InvalidOperationException">The list is empty.</exception> public SyntaxTrivia Last() { if (Any()) { return this[this.Count - 1]; } throw new InvalidOperationException(); } /// <summary> /// Does this list have any items. /// </summary> public bool Any() { return Node != null; } /// <summary> /// Returns a list which contains all elements of <see cref="SyntaxTriviaList"/> in reversed order. /// </summary> /// <returns><see cref="Reversed"/> which contains all elements of <see cref="SyntaxTriviaList"/> in reversed order</returns> public Reversed Reverse() { return new Reversed(this); } public Enumerator GetEnumerator() { return new Enumerator(in this); } public int IndexOf(SyntaxTrivia triviaInList) { for (int i = 0, n = this.Count; i < n; i++) { var trivia = this[i]; if (trivia == triviaInList) { return i; } } return -1; } internal int IndexOf(int rawKind) { for (int i = 0, n = this.Count; i < n; i++) { if (this[i].RawKind == rawKind) { return i; } } return -1; } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the specified trivia added to the end. /// </summary> /// <param name="trivia">The trivia to add.</param> public SyntaxTriviaList Add(SyntaxTrivia trivia) { return Insert(this.Count, trivia); } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the specified trivia added to the end. /// </summary> /// <param name="trivia">The trivia to add.</param> public SyntaxTriviaList AddRange(IEnumerable<SyntaxTrivia> trivia) { return InsertRange(this.Count, trivia); } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the specified trivia inserted at the index. /// </summary> /// <param name="index">The index in the list to insert the trivia at.</param> /// <param name="trivia">The trivia to insert.</param> public SyntaxTriviaList Insert(int index, SyntaxTrivia trivia) { if (trivia == default(SyntaxTrivia)) { throw new ArgumentOutOfRangeException(nameof(trivia)); } return InsertRange(index, new[] { trivia }); } private static readonly ObjectPool<SyntaxTriviaListBuilder> s_builderPool = new ObjectPool<SyntaxTriviaListBuilder>(() => SyntaxTriviaListBuilder.Create()); private static SyntaxTriviaListBuilder GetBuilder() => s_builderPool.Allocate(); private static void ClearAndFreeBuilder(SyntaxTriviaListBuilder builder) { // It's possible someone might create a list with a huge amount of trivia // in it. We don't want to hold onto such items forever. So only cache // reasonably sized lists. In IDE testing, around 99% of all trivia lists // were 16 or less elements. const int MaxBuilderCount = 16; if (builder.Count <= MaxBuilderCount) { builder.Clear(); s_builderPool.Free(builder); } } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the specified trivia inserted at the index. /// </summary> /// <param name="index">The index in the list to insert the trivia at.</param> /// <param name="trivia">The trivia to insert.</param> public SyntaxTriviaList InsertRange(int index, IEnumerable<SyntaxTrivia> trivia) { var thisCount = this.Count; if (index < 0 || index > thisCount) { throw new ArgumentOutOfRangeException(nameof(index)); } if (trivia == null) { throw new ArgumentNullException(nameof(trivia)); } // Just return ourselves if we're not being asked to add anything. var triviaCollection = trivia as ICollection<SyntaxTrivia>; if (triviaCollection != null && triviaCollection.Count == 0) { return this; } var builder = GetBuilder(); try { for (int i = 0; i < index; i++) { builder.Add(this[i]); } builder.AddRange(trivia); for (int i = index; i < thisCount; i++) { builder.Add(this[i]); } return builder.Count == thisCount ? this : builder.ToList(); } finally { ClearAndFreeBuilder(builder); } } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the element at the specified index removed. /// </summary> /// <param name="index">The index identifying the element to remove.</param> public SyntaxTriviaList RemoveAt(int index) { if (index < 0 || index >= this.Count) { throw new ArgumentOutOfRangeException(nameof(index)); } var list = this.ToList(); list.RemoveAt(index); return new SyntaxTriviaList(default(SyntaxToken), GreenNode.CreateList(list, static n => n.RequiredUnderlyingNode), 0, 0); } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the specified element removed. /// </summary> /// <param name="triviaInList">The trivia element to remove.</param> public SyntaxTriviaList Remove(SyntaxTrivia triviaInList) { var index = this.IndexOf(triviaInList); if (index >= 0 && index < this.Count) { return this.RemoveAt(index); } return this; } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the specified element replaced with new trivia. /// </summary> /// <param name="triviaInList">The trivia element to replace.</param> /// <param name="newTrivia">The trivia to replace the element with.</param> public SyntaxTriviaList Replace(SyntaxTrivia triviaInList, SyntaxTrivia newTrivia) { if (newTrivia == default(SyntaxTrivia)) { throw new ArgumentOutOfRangeException(nameof(newTrivia)); } return ReplaceRange(triviaInList, new[] { newTrivia }); } /// <summary> /// Creates a new <see cref="SyntaxTriviaList"/> with the specified element replaced with new trivia. /// </summary> /// <param name="triviaInList">The trivia element to replace.</param> /// <param name="newTrivia">The trivia to replace the element with.</param> public SyntaxTriviaList ReplaceRange(SyntaxTrivia triviaInList, IEnumerable<SyntaxTrivia> newTrivia) { var index = this.IndexOf(triviaInList); if (index >= 0 && index < this.Count) { var list = this.ToList(); list.RemoveAt(index); list.InsertRange(index, newTrivia); return new SyntaxTriviaList(default(SyntaxToken), GreenNode.CreateList(list, static n => n.RequiredUnderlyingNode), 0, 0); } throw new ArgumentOutOfRangeException(nameof(triviaInList)); } // for debugging private SyntaxTrivia[] Nodes => this.ToArray(); IEnumerator<SyntaxTrivia> IEnumerable<SyntaxTrivia>.GetEnumerator() { if (Node == null) { return SpecializedCollections.EmptyEnumerator<SyntaxTrivia>(); } return new EnumeratorImpl(in this); } IEnumerator IEnumerable.GetEnumerator() { if (Node == null) { return SpecializedCollections.EmptyEnumerator<SyntaxTrivia>(); } return new EnumeratorImpl(in this); } /// <summary> /// get the green node at the specific slot /// </summary> private GreenNode? GetGreenNodeAt(int i) { Debug.Assert(Node is object); return GetGreenNodeAt(Node, i); } private static GreenNode? GetGreenNodeAt(GreenNode node, int i) { Debug.Assert(node.IsList || (i == 0 && !node.IsList)); return node.IsList ? node.GetSlot(i) : node; } public bool Equals(SyntaxTriviaList other) { return Node == other.Node && Index == other.Index && Token.Equals(other.Token); } public static bool operator ==(SyntaxTriviaList left, SyntaxTriviaList right) { return left.Equals(right); } public static bool operator !=(SyntaxTriviaList left, SyntaxTriviaList right) { return !left.Equals(right); } public override bool Equals(object? obj) { return (obj is SyntaxTriviaList list) && Equals(list); } public override int GetHashCode() { return Hash.Combine(Token.GetHashCode(), Hash.Combine(Node, Index)); } /// <summary> /// Copy <paramref name="count"/> number of items starting at <paramref name="offset"/> from this list into <paramref name="array"/> starting at <paramref name="arrayOffset"/>. /// </summary> internal void CopyTo(int offset, SyntaxTrivia[] array, int arrayOffset, int count) { if (offset < 0 || count < 0 || this.Count < offset + count) { throw new IndexOutOfRangeException(); } if (count == 0) { return; } // get first one without creating any red node var first = this[offset]; array[arrayOffset] = first; // calculate trivia position from the first ourselves from now on var position = first.Position; var current = first; for (int i = 1; i < count; i++) { position += current.FullWidth; current = new SyntaxTrivia(Token, GetGreenNodeAt(offset + i), position, Index + i); array[arrayOffset + i] = current; } } public override string ToString() { return Node != null ? Node.ToString() : string.Empty; } public string ToFullString() { return Node != null ? Node.ToFullString() : string.Empty; } public static SyntaxTriviaList Create(SyntaxTrivia trivia) { return new SyntaxTriviaList(trivia); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenTuples.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.Text 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.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Imports Roslyn.Test.Utilities.TestMetadata Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests <CompilerTrait(CompilerFeature.Tuples)> Public Class CodeGenTuples Inherits BasicTestBase ReadOnly s_valueTupleRefs As MetadataReference() = New MetadataReference() {ValueTupleRef, SystemRuntimeFacadeRef} ReadOnly s_valueTupleRefsAndDefault As MetadataReference() = New MetadataReference() {ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef, SystemRef, SystemCoreRef, MsvbRef} ReadOnly s_trivial2uple As String = " Namespace System Public Structure ValueTuple(Of T1, T2) Public Dim Item1 As T1 Public Dim Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return ""{"" + Item1?.ToString() + "", "" + Item2?.ToString() + ""}"" End Function End Structure End Namespace namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Field Or AttributeTargets.Parameter Or AttributeTargets.Property Or AttributeTargets.ReturnValue Or AttributeTargets.Class Or AttributeTargets.Struct )> public class TupleElementNamesAttribute : Inherits Attribute public Sub New(transformNames As String()) End Sub End Class End Namespace " ReadOnly s_tupleattributes As String = " namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Field Or AttributeTargets.Parameter Or AttributeTargets.Property Or AttributeTargets.ReturnValue Or AttributeTargets.Class Or AttributeTargets.Struct )> public class TupleElementNamesAttribute : Inherits Attribute public Sub New(transformNames As String()) End Sub End Class End Namespace " ReadOnly s_trivial3uple As String = " Namespace System Public Structure ValueTuple(Of T1, T2, T3) Public Dim Item1 As T1 Public Dim Item2 As T2 Public Dim Item3 As T3 Public Sub New(item1 As T1, item2 As T2, item3 As T3) me.Item1 = item1 me.Item2 = item2 me.Item3 = item3 End Sub End Structure End Namespace " ReadOnly s_trivialRemainingTuples As String = " Namespace System Public Structure ValueTuple(Of T1, T2, T3, T4) Public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4) End Sub End Structure Public Structure ValueTuple(Of T1, T2, T3, T4, T5) Public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5) End Sub End Structure Public Structure ValueTuple(Of T1, T2, T3, T4, T5, T6) Public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6) End Sub End Structure Public Structure ValueTuple(Of T1, T2, T3, T4, T5, T6, T7) Public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6, item7 As T7) End Sub End Structure Public Structure ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest) Public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6, item7 As T7, rest As TRest) End Sub End Structure End Namespace " <Fact> Public Sub TupleNamesInArrayInAttribute() Dim comp = CreateCompilation( <compilation> <file name="a.vb"><![CDATA[ Imports System <My(New (String, bob As String)() { })> Public Class MyAttribute Inherits System.Attribute Public Sub New(x As (alice As String, String)()) End Sub End Class ]]></file> </compilation>) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30045: Attribute constructor has a parameter of type '(alice As String, String)()', which is not an integral, floating-point or Enum type or one of Object, Char, String, Boolean, System.Type or 1-dimensional array of these types. <My(New (String, bob As String)() { })> ~~ ]]></errors>) End Sub <Fact> Public Sub TupleTypeBinding() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim t as (Integer, Integer) console.writeline(t) End Sub End Module Namespace System Structure ValueTuple(Of T1, T2) Public Overrides Function ToString() As String Return "hello" End Function End Structure End Namespace </file> </compilation>, expectedOutput:=<![CDATA[ hello ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 .locals init (System.ValueTuple(Of Integer, Integer) V_0) //t IL_0000: ldloc.0 IL_0001: box "System.ValueTuple(Of Integer, Integer)" IL_0006: call "Sub System.Console.WriteLine(Object)" IL_000b: ret } ]]>) End Sub <Fact> Public Sub TupleTypeBindingTypeChar() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> option strict on Imports System Module C Sub Main() Dim t as (A%, B$) = Nothing console.writeline(t.GetType()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.ValueTuple`2[System.Int32,System.String] ]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 25 (0x19) .maxstack 1 .locals init (System.ValueTuple(Of Integer, String) V_0) //t IL_0000: ldloca.s V_0 IL_0002: initobj "System.ValueTuple(Of Integer, String)" IL_0008: ldloc.0 IL_0009: box "System.ValueTuple(Of Integer, String)" IL_000e: call "Function Object.GetType() As System.Type" IL_0013: call "Sub System.Console.WriteLine(Object)" IL_0018: ret } ]]>) End Sub <Fact> Public Sub TupleTypeBindingTypeChar1() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> option strict off Imports System Module C Sub Main() Dim t as (A%, B$) = Nothing console.writeline(t.GetType()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.ValueTuple`2[System.Int32,System.String] ]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 25 (0x19) .maxstack 1 .locals init (System.ValueTuple(Of Integer, String) V_0) //t IL_0000: ldloca.s V_0 IL_0002: initobj "System.ValueTuple(Of Integer, String)" IL_0008: ldloc.0 IL_0009: box "System.ValueTuple(Of Integer, String)" IL_000e: call "Function Object.GetType() As System.Type" IL_0013: call "Sub System.Console.WriteLine(Object)" IL_0018: ret } ]]>) End Sub <Fact> Public Sub TupleTypeBindingTypeCharErr() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim t as (A% As String, B$ As String, C As String$) = nothing console.writeline(t.A.Length) 'A should not take the type from % in this case Dim t1 as (String$, String%) = nothing console.writeline(t1.GetType()) Dim B = 1 Dim t2 = (A% := "qq", B$) console.writeline(t2.A.Length) 'A should not take the type from % in this case Dim t3 As (V1(), V2%()) = Nothing console.writeline(t3.Item1.Length) End Sub Async Sub T() Dim t4 as (Integer% As String, Await As String, Function$) = nothing console.writeline(t4.Integer.Length) console.writeline(t4.Await.Length) console.writeline(t4.Function.Length) Dim t5 as (Function As String, Sub, Junk1 As Junk2 Recovery, Junk4 Junk5) = nothing console.writeline(t4.Function.Length) End Sub class V2 end class End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30302: Type character '%' cannot be used in a declaration with an explicit type. Dim t as (A% As String, B$ As String, C As String$) = nothing ~~ BC30302: Type character '$' cannot be used in a declaration with an explicit type. Dim t as (A% As String, B$ As String, C As String$) = nothing ~~ BC30468: Type declaration characters are not valid in this context. Dim t as (A% As String, B$ As String, C As String$) = nothing ~~~~~~~ BC37262: Tuple element names must be unique. Dim t1 as (String$, String%) = nothing ~~~~~~~ BC37270: Type characters cannot be used in tuple literals. Dim t2 = (A% := "qq", B$) ~~ BC30277: Type character '$' does not match declared data type 'Integer'. Dim t2 = (A% := "qq", B$) ~~ BC30002: Type 'V1' is not defined. Dim t3 As (V1(), V2%()) = Nothing ~~ BC32017: Comma, ')', or a valid expression continuation expected. Dim t3 As (V1(), V2%()) = Nothing ~ BC42356: This async method lacks 'Await' operators and so 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 Sub T() ~ BC30302: Type character '%' cannot be used in a declaration with an explicit type. Dim t4 as (Integer% As String, Await As String, Function$) = nothing ~~~~~~~~ BC30183: Keyword is not valid as an identifier. Dim t4 as (Integer% As String, Await As String, Function$) = nothing ~~~~~ BC30180: Keyword does not name a type. Dim t5 as (Function As String, Sub, Junk1 As Junk2 Recovery, Junk4 Junk5) = nothing ~ BC30180: Keyword does not name a type. Dim t5 as (Function As String, Sub, Junk1 As Junk2 Recovery, Junk4 Junk5) = nothing ~ BC30002: Type 'Junk2' is not defined. Dim t5 as (Function As String, Sub, Junk1 As Junk2 Recovery, Junk4 Junk5) = nothing ~~~~~ BC32017: Comma, ')', or a valid expression continuation expected. Dim t5 as (Function As String, Sub, Junk1 As Junk2 Recovery, Junk4 Junk5) = nothing ~~~~~~~~ BC30002: Type 'Junk4' is not defined. Dim t5 as (Function As String, Sub, Junk1 As Junk2 Recovery, Junk4 Junk5) = nothing ~~~~~ BC32017: Comma, ')', or a valid expression continuation expected. Dim t5 as (Function As String, Sub, Junk1 As Junk2 Recovery, Junk4 Junk5) = nothing ~~~~~ </errors>) End Sub <Fact> Public Sub TupleTypeBindingNoTuple() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim t as (Integer, Integer) console.writeline(t) console.writeline(t.Item1) Dim t1 as (A As Integer, B As Integer) console.writeline(t1) console.writeline(t1.Item1) console.writeline(t1.A) End Sub End Module ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported. Dim t as (Integer, Integer) ~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported. Dim t1 as (A As Integer, B As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Dim t1 as (A As Integer, B As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleDefaultType001() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim t = (Nothing, Nothing) console.writeline(t) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (, ) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 18 (0x12) .maxstack 2 IL_0000: ldnull IL_0001: ldnull IL_0002: newobj "Sub System.ValueTuple(Of Object, Object)..ctor(Object, Object)" IL_0007: box "System.ValueTuple(Of Object, Object)" IL_000c: call "Sub System.Console.WriteLine(Object)" IL_0011: ret } ]]>) End Sub <Fact()> Public Sub TupleDefaultType001err() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim t = (Nothing, Nothing) console.writeline(t) End Sub End Module ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported. Dim t = (Nothing, Nothing) ~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub TupleDefaultType002() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim t1 = ({Nothing}, {Nothing}) console.writeline(t1.GetType()) Dim t2 = {(Nothing, Nothing)} console.writeline(t2.GetType()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.ValueTuple`2[System.Object[],System.Object[]] System.ValueTuple`2[System.Object,System.Object][] ]]>) End Sub <Fact()> Public Sub TupleDefaultType003() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim t3 = Function(){(Nothing, Nothing)} console.writeline(t3.GetType()) Dim t4 = {Function()(Nothing, Nothing)} console.writeline(t4.GetType()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ VB$AnonymousDelegate_0`1[System.ValueTuple`2[System.Object,System.Object][]] VB$AnonymousDelegate_0`1[System.ValueTuple`2[System.Object,System.Object]][] ]]>) End Sub <Fact()> Public Sub TupleDefaultType004() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Test(({Nothing}, {{Nothing}})) Test((Function(x as integer)x, Function(x as Long)x)) End Sub function Test(of T, U)(x as (T, U)) as (U, T) System.Console.WriteLine(GetType(T)) System.Console.WriteLine(GetType(U)) System.Console.WriteLine() return (x.Item2, x.Item1) End Function End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.Object[] System.Object[,] VB$AnonymousDelegate_0`2[System.Int32,System.Int32] VB$AnonymousDelegate_0`2[System.Int64,System.Int64] ]]>) End Sub <Fact()> Public Sub TupleDefaultType005() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Test((Function(x as integer)Function()x, Function(x as Long){({Nothing}, {Nothing})})) End Sub function Test(of T, U)(x as (T, U)) as (U, T) System.Console.WriteLine(GetType(T)) System.Console.WriteLine(GetType(U)) System.Console.WriteLine() return (x.Item2, x.Item1) End Function End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ VB$AnonymousDelegate_0`2[System.Int32,VB$AnonymousDelegate_1`1[System.Int32]] VB$AnonymousDelegate_0`2[System.Int64,System.ValueTuple`2[System.Object[],System.Object[]][]] ]]>) End Sub <Fact()> Public Sub TupleDefaultType006() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Test((Nothing, Nothing), "q") Test((Nothing, "q"), Nothing) Test1("q", (Nothing, Nothing)) Test1(Nothing, ("q", Nothing)) End Sub function Test(of T)(x as (T, T), y as T) as T System.Console.WriteLine(GetType(T)) return y End Function function Test1(of T)(x as T, y as (T, T)) as T System.Console.WriteLine(GetType(T)) return x End Function End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.String System.String System.String System.String ]]>) End Sub <Fact()> Public Sub TupleDefaultType006err() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Test1((Nothing, Nothing), Nothing) Test2(Nothing, (Nothing, Nothing)) End Sub function Test1(of T)(x as (T, T), y as T) as T System.Console.WriteLine(GetType(T)) return y End Function function Test2(of T)(x as T, y as (T, T)) as T System.Console.WriteLine(GetType(T)) return x End Function End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC36645: Data type(s) of the type parameter(s) in method 'Public Function Test1(Of T)(x As (T, T), y As T) As T' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. Test1((Nothing, Nothing), Nothing) ~~~~~ BC36645: Data type(s) of the type parameter(s) in method 'Public Function Test2(Of T)(x As T, y As (T, T)) As T' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. Test2(Nothing, (Nothing, Nothing)) ~~~~~ </errors>) End Sub <Fact()> Public Sub TupleDefaultType007() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim valid As (A as Action, B as Action) = (AddressOf Main, AddressOf Main) Test2(valid) Test2((AddressOf Main, Sub() Main)) End Sub function Test2(of T)(x as (T, T)) as (T, T) System.Console.WriteLine(GetType(T)) return x End Function End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.Action VB$AnonymousDelegate_0 ]]>) End Sub <Fact()> Public Sub TupleDefaultType007err() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x = (AddressOf Main, AddressOf Main) Dim x1 = (Function() Main, Function() Main) Dim x2 = (AddressOf Mai, Function() Mai) Dim x3 = (A := AddressOf Main, B := (D := AddressOf Main, C := AddressOf Main)) Test1((AddressOf Main, Sub() Main)) Test1((AddressOf Main, Function() Main)) Test2((AddressOf Main, Function() Main)) End Sub function Test1(of T)(x as T) as T System.Console.WriteLine(GetType(T)) return x End Function function Test2(of T)(x as (T, T)) as (T, T) System.Console.WriteLine(GetType(T)) return x End Function End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30491: Expression does not produce a value. Dim x = (AddressOf Main, AddressOf Main) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30491: Expression does not produce a value. Dim x1 = (Function() Main, Function() Main) ~~~~ BC30491: Expression does not produce a value. Dim x1 = (Function() Main, Function() Main) ~~~~ BC30451: 'Mai' is not declared. It may be inaccessible due to its protection level. Dim x2 = (AddressOf Mai, Function() Mai) ~~~ BC30491: Expression does not produce a value. Dim x3 = (A := AddressOf Main, B := (D := AddressOf Main, C := AddressOf Main)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36645: Data type(s) of the type parameter(s) in method 'Public Function Test1(Of T)(x As T) As T' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. Test1((AddressOf Main, Sub() Main)) ~~~~~ BC36645: Data type(s) of the type parameter(s) in method 'Public Function Test1(Of T)(x As T) As T' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. Test1((AddressOf Main, Function() Main)) ~~~~~ BC36645: Data type(s) of the type parameter(s) in method 'Public Function Test2(Of T)(x As (T, T)) As (T, T)' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. Test2((AddressOf Main, Function() Main)) ~~~~~ </errors>) End Sub <Fact()> Public Sub DataFlow() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() dim initialized as Object = Nothing dim baseline_literal = (initialized, initialized) dim uninitialized as Object dim literal = (uninitialized, uninitialized) dim uninitialized1 as Exception dim identity_literal as (Alice As Exception, Bob As Exception) = (uninitialized1, uninitialized1) dim uninitialized2 as Exception dim converted_literal as (Object, Object) = (uninitialized2, uninitialized2) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC42104: Variable 'uninitialized' is used before it has been assigned a value. A null reference exception could result at runtime. dim literal = (uninitialized, uninitialized) ~~~~~~~~~~~~~ BC42104: Variable 'uninitialized1' is used before it has been assigned a value. A null reference exception could result at runtime. dim identity_literal as (Alice As Exception, Bob As Exception) = (uninitialized1, uninitialized1) ~~~~~~~~~~~~~~ BC42104: Variable 'uninitialized2' is used before it has been assigned a value. A null reference exception could result at runtime. dim converted_literal as (Object, Object) = (uninitialized2, uninitialized2) ~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleFieldBinding() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim t as (Integer, Integer) t.Item1 = 42 t.Item2 = t.Item1 console.writeline(t.Item2) End Sub End Module Namespace System Structure ValueTuple(Of T1, T2) Public Item1 As T1 Public Item2 As T2 End Structure End Namespace </file> </compilation>, expectedOutput:=<![CDATA[ 42 ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 34 (0x22) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer) V_0) //t IL_0000: ldloca.s V_0 IL_0002: ldc.i4.s 42 IL_0004: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0009: ldloca.s V_0 IL_000b: ldloc.0 IL_000c: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0011: stfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0016: ldloc.0 IL_0017: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_001c: call "Sub System.Console.WriteLine(Integer)" IL_0021: ret } ]]>) End Sub <Fact> Public Sub TupleFieldBinding01() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim vt as ValueTuple(Of Integer, Integer) = M1(2,3) console.writeline(vt.Item2) End Sub Function M1(x As Integer, y As Integer) As ValueTuple(Of Integer, Integer) Return New ValueTuple(Of Integer, Integer)(x, y) End Function End Module </file> </compilation>, expectedOutput:=<![CDATA[ 3 ]]>, references:=s_valueTupleRefs) verifier.VerifyIL("C.M1", <![CDATA[ { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0007: ret } ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 18 (0x12) .maxstack 2 IL_0000: ldc.i4.2 IL_0001: ldc.i4.3 IL_0002: call "Function C.M1(Integer, Integer) As (Integer, Integer)" IL_0007: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_000c: call "Sub System.Console.WriteLine(Integer)" IL_0011: ret } ]]>) End Sub <Fact> Public Sub TupleFieldBindingLong() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim t as (Integer, Integer, Integer, integer, integer, integer, integer, integer, integer, Integer, Integer, String, integer, integer, integer, integer, String, integer) t.Item17 = "hello" t.Item12 = t.Item17 console.writeline(t.Item12) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ hello ]]>, references:=s_valueTupleRefs) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 67 (0x43) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)) V_0) //t IL_0000: ldloca.s V_0 IL_0002: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)).Rest As (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)" IL_0007: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, String, Integer, Integer, (Integer, Integer, String, Integer)).Rest As (Integer, Integer, String, Integer)" IL_000c: ldstr "hello" IL_0011: stfld "System.ValueTuple(Of Integer, Integer, String, Integer).Item3 As String" IL_0016: ldloca.s V_0 IL_0018: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)).Rest As (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)" IL_001d: ldloc.0 IL_001e: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)).Rest As (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)" IL_0023: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, String, Integer, Integer, (Integer, Integer, String, Integer)).Rest As (Integer, Integer, String, Integer)" IL_0028: ldfld "System.ValueTuple(Of Integer, Integer, String, Integer).Item3 As String" IL_002d: stfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, String, Integer, Integer, (Integer, Integer, String, Integer)).Item5 As String" IL_0032: ldloc.0 IL_0033: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)).Rest As (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)" IL_0038: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, String, Integer, Integer, (Integer, Integer, String, Integer)).Item5 As String" IL_003d: call "Sub System.Console.WriteLine(String)" IL_0042: ret } ]]>) End Sub <Fact> Public Sub TupleNamedFieldBinding() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim t As (a As Integer, b As Integer) t.a = 42 t.b = t.a Console.WriteLine(t.b) End Sub End Module Namespace System Structure ValueTuple(Of T1, T2) Public Item1 As T1 Public Item2 As T2 End Structure End Namespace namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Field Or AttributeTargets.Parameter Or AttributeTargets.Property Or AttributeTargets.ReturnValue Or AttributeTargets.Class Or AttributeTargets.Struct )> public class TupleElementNamesAttribute : Inherits Attribute public Sub New(transformNames As String()) End Sub End Class End Namespace </file> </compilation>, expectedOutput:=<![CDATA[ 42 ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 34 (0x22) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer) V_0) //t IL_0000: ldloca.s V_0 IL_0002: ldc.i4.s 42 IL_0004: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0009: ldloca.s V_0 IL_000b: ldloc.0 IL_000c: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0011: stfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0016: ldloc.0 IL_0017: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_001c: call "Sub System.Console.WriteLine(Integer)" IL_0021: ret } ]]>) End Sub <Fact> Public Sub TupleDefaultFieldBinding() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Dim t As (Integer, Integer) = nothing t.Item1 = 42 t.Item2 = t.Item1 Console.WriteLine(t.Item2) Dim t1 = (A:=1, B:=123) Console.WriteLine(t1.B) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 42 123 ]]>, references:=s_valueTupleRefs) verifier.VerifyIL("Module1.Main", <![CDATA[ { // Code size 60 (0x3c) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer) V_0) //t IL_0000: ldloca.s V_0 IL_0002: initobj "System.ValueTuple(Of Integer, Integer)" IL_0008: ldloca.s V_0 IL_000a: ldc.i4.s 42 IL_000c: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0011: ldloca.s V_0 IL_0013: ldloc.0 IL_0014: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0019: stfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_001e: ldloc.0 IL_001f: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0024: call "Sub System.Console.WriteLine(Integer)" IL_0029: ldc.i4.1 IL_002a: ldc.i4.s 123 IL_002c: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0031: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0036: call "Sub System.Console.WriteLine(Integer)" IL_003b: ret } ]]>) End Sub <Fact> Public Sub TupleNamedFieldBindingLong() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim t as (a1 as Integer, a2 as Integer, a3 as Integer, a4 as integer, a5 as integer, a6 as integer, a7 as integer, a8 as integer, a9 as integer, a10 as Integer, a11 as Integer, a12 as Integer, a13 as integer, a14 as integer, a15 as integer, a16 as integer, a17 as integer, a18 as integer) t.a17 = 42 t.a12 = t.a17 console.writeline(t.a12) TestArray() TestNullable() End Sub Sub TestArray() Dim t = New (a1 as Integer, a2 as Integer, a3 as Integer, a4 as integer, a5 as integer, a6 as integer, a7 as integer, a8 as integer, a9 as integer, a10 as Integer, a11 as Integer, a12 as Integer, a13 as integer, a14 as integer, a15 as integer, a16 as integer, a17 as integer, a18 as integer)() {Nothing} t(0).a17 = 42 t(0).a12 = t(0).a17 console.writeline(t(0).a12) End Sub Sub TestNullable() Dim t as New (a1 as Integer, a2 as Integer, a3 as Integer, a4 as integer, a5 as integer, a6 as integer, a7 as integer, a8 as integer, a9 as integer, a10 as Integer, a11 as Integer, a12 as Integer, a13 as integer, a14 as integer, a15 as integer, a16 as integer, a17 as integer, a18 as integer)? console.writeline(t.HasValue) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 42 42 False ]]>, references:=s_valueTupleRefs) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 74 (0x4a) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)) V_0) //t IL_0000: ldloca.s V_0 IL_0002: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)" IL_0007: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer)" IL_000c: ldc.i4.s 42 IL_000e: stfld "System.ValueTuple(Of Integer, Integer, Integer, Integer).Item3 As Integer" IL_0013: ldloca.s V_0 IL_0015: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)" IL_001a: ldloc.0 IL_001b: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)" IL_0020: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer)" IL_0025: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer).Item3 As Integer" IL_002a: stfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer)).Item5 As Integer" IL_002f: ldloc.0 IL_0030: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)" IL_0035: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer)).Item5 As Integer" IL_003a: call "Sub System.Console.WriteLine(Integer)" IL_003f: call "Sub C.TestArray()" IL_0044: call "Sub C.TestNullable()" IL_0049: ret } ]]>) End Sub <Fact> Public Sub TupleNewLongErr() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim t = New (a1 as Integer, a2 as Integer, a3 as Integer, a4 as integer, a5 as integer, a6 as integer, a7 as integer, a8 as integer, a9 as integer, a10 as Integer, a11 as Integer, a12 as String, a13 as integer, a14 as integer, a15 as integer, a16 as integer, a17 as integer, a18 as integer) console.writeline(t.a12.Length) Dim t1 As New (a1 as Integer, a2 as Integer, a3 as Integer, a4 as integer, a5 as integer, a6 as integer, a7 as integer, a8 as integer, a9 as integer, a10 as Integer, a11 as Integer, a12 as String, a13 as integer, a14 as integer, a15 as integer, a16 as integer, a17 as integer, a18 as integer) console.writeline(t1.a12.Length) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) ' should not complain about missing constructor comp.AssertTheseDiagnostics( <errors> BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead. Dim t = New (a1 as Integer, a2 as Integer, a3 as Integer, a4 as integer, ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead. Dim t1 As New (a1 as Integer, a2 as Integer, a3 as Integer, a4 as integer, ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleDisallowedWithNew() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C Dim t1 = New (a1 as Integer, a2 as Integer)() Dim t2 As New (a1 as Integer, a2 as Integer) Sub M() Dim t1 = New (a1 as Integer, a2 as Integer)() Dim t2 As New (a1 as Integer, a2 as Integer) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead. Dim t1 = New (a1 as Integer, a2 as Integer)() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead. Dim t2 As New (a1 as Integer, a2 as Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead. Dim t1 = New (a1 as Integer, a2 as Integer)() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead. Dim t2 As New (a1 as Integer, a2 as Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub ParseNewTuple() Dim comp1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class A Sub Main() Dim x = New (A, A) Dim y = New (A, A)() Dim z = New (x As Integer, A) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp1.AssertTheseDiagnostics(<errors> BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead. Dim x = New (A, A) ~~~~~~ BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead. Dim y = New (A, A)() ~~~~~~ BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead. Dim z = New (x As Integer, A) ~~~~~~~~~~~~~~~~~ </errors>) Dim comp2 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Public Function Bar() As (Alice As (Alice As Integer, Bob As Integer)(), Bob As Integer) ' this is actually ok, since it is an array Return (New(Integer, Integer)() {(4, 5)}, 5) End Function End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp2.AssertNoDiagnostics() End Sub <Fact> Public Sub TupleLiteralBinding() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim t as (Integer, Integer) = (1, 2) console.writeline(t) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ (1, 2) ]]>, references:=s_valueTupleRefs) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 18 (0x12) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0007: box "System.ValueTuple(Of Integer, Integer)" IL_000c: call "Sub System.Console.WriteLine(Object)" IL_0011: ret } ]]>) End Sub <Fact> Public Sub TupleLiteralBindingNamed() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim t = (A := 1, B := "hello") console.writeline(t.B) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ hello ]]>, references:=s_valueTupleRefs) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 22 (0x16) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: ldstr "hello" IL_0006: newobj "Sub System.ValueTuple(Of Integer, String)..ctor(Integer, String)" IL_000b: ldfld "System.ValueTuple(Of Integer, String).Item2 As String" IL_0010: call "Sub System.Console.WriteLine(String)" IL_0015: ret } ]]>) End Sub <Fact> Public Sub TupleLiteralSample() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Threading.Tasks Module Module1 Sub Main() Dim t As (Integer, Integer) = Nothing t.Item1 = 42 t.Item2 = t.Item1 Console.WriteLine(t.Item2) Dim t1 = (A:=1, B:=123) Console.WriteLine(t1.B) Dim numbers = {1, 2, 3, 4} Dim t2 = Tally(numbers).Result System.Console.WriteLine($"Sum: {t2.Sum}, Count: {t2.Count}") End Sub Public Async Function Tally(values As IEnumerable(Of Integer)) As Task(Of (Sum As Integer, Count As Integer)) Dim s = 0, c = 0 For Each n In values s += n c += 1 Next 'Await Task.Yield() Return (Sum:=s, Count:=c) End Function End Module Namespace System Structure ValueTuple(Of T1, T2) Public Item1 As T1 Public Item2 As T2 Sub New(item1 as T1, item2 as T2) Me.Item1 = item1 Me.Item2 = item2 End Sub End Structure End Namespace namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Field Or AttributeTargets.Parameter Or AttributeTargets.Property Or AttributeTargets.ReturnValue Or AttributeTargets.Class Or AttributeTargets.Struct )> public class TupleElementNamesAttribute : Inherits Attribute public Sub New(transformNames As String()) End Sub End Class End Namespace </file> </compilation>, useLatestFramework:=True, expectedOutput:="42 123 Sum: 10, Count: 4") End Sub <Fact> <WorkItem(18762, "https://github.com/dotnet/roslyn/issues/18762")> Public Sub UnnamedTempShouldNotCrashPdbEncoding() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Threading.Tasks Module Module1 Private Async Function DoAllWorkAsync() As Task(Of (FirstValue As String, SecondValue As String)) Return (Nothing, Nothing) End Function End Module </file> </compilation>, references:={ValueTupleRef, SystemRuntimeFacadeRef}, useLatestFramework:=True, options:=TestOptions.DebugDll) End Sub <Fact> Public Sub Overloading001() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module m1 Sub Test(x as (a as integer, b as Integer)) End Sub Sub Test(x as (c as integer, d as Integer)) End Sub End module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37271: 'Public Sub Test(x As (a As Integer, b As Integer))' has multiple definitions with identical signatures with different tuple element names, including 'Public Sub Test(x As (c As Integer, d As Integer))'. Sub Test(x as (a as integer, b as Integer)) ~~~~ </errors>) End Sub <Fact> Public Sub Overloading002() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module m1 Sub Test(x as (integer,Integer)) End Sub Sub Test(x as (a as integer, b as Integer)) End Sub End module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37271: 'Public Sub Test(x As (Integer, Integer))' has multiple definitions with identical signatures with different tuple element names, including 'Public Sub Test(x As (a As Integer, b As Integer))'. Sub Test(x as (integer,Integer)) ~~~~ </errors>) End Sub <Fact> Public Sub SimpleTupleTargetTyped001() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x as (String, String) = (Nothing, Nothing) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (, ) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 28 (0x1c) .maxstack 3 .locals init (System.ValueTuple(Of String, String) V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldnull IL_0003: ldnull IL_0004: call "Sub System.ValueTuple(Of String, String)..ctor(String, String)" IL_0009: ldloca.s V_0 IL_000b: constrained. "System.ValueTuple(Of String, String)" IL_0011: callvirt "Function Object.ToString() As String" IL_0016: call "Sub System.Console.WriteLine(String)" IL_001b: ret } ]]>) Dim comp = verifier.Compilation Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(Nothing, Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Assert.Equal("(System.String, System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(node).Kind) End Sub <Fact> Public Sub SimpleTupleTargetTyped001Err() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x as (A as String, B as String) = (C:=Nothing, D:=Nothing, E:=Nothing) System.Console.WriteLine(x.ToString()) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30311: Value of type '(C As Object, D As Object, E As Object)' cannot be converted to '(A As String, B As String)'. Dim x as (A as String, B as String) = (C:=Nothing, D:=Nothing, E:=Nothing) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub SimpleTupleTargetTyped002() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x as (Func(Of integer), Func(of String)) = (Function() 42, Function() "hi") System.Console.WriteLine((x.Item1(), x.Item2()).ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (42, hi) ]]>) End Sub <Fact> Public Sub SimpleTupleTargetTyped002a() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x as (Func(Of integer), Func(of String)) = (Function() 42, Function() Nothing) System.Console.WriteLine((x.Item1(), x.Item2()).ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (42, ) ]]>) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub SimpleTupleTargetTyped003() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x = CType((Nothing, 1),(String, Byte)) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (, 1) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 28 (0x1c) .maxstack 3 .locals init (System.ValueTuple(Of String, Byte) V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldnull IL_0003: ldc.i4.1 IL_0004: call "Sub System.ValueTuple(Of String, Byte)..ctor(String, Byte)" IL_0009: ldloca.s V_0 IL_000b: constrained. "System.ValueTuple(Of String, Byte)" IL_0011: callvirt "Function Object.ToString() As String" IL_0016: call "Sub System.Console.WriteLine(String)" IL_001b: ret } ]]>) Dim compilation = verifier.Compilation Dim tree = compilation.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of CTypeExpressionSyntax)().Single() Assert.Equal("CType((Nothing, 1),(String, Byte))", node.ToString()) compilation.VerifyOperationTree(node, expectedOperationTree:= <![CDATA[ IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.String, System.Byte)) (Syntax: 'CType((Noth ... ing, Byte))') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.String, System.Byte)) (Syntax: '(Nothing, 1)') NaturalType: null Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ]]>.Value) End Sub <Fact> Public Sub SimpleTupleTargetTyped004() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x = DirectCast((Nothing, 1),(String, String)) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (, 1) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 33 (0x21) .maxstack 3 .locals init (System.ValueTuple(Of String, String) V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldnull IL_0003: ldc.i4.1 IL_0004: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String" IL_0009: call "Sub System.ValueTuple(Of String, String)..ctor(String, String)" IL_000e: ldloca.s V_0 IL_0010: constrained. "System.ValueTuple(Of String, String)" IL_0016: callvirt "Function Object.ToString() As String" IL_001b: call "Sub System.Console.WriteLine(String)" IL_0020: ret } ]]>) End Sub <Fact> Public Sub SimpleTupleTargetTyped005() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim i as integer = 100 Dim x = CType((Nothing, i),(String, byte)) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (, 100) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 32 (0x20) .maxstack 3 .locals init (Integer V_0, //i System.ValueTuple(Of String, Byte) V_1) //x IL_0000: ldc.i4.s 100 IL_0002: stloc.0 IL_0003: ldloca.s V_1 IL_0005: ldnull IL_0006: ldloc.0 IL_0007: conv.ovf.u1 IL_0008: call "Sub System.ValueTuple(Of String, Byte)..ctor(String, Byte)" IL_000d: ldloca.s V_1 IL_000f: constrained. "System.ValueTuple(Of String, Byte)" IL_0015: callvirt "Function Object.ToString() As String" IL_001a: call "Sub System.Console.WriteLine(String)" IL_001f: ret } ]]>) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub SimpleTupleTargetTyped006() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim i as integer = 100 Dim x = DirectCast((Nothing, i),(String, byte)) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (, 100) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 32 (0x20) .maxstack 3 .locals init (Integer V_0, //i System.ValueTuple(Of String, Byte) V_1) //x IL_0000: ldc.i4.s 100 IL_0002: stloc.0 IL_0003: ldloca.s V_1 IL_0005: ldnull IL_0006: ldloc.0 IL_0007: conv.ovf.u1 IL_0008: call "Sub System.ValueTuple(Of String, Byte)..ctor(String, Byte)" IL_000d: ldloca.s V_1 IL_000f: constrained. "System.ValueTuple(Of String, Byte)" IL_0015: callvirt "Function Object.ToString() As String" IL_001a: call "Sub System.Console.WriteLine(String)" IL_001f: ret } ]]>) Dim compilation = verifier.Compilation Dim tree = compilation.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of DirectCastExpressionSyntax)().Single() Assert.Equal("DirectCast((Nothing, i),(String, byte))", node.ToString()) compilation.VerifyOperationTree(node, expectedOperationTree:= <![CDATA[ IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.String, System.Byte)) (Syntax: 'DirectCast( ... ing, byte))') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.String, i As System.Byte)) (Syntax: '(Nothing, i)') NaturalType: null Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') ]]>.Value) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub SimpleTupleTargetTyped007() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim i as integer = 100 Dim x = TryCast((Nothing, i),(String, byte)) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (, 100) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 32 (0x20) .maxstack 3 .locals init (Integer V_0, //i System.ValueTuple(Of String, Byte) V_1) //x IL_0000: ldc.i4.s 100 IL_0002: stloc.0 IL_0003: ldloca.s V_1 IL_0005: ldnull IL_0006: ldloc.0 IL_0007: conv.ovf.u1 IL_0008: call "Sub System.ValueTuple(Of String, Byte)..ctor(String, Byte)" IL_000d: ldloca.s V_1 IL_000f: constrained. "System.ValueTuple(Of String, Byte)" IL_0015: callvirt "Function Object.ToString() As String" IL_001a: call "Sub System.Console.WriteLine(String)" IL_001f: ret } ]]>) Dim compilation = verifier.Compilation Dim tree = compilation.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of TryCastExpressionSyntax)().Single() Assert.Equal("TryCast((Nothing, i),(String, byte))", node.ToString()) compilation.VerifyOperationTree(node, expectedOperationTree:= <![CDATA[ IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.String, System.Byte)) (Syntax: 'TryCast((No ... ing, byte))') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.String, i As System.Byte)) (Syntax: '(Nothing, i)') NaturalType: null Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') ]]>.Value) Dim model = compilation.GetSemanticModel(tree) Dim typeInfo = model.GetTypeInfo(node.Expression) Assert.Null(typeInfo.Type) Assert.Equal("(System.String, i As System.Byte)", typeInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(node.Expression).Kind) End Sub <Fact> Public Sub TupleConversionWidening() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim i as (x as byte, y as byte) = (a:=100, b:=100) Dim x as (integer, double) = i System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (100, 100) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Double) V_0, //x System.ValueTuple(Of Byte, Byte) V_1) IL_0000: ldc.i4.s 100 IL_0002: ldc.i4.s 100 IL_0004: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)" IL_0009: stloc.1 IL_000a: ldloc.1 IL_000b: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_0010: ldloc.1 IL_0011: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_0016: conv.r8 IL_0017: newobj "Sub System.ValueTuple(Of Integer, Double)..ctor(Integer, Double)" IL_001c: stloc.0 IL_001d: ldloca.s V_0 IL_001f: constrained. "System.ValueTuple(Of Integer, Double)" IL_0025: callvirt "Function Object.ToString() As String" IL_002a: call "Sub System.Console.WriteLine(String)" IL_002f: ret } ]]>) Dim comp = verifier.Compilation Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(a:=100, b:=100)", node.ToString()) Assert.Equal("(a As Integer, b As Integer)", model.GetTypeInfo(node).Type.ToDisplayString()) Assert.Equal("(x As System.Byte, y As System.Byte)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) End Sub <Fact> Public Sub TupleConversionNarrowing() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim i as (Integer, String) = (100, 100) Dim x as (Byte, Byte) = i System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (100, 100) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 58 (0x3a) .maxstack 2 .locals init (System.ValueTuple(Of Byte, Byte) V_0, //x System.ValueTuple(Of Integer, String) V_1) IL_0000: ldc.i4.s 100 IL_0002: ldc.i4.s 100 IL_0004: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String" IL_0009: newobj "Sub System.ValueTuple(Of Integer, String)..ctor(Integer, String)" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldfld "System.ValueTuple(Of Integer, String).Item1 As Integer" IL_0015: conv.ovf.u1 IL_0016: ldloc.1 IL_0017: ldfld "System.ValueTuple(Of Integer, String).Item2 As String" IL_001c: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToByte(String) As Byte" IL_0021: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)" IL_0026: stloc.0 IL_0027: ldloca.s V_0 IL_0029: constrained. "System.ValueTuple(Of Byte, Byte)" IL_002f: callvirt "Function Object.ToString() As String" IL_0034: call "Sub System.Console.WriteLine(String)" IL_0039: ret } ]]>) Dim comp = verifier.Compilation Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(100, 100)", node.ToString()) Assert.Equal("(Integer, Integer)", model.GetTypeInfo(node).Type.ToDisplayString()) Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.NarrowingTuple, model.GetConversion(node).Kind) End Sub <Fact> Public Sub TupleConversionNarrowingUnchecked() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim i as (Integer, String) = (100, 100) Dim x as (Byte, Byte) = i System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), expectedOutput:=<![CDATA[ (100, 100) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 58 (0x3a) .maxstack 2 .locals init (System.ValueTuple(Of Byte, Byte) V_0, //x System.ValueTuple(Of Integer, String) V_1) IL_0000: ldc.i4.s 100 IL_0002: ldc.i4.s 100 IL_0004: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String" IL_0009: newobj "Sub System.ValueTuple(Of Integer, String)..ctor(Integer, String)" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldfld "System.ValueTuple(Of Integer, String).Item1 As Integer" IL_0015: conv.u1 IL_0016: ldloc.1 IL_0017: ldfld "System.ValueTuple(Of Integer, String).Item2 As String" IL_001c: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToByte(String) As Byte" IL_0021: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)" IL_0026: stloc.0 IL_0027: ldloca.s V_0 IL_0029: constrained. "System.ValueTuple(Of Byte, Byte)" IL_002f: callvirt "Function Object.ToString() As String" IL_0034: call "Sub System.Console.WriteLine(String)" IL_0039: ret } ]]>) End Sub <Fact> Public Sub TupleConversionObject() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim i as (object, object) = (1, (2,3)) Dim x as (integer, (integer, integer)) = ctype(i, (integer, (integer, integer))) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (1, (2, 3)) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 86 (0x56) .maxstack 3 .locals init (System.ValueTuple(Of Integer, (Integer, Integer)) V_0, //x System.ValueTuple(Of Object, Object) V_1, System.ValueTuple(Of Integer, Integer) V_2) IL_0000: ldc.i4.1 IL_0001: box "Integer" IL_0006: ldc.i4.2 IL_0007: ldc.i4.3 IL_0008: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_000d: box "System.ValueTuple(Of Integer, Integer)" IL_0012: newobj "Sub System.ValueTuple(Of Object, Object)..ctor(Object, Object)" IL_0017: stloc.1 IL_0018: ldloc.1 IL_0019: ldfld "System.ValueTuple(Of Object, Object).Item1 As Object" IL_001e: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_0023: ldloc.1 IL_0024: ldfld "System.ValueTuple(Of Object, Object).Item2 As Object" IL_0029: dup IL_002a: brtrue.s IL_0038 IL_002c: pop IL_002d: ldloca.s V_2 IL_002f: initobj "System.ValueTuple(Of Integer, Integer)" IL_0035: ldloc.2 IL_0036: br.s IL_003d IL_0038: unbox.any "System.ValueTuple(Of Integer, Integer)" IL_003d: newobj "Sub System.ValueTuple(Of Integer, (Integer, Integer))..ctor(Integer, (Integer, Integer))" IL_0042: stloc.0 IL_0043: ldloca.s V_0 IL_0045: constrained. "System.ValueTuple(Of Integer, (Integer, Integer))" IL_004b: callvirt "Function Object.ToString() As String" IL_0050: call "Sub System.Console.WriteLine(String)" IL_0055: ret } ]]>) End Sub <Fact> Public Sub TupleConversionOverloadResolution() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim b as (byte, byte) = (100, 100) Test(b) Dim i as (integer, integer) = b Test(i) Dim l as (Long, integer) = b Test(l) End Sub Sub Test(x as (integer, integer)) System.Console.Writeline("integer") End SUb Sub Test(x as (Long, Long)) System.Console.Writeline("long") End SUb End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ integer integer long ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 101 (0x65) .maxstack 3 .locals init (System.ValueTuple(Of Byte, Byte) V_0, System.ValueTuple(Of Long, Integer) V_1) IL_0000: ldc.i4.s 100 IL_0002: ldc.i4.s 100 IL_0004: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)" IL_0009: dup IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_0011: ldloc.0 IL_0012: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_0017: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_001c: call "Sub C.Test((Integer, Integer))" IL_0021: dup IL_0022: stloc.0 IL_0023: ldloc.0 IL_0024: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_0029: ldloc.0 IL_002a: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_002f: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0034: call "Sub C.Test((Integer, Integer))" IL_0039: stloc.0 IL_003a: ldloc.0 IL_003b: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_0040: conv.u8 IL_0041: ldloc.0 IL_0042: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_0047: newobj "Sub System.ValueTuple(Of Long, Integer)..ctor(Long, Integer)" IL_004c: stloc.1 IL_004d: ldloc.1 IL_004e: ldfld "System.ValueTuple(Of Long, Integer).Item1 As Long" IL_0053: ldloc.1 IL_0054: ldfld "System.ValueTuple(Of Long, Integer).Item2 As Integer" IL_0059: conv.i8 IL_005a: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)" IL_005f: call "Sub C.Test((Long, Long))" IL_0064: ret } ]]>) End Sub <Fact> Public Sub TupleConversionNullable001() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim i as (x as byte, y as byte)? = (a:=100, b:=100) Dim x as (integer, double) = CType(i, (integer, double)) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (100, 100) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 62 (0x3e) .maxstack 3 .locals init ((x As Byte, y As Byte)? V_0, //i System.ValueTuple(Of Integer, Double) V_1, //x System.ValueTuple(Of Byte, Byte) V_2) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.s 100 IL_0004: ldc.i4.s 100 IL_0006: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)" IL_000b: call "Sub (x As Byte, y As Byte)?..ctor((x As Byte, y As Byte))" IL_0010: ldloca.s V_0 IL_0012: call "Function (x As Byte, y As Byte)?.get_Value() As (x As Byte, y As Byte)" IL_0017: stloc.2 IL_0018: ldloc.2 IL_0019: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_001e: ldloc.2 IL_001f: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_0024: conv.r8 IL_0025: newobj "Sub System.ValueTuple(Of Integer, Double)..ctor(Integer, Double)" IL_002a: stloc.1 IL_002b: ldloca.s V_1 IL_002d: constrained. "System.ValueTuple(Of Integer, Double)" IL_0033: callvirt "Function Object.ToString() As String" IL_0038: call "Sub System.Console.WriteLine(String)" IL_003d: ret } ]]>) End Sub <Fact> Public Sub TupleConversionNullable002() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim i as (x as byte, y as byte) = (a:=100, b:=100) Dim x as (integer, double)? = CType(i, (integer, double)) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (100, 100) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 57 (0x39) .maxstack 3 .locals init (System.ValueTuple(Of Byte, Byte) V_0, //i (Integer, Double)? V_1, //x System.ValueTuple(Of Byte, Byte) V_2) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.s 100 IL_0004: ldc.i4.s 100 IL_0006: call "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)" IL_000b: ldloca.s V_1 IL_000d: ldloc.0 IL_000e: stloc.2 IL_000f: ldloc.2 IL_0010: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_0015: ldloc.2 IL_0016: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_001b: conv.r8 IL_001c: newobj "Sub System.ValueTuple(Of Integer, Double)..ctor(Integer, Double)" IL_0021: call "Sub (Integer, Double)?..ctor((Integer, Double))" IL_0026: ldloca.s V_1 IL_0028: constrained. "(Integer, Double)?" IL_002e: callvirt "Function Object.ToString() As String" IL_0033: call "Sub System.Console.WriteLine(String)" IL_0038: ret } ]]>) End Sub <Fact> Public Sub TupleConversionNullable003() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim i as (x as byte, y as byte)? = (a:=100, b:=100) Dim x = CType(i, (integer, double)?) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (100, 100) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 87 (0x57) .maxstack 3 .locals init ((x As Byte, y As Byte)? V_0, //i (Integer, Double)? V_1, //x (Integer, Double)? V_2, System.ValueTuple(Of Byte, Byte) V_3) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.s 100 IL_0004: ldc.i4.s 100 IL_0006: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)" IL_000b: call "Sub (x As Byte, y As Byte)?..ctor((x As Byte, y As Byte))" IL_0010: ldloca.s V_0 IL_0012: call "Function (x As Byte, y As Byte)?.get_HasValue() As Boolean" IL_0017: brtrue.s IL_0024 IL_0019: ldloca.s V_2 IL_001b: initobj "(Integer, Double)?" IL_0021: ldloc.2 IL_0022: br.s IL_0043 IL_0024: ldloca.s V_0 IL_0026: call "Function (x As Byte, y As Byte)?.GetValueOrDefault() As (x As Byte, y As Byte)" IL_002b: stloc.3 IL_002c: ldloc.3 IL_002d: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_0032: ldloc.3 IL_0033: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_0038: conv.r8 IL_0039: newobj "Sub System.ValueTuple(Of Integer, Double)..ctor(Integer, Double)" IL_003e: newobj "Sub (Integer, Double)?..ctor((Integer, Double))" IL_0043: stloc.1 IL_0044: ldloca.s V_1 IL_0046: constrained. "(Integer, Double)?" IL_004c: callvirt "Function Object.ToString() As String" IL_0051: call "Sub System.Console.WriteLine(String)" IL_0056: ret } ]]>) End Sub <Fact> Public Sub TupleConversionNullable004() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim i as ValueTuple(of byte, byte)? = (a:=100, b:=100) Dim x = CType(i, ValueTuple(of integer, double)?) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (100, 100) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 87 (0x57) .maxstack 3 .locals init ((Byte, Byte)? V_0, //i (Integer, Double)? V_1, //x (Integer, Double)? V_2, System.ValueTuple(Of Byte, Byte) V_3) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.s 100 IL_0004: ldc.i4.s 100 IL_0006: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)" IL_000b: call "Sub (Byte, Byte)?..ctor((Byte, Byte))" IL_0010: ldloca.s V_0 IL_0012: call "Function (Byte, Byte)?.get_HasValue() As Boolean" IL_0017: brtrue.s IL_0024 IL_0019: ldloca.s V_2 IL_001b: initobj "(Integer, Double)?" IL_0021: ldloc.2 IL_0022: br.s IL_0043 IL_0024: ldloca.s V_0 IL_0026: call "Function (Byte, Byte)?.GetValueOrDefault() As (Byte, Byte)" IL_002b: stloc.3 IL_002c: ldloc.3 IL_002d: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_0032: ldloc.3 IL_0033: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_0038: conv.r8 IL_0039: newobj "Sub System.ValueTuple(Of Integer, Double)..ctor(Integer, Double)" IL_003e: newobj "Sub (Integer, Double)?..ctor((Integer, Double))" IL_0043: stloc.1 IL_0044: ldloca.s V_1 IL_0046: constrained. "(Integer, Double)?" IL_004c: callvirt "Function Object.ToString() As String" IL_0051: call "Sub System.Console.WriteLine(String)" IL_0056: ret } ]]>) End Sub <Fact> Public Sub ImplicitConversions02() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x = (a:=1, b:=1) Dim y As C1 = x x = y System.Console.WriteLine(x) x = CType(CType(x, C1), (integer, integer)) System.Console.WriteLine(x) End Sub End Module Class C1 Public Shared Widening Operator CType(arg as (long, long)) as C1 return new C1() End Operator Public Shared Widening Operator CType(arg as C1) as (c As Byte, d as Byte) return (2, 2) End Operator End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (2, 2) (2, 2) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 125 (0x7d) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer) V_0, System.ValueTuple(Of Byte, Byte) V_1) IL_0000: ldc.i4.1 IL_0001: ldc.i4.1 IL_0002: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_000e: conv.i8 IL_000f: ldloc.0 IL_0010: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0015: conv.i8 IL_0016: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)" IL_001b: call "Function C1.op_Implicit((Long, Long)) As C1" IL_0020: call "Function C1.op_Implicit(C1) As (c As Byte, d As Byte)" IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_002c: ldloc.1 IL_002d: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_0032: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0037: dup IL_0038: box "System.ValueTuple(Of Integer, Integer)" IL_003d: call "Sub System.Console.WriteLine(Object)" IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0049: conv.i8 IL_004a: ldloc.0 IL_004b: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0050: conv.i8 IL_0051: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)" IL_0056: call "Function C1.op_Implicit((Long, Long)) As C1" IL_005b: call "Function C1.op_Implicit(C1) As (c As Byte, d As Byte)" IL_0060: stloc.1 IL_0061: ldloc.1 IL_0062: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_0067: ldloc.1 IL_0068: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_006d: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0072: box "System.ValueTuple(Of Integer, Integer)" IL_0077: call "Sub System.Console.WriteLine(Object)" IL_007c: ret } ]]>) End Sub <Fact> Public Sub ExplicitConversions02() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x = (a:=1, b:=1) Dim y As C1 = CType(x, C1) x = CTYpe(y, (integer, integer)) System.Console.WriteLine(x) x = CType(CType(x, C1), (integer, integer)) System.Console.WriteLine(x) End Sub End Module Class C1 Public Shared Narrowing Operator CType(arg as (long, long)) as C1 return new C1() End Operator Public Shared Narrowing Operator CType(arg as C1) as (c As Byte, d as Byte) return (2, 2) End Operator End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (2, 2) (2, 2) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 125 (0x7d) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer) V_0, System.ValueTuple(Of Byte, Byte) V_1) IL_0000: ldc.i4.1 IL_0001: ldc.i4.1 IL_0002: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_000e: conv.i8 IL_000f: ldloc.0 IL_0010: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0015: conv.i8 IL_0016: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)" IL_001b: call "Function C1.op_Explicit((Long, Long)) As C1" IL_0020: call "Function C1.op_Explicit(C1) As (c As Byte, d As Byte)" IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_002c: ldloc.1 IL_002d: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_0032: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0037: dup IL_0038: box "System.ValueTuple(Of Integer, Integer)" IL_003d: call "Sub System.Console.WriteLine(Object)" IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0049: conv.i8 IL_004a: ldloc.0 IL_004b: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0050: conv.i8 IL_0051: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)" IL_0056: call "Function C1.op_Explicit((Long, Long)) As C1" IL_005b: call "Function C1.op_Explicit(C1) As (c As Byte, d As Byte)" IL_0060: stloc.1 IL_0061: ldloc.1 IL_0062: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_0067: ldloc.1 IL_0068: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_006d: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0072: box "System.ValueTuple(Of Integer, Integer)" IL_0077: call "Sub System.Console.WriteLine(Object)" IL_007c: ret } ]]>) End Sub <Fact> Public Sub ImplicitConversions03() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x = (a:=1, b:=1) Dim y As C1 = x Dim x1 as (integer, integer)? = y System.Console.WriteLine(x1) x1 = CType(CType(x, C1), (integer, integer)?) System.Console.WriteLine(x1) End Sub End Module Class C1 Public Shared Widening Operator CType(arg as (long, long)) as C1 return new C1() End Operator Public Shared Widening Operator CType(arg as C1) as (c As Byte, d as Byte) return (2, 2) End Operator End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (2, 2) (2, 2) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 140 (0x8c) .maxstack 3 .locals init (System.ValueTuple(Of Integer, Integer) V_0, //x C1 V_1, //y System.ValueTuple(Of Integer, Integer) V_2, System.ValueTuple(Of Byte, Byte) V_3) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.1 IL_0004: call "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0009: ldloc.0 IL_000a: stloc.2 IL_000b: ldloc.2 IL_000c: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0011: conv.i8 IL_0012: ldloc.2 IL_0013: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0018: conv.i8 IL_0019: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)" IL_001e: call "Function C1.op_Implicit((Long, Long)) As C1" IL_0023: stloc.1 IL_0024: ldloc.1 IL_0025: call "Function C1.op_Implicit(C1) As (c As Byte, d As Byte)" IL_002a: stloc.3 IL_002b: ldloc.3 IL_002c: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_0031: ldloc.3 IL_0032: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_0037: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_003c: newobj "Sub (Integer, Integer)?..ctor((Integer, Integer))" IL_0041: box "(Integer, Integer)?" IL_0046: call "Sub System.Console.WriteLine(Object)" IL_004b: ldloc.0 IL_004c: stloc.2 IL_004d: ldloc.2 IL_004e: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0053: conv.i8 IL_0054: ldloc.2 IL_0055: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_005a: conv.i8 IL_005b: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)" IL_0060: call "Function C1.op_Implicit((Long, Long)) As C1" IL_0065: call "Function C1.op_Implicit(C1) As (c As Byte, d As Byte)" IL_006a: stloc.3 IL_006b: ldloc.3 IL_006c: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_0071: ldloc.3 IL_0072: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_0077: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_007c: newobj "Sub (Integer, Integer)?..ctor((Integer, Integer))" IL_0081: box "(Integer, Integer)?" IL_0086: call "Sub System.Console.WriteLine(Object)" IL_008b: ret } ]]>) End Sub <Fact> Public Sub ImplicitConversions04() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x = (1, (1, (1, (1, (1, (1, 1)))))) Dim y as C1 = x Dim x2 as (integer, integer) = y System.Console.WriteLine(x2) Dim x3 as (integer, (integer, integer)) = y System.Console.WriteLine(x3) Dim x12 as (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, Integer))))))))))) = y System.Console.WriteLine(x12) End Sub End Module Class C1 Private x as Byte Public Shared Widening Operator CType(arg as (long, C1)) as C1 Dim result = new C1() result.x = arg.Item2.x return result End Operator Public Shared Widening Operator CType(arg as (long, long)) as C1 Dim result = new C1() result.x = CByte(arg.Item2) return result End Operator Public Shared Widening Operator CType(arg as C1) as (c As Byte, d as C1) Dim t = arg.x arg.x += 1 return (CByte(t), arg) End Operator Public Shared Widening Operator CType(arg as C1) as (c As Byte, d as Byte) Dim t1 = arg.x arg.x += 1 Dim t2 = arg.x arg.x += 1 return (CByte(t1), CByte(t2)) End Operator End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (1, 2) (3, (4, 5)) (6, (7, (8, (9, (10, (11, (12, (13, (14, (15, (16, 17))))))))))) ]]>) End Sub <Fact> Public Sub ExplicitConversions04() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x = (1, (1, (1, (1, (1, (1, 1)))))) Dim y as C1 = x Dim x2 as (integer, integer) = y System.Console.WriteLine(x2) Dim x3 as (integer, (integer, integer)) = y System.Console.WriteLine(x3) Dim x12 as (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, Integer))))))))))) = y System.Console.WriteLine(x12) End Sub End Module Class C1 Private x as Byte Public Shared Narrowing Operator CType(arg as (long, C1)) as C1 Dim result = new C1() result.x = arg.Item2.x return result End Operator Public Shared Narrowing Operator CType(arg as (long, long)) as C1 Dim result = new C1() result.x = CByte(arg.Item2) return result End Operator Public Shared Narrowing Operator CType(arg as C1) as (c As Byte, d as C1) Dim t = arg.x arg.x += 1 return (CByte(t), arg) End Operator Public Shared Narrowing Operator CType(arg as C1) as (c As Byte, d as Byte) Dim t1 = arg.x arg.x += 1 Dim t2 = arg.x arg.x += 1 return (CByte(t1), CByte(t2)) End Operator End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (1, 2) (3, (4, 5)) (6, (7, (8, (9, (10, (11, (12, (13, (14, (15, (16, 17))))))))))) ]]>) End Sub <Fact> Public Sub NarrowingFromNumericConstant_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class C Shared Sub Main() Dim x1 As Byte = 300 Dim x2 As Byte() = { 300 } Dim x3 As (Byte, Byte) = (300, 300) Dim x4 As Byte? = 300 Dim x5 As Byte?() = { 300 } Dim x6 As (Byte?, Byte?) = (300, 300) Dim x7 As (Byte, Byte)? = (300, 300) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected></expected>) End Sub <Fact> Public Sub NarrowingFromNumericConstant_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Public Class C Shared Sub M1 (x as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M1 (x as Short) System.Console.WriteLine("Short") End Sub Shared Sub M2 (x as Byte(), y as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M2 (x as Byte(), y as Short) System.Console.WriteLine("Short") End Sub Shared Sub M3 (x as (Byte, Byte)) System.Console.WriteLine("Byte") End Sub Shared Sub M3 (x as (Short, Short)) System.Console.WriteLine("Short") End Sub Shared Sub M4 (x as (Byte, Byte), y as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M4 (x as (Byte, Byte), y as Short) System.Console.WriteLine("Short") End Sub Shared Sub M5 (x as Byte?) System.Console.WriteLine("Byte") End Sub Shared Sub M5 (x as Short?) System.Console.WriteLine("Short") End Sub Shared Sub M6 (x as (Byte?, Byte?)) System.Console.WriteLine("Byte") End Sub Shared Sub M6 (x as (Short?, Short?)) System.Console.WriteLine("Short") End Sub Shared Sub M7 (x as (Byte, Byte)?) System.Console.WriteLine("Byte") End Sub Shared Sub M7 (x as (Short, Short)?) System.Console.WriteLine("Short") End Sub Shared Sub M8 (x as (Byte, Byte)?, y as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M8 (x as (Byte, Byte)?, y as Short) System.Console.WriteLine("Short") End Sub Shared Sub Main() M1(70000) M2({ 300 }, 70000) M3((70000, 70000)) M4((300, 300), 70000) M5(70000) M6((70000, 70000)) M7((70000, 70000)) M8((300, 300), 70000) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected></expected>) CompileAndVerify(comp, expectedOutput:= "Byte Byte Byte Byte Byte Byte Byte Byte") End Sub <Fact> Public Sub NarrowingFromNumericConstant_03() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class C Shared Sub M1 (x as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M1 (x as Short) System.Console.WriteLine("Short") End Sub Shared Sub M2 (x as Byte(), y as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M2 (x as Byte(), y as Short) System.Console.WriteLine("Short") End Sub Shared Sub M3 (x as (Byte, Byte)) System.Console.WriteLine("Byte") End Sub Shared Sub M3 (x as (Short, Short)) System.Console.WriteLine("Short") End Sub Shared Sub M4 (x as (Byte, Byte), y as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M4 (x as (Byte, Byte), y as Short) System.Console.WriteLine("Short") End Sub Shared Sub M5 (x as Byte?) System.Console.WriteLine("Byte") End Sub Shared Sub M5 (x as Short?) System.Console.WriteLine("Short") End Sub Shared Sub M6 (x as (Byte?, Byte?)) System.Console.WriteLine("Byte") End Sub Shared Sub M6 (x as (Short?, Short?)) System.Console.WriteLine("Short") End Sub Shared Sub M7 (x as (Byte, Byte)?) System.Console.WriteLine("Byte") End Sub Shared Sub M7 (x as (Short, Short)?) System.Console.WriteLine("Short") End Sub Shared Sub M8 (x as (Byte, Byte)?, y as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M8 (x as (Byte, Byte)?, y as Short) System.Console.WriteLine("Short") End Sub Shared Sub Main() M1(70000) M2({ 300 }, 70000) M3((70000, 70000)) M4((300, 300), 70000) M5(70000) M6((70000, 70000)) M7((70000, 70000)) M8((300, 300), 70000) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected></expected>) CompileAndVerify(comp, expectedOutput:= "Byte Byte Byte Byte Byte Byte Byte Byte") End Sub <Fact> Public Sub NarrowingFromNumericConstant_04() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Public Class C Shared Sub M1 (x as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M1 (x as Integer) System.Console.WriteLine("Integer") End Sub Shared Sub M2 (x as Byte?) System.Console.WriteLine("Byte") End Sub Shared Sub M2 (x as Integer?) System.Console.WriteLine("Integer") End Sub Shared Sub M3 (x as Byte()) System.Console.WriteLine("Byte") End Sub Shared Sub M3 (x as Integer()) System.Console.WriteLine("Integer") End Sub Shared Sub M4 (x as (Byte, Byte)) System.Console.WriteLine("Byte") End Sub Shared Sub M4 (x as (Integer, Integer)) System.Console.WriteLine("Integer") End Sub Shared Sub M5 (x as (Byte?, Byte?)) System.Console.WriteLine("Byte") End Sub Shared Sub M5 (x as (Integer?, Integer?)) System.Console.WriteLine("Integer") End Sub Shared Sub M6 (x as (Byte, Byte)?) System.Console.WriteLine("Byte") End Sub Shared Sub M6 (x as (Integer, Integer)?) System.Console.WriteLine("Integer") End Sub Shared Sub M7 (x as (Byte, Byte)()) System.Console.WriteLine("Byte") End Sub Shared Sub M7 (x as (Integer, Integer)()) System.Console.WriteLine("Integer") End Sub Shared Sub Main() M1(1) M2(1) M3({1}) M4((1, 1)) M5((1, 1)) M6((1, 1)) M7({(1, 1)}) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(True), additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected></expected>) CompileAndVerify(comp, expectedOutput:= "Integer Integer Integer Integer Integer Integer Integer") End Sub <Fact> Public Sub NarrowingFromNumericConstant_05() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Public Class C Shared Sub M1 (x as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M1 (x as Long) System.Console.WriteLine("Long") End Sub Shared Sub M2 (x as Byte?) System.Console.WriteLine("Byte") End Sub Shared Sub M2 (x as Long?) System.Console.WriteLine("Long") End Sub Shared Sub M3 (x as Byte()) System.Console.WriteLine("Byte") End Sub Shared Sub M3 (x as Long()) System.Console.WriteLine("Long") End Sub Shared Sub M4 (x as (Byte, Byte)) System.Console.WriteLine("Byte") End Sub Shared Sub M4 (x as (Long, Long)) System.Console.WriteLine("Long") End Sub Shared Sub M5 (x as (Byte?, Byte?)) System.Console.WriteLine("Byte") End Sub Shared Sub M5 (x as (Long?, Long?)) System.Console.WriteLine("Long") End Sub Shared Sub M6 (x as (Byte, Byte)?) System.Console.WriteLine("Byte") End Sub Shared Sub M6 (x as (Long, Long)?) System.Console.WriteLine("Long") End Sub Shared Sub M7 (x as (Byte, Byte)()) System.Console.WriteLine("Byte") End Sub Shared Sub M7 (x as (Long, Long)()) System.Console.WriteLine("Long") End Sub Shared Sub Main() M1(1) M2(1) M3({1}) M4((1, 1)) M5((1, 1)) M6((1, 1)) M7({(1, 1)}) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(True), additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected></expected>) CompileAndVerify(comp, expectedOutput:= "Long Long Long Long Long Long Long") End Sub <Fact> <WorkItem(14473, "https://github.com/dotnet/roslyn/issues/14473")> Public Sub NarrowingFromNumericConstant_06() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class C Shared Sub M2 (x as Byte?) System.Console.WriteLine("Byte") End Sub Shared Sub M3 (x as Byte()) System.Console.WriteLine("Byte") End Sub Shared Sub M5 (x as (Byte?, Byte?)) System.Console.WriteLine("Byte") End Sub Shared Sub M6 (x as Byte?()) System.Console.WriteLine("Byte") End Sub Shared Sub M7 (x as (Byte, Byte)()) System.Console.WriteLine("Byte") End Sub Shared Sub Main() Dim a as Byte? = 1 Dim b as Byte() = {1} Dim c as (Byte?, Byte?) = (1, 1) Dim d as Byte?() = {1} Dim e as (Byte, Byte)() = {(1, 1)} M2(1) M3({1}) M5((1, 1)) M6({1}) M7({(1, 1)}) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(True), additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected></expected>) CompileAndVerify(comp, expectedOutput:= "Byte Byte Byte Byte Byte") End Sub <Fact> <WorkItem(14473, "https://github.com/dotnet/roslyn/issues/14473")> Public Sub NarrowingFromNumericConstant_07() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class C Shared Sub M1 (x as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M2 (x as Byte(), y as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M3 (x as (Byte, Byte)) System.Console.WriteLine("Byte") End Sub Shared Sub M4 (x as (Byte, Byte), y as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M5 (x as Byte?) System.Console.WriteLine("Byte") End Sub Shared Sub M6 (x as (Byte?, Byte?)) System.Console.WriteLine("Byte") End Sub Shared Sub M7 (x as (Byte, Byte)?) System.Console.WriteLine("Byte") End Sub Shared Sub M8 (x as (Byte, Byte)?, y as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub Main() M1(300) M2({ 300 }, 300) M3((300, 300)) M4((300, 300), 300) M5(70000) M6((70000, 70000)) M7((70000, 70000)) M8((300, 300), 300) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected></expected>) CompileAndVerify(comp, expectedOutput:= "Byte Byte Byte Byte Byte Byte Byte Byte") End Sub <Fact> Public Sub NarrowingFromNumericConstant_08() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Public Class C Shared Sub Main() Dim x00 As (Integer, Integer) = (1, 1) Dim x01 As (Byte, Integer) = (1, 1) Dim x02 As (Integer, Byte) = (1, 1) Dim x03 As (Byte, Long) = (1, 1) Dim x04 As (Long, Byte) = (1, 1) Dim x05 As (Byte, Integer) = (300, 1) Dim x06 As (Integer, Byte) = (1, 300) Dim x07 As (Byte, Long) = (300, 1) Dim x08 As (Long, Byte) = (1, 300) Dim x09 As (Long, Long) = (1, 300) Dim x10 As (Byte, Byte) = (1, 300) Dim x11 As (Byte, Byte) = (300, 1) Dim one As Integer = 1 Dim x12 As (Byte, Byte, Byte) = (one, 300, 1) Dim x13 As (Byte, Byte, Byte) = (300, one, 1) Dim x14 As (Byte, Byte, Byte) = (300, 1, one) Dim x15 As (Byte, Byte) = (one, one) Dim x16 As (Integer, (Byte, Integer)) = (1, (1, 1)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected></expected>) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ToArray() AssertConversions(model, nodes(0), ConversionKind.Identity, ConversionKind.Identity, ConversionKind.Identity) AssertConversions(model, nodes(1), ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.Identity) AssertConversions(model, nodes(2), ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.Identity, ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant) AssertConversions(model, nodes(3), ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.WideningNumeric) AssertConversions(model, nodes(4), ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.WideningNumeric, ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant) AssertConversions(model, nodes(5), ConversionKind.NarrowingTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.Identity) AssertConversions(model, nodes(6), ConversionKind.NarrowingTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.Identity, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant) AssertConversions(model, nodes(7), ConversionKind.NarrowingTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.WideningNumeric) AssertConversions(model, nodes(8), ConversionKind.NarrowingTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.WideningNumeric, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant) AssertConversions(model, nodes(9), ConversionKind.WideningTuple, ConversionKind.WideningNumeric, ConversionKind.WideningNumeric) AssertConversions(model, nodes(10), ConversionKind.NarrowingTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant) AssertConversions(model, nodes(11), ConversionKind.NarrowingTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant) AssertConversions(model, nodes(12), ConversionKind.NarrowingTuple, ConversionKind.NarrowingNumeric, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant) AssertConversions(model, nodes(13), ConversionKind.NarrowingTuple, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.NarrowingNumeric, ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant) AssertConversions(model, nodes(14), ConversionKind.NarrowingTuple, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.NarrowingNumeric) AssertConversions(model, nodes(15), ConversionKind.NarrowingTuple, ConversionKind.NarrowingNumeric, ConversionKind.NarrowingNumeric) AssertConversions(model, nodes(16), ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.Identity, ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant) End Sub Private Shared Sub AssertConversions(model As SemanticModel, literal As TupleExpressionSyntax, aggregate As ConversionKind, ParamArray parts As ConversionKind()) If parts.Length > 0 Then Assert.Equal(literal.Arguments.Count, parts.Length) For i As Integer = 0 To parts.Length - 1 Assert.Equal(parts(i), model.GetConversion(literal.Arguments(i).Expression).Kind) Next End If Assert.Equal(aggregate, model.GetConversion(literal).Kind) End Sub <Fact> Public Sub Narrowing_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class C Shared Sub M2 (x as Byte?) System.Console.WriteLine("Byte") End Sub Shared Sub M5 (x as (Byte?, Byte?)) System.Console.WriteLine("Byte") End Sub Shared Sub Main() Dim x as integer = 1 Dim a as Byte? = x Dim b as (Byte?, Byte?) = (x, x) M2(x) M5((x, x)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(True), additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected> BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'. Dim a as Byte? = x ~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'. Dim b as (Byte?, Byte?) = (x, x) ~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'. Dim b as (Byte?, Byte?) = (x, x) ~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'. M2(x) ~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'. M5((x, x)) ~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'. M5((x, x)) ~ </expected>) End Sub <Fact> Public Sub Narrowing_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class C Shared Sub Main() Dim x as integer = 1 Dim x1 = CType(x, Byte) Dim x2 = CType(x, Byte?) Dim x3 = CType((x, x), (Byte, Integer)) Dim x4 = CType((x, x), (Byte?, Integer?)) Dim x5 = CType((x, x), (Byte, Integer)?) Dim x6 = CType((x, x), (Byte?, Integer?)?) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp) End Sub <Fact> Public Sub Narrowing_03() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class C Shared Sub Main() Dim x as (Integer, Integer) = (1, 1) Dim x3 = CType(x, (Byte, Integer)) Dim x4 = CType(x, (Byte?, Integer?)) Dim x5 = CType(x, (Byte, Integer)?) Dim x6 = CType(x, (Byte?, Integer?)?) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp) End Sub <Fact> Public Sub Narrowing_04() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class C Shared Sub Main() Dim x as (Integer, Integer) = (1, 1) Dim x3 as (Byte, Integer) = x Dim x4 as (Byte?, Integer?) = x Dim x5 as (Byte, Integer)? = x Dim x6 as (Byte?, Integer?)?= x End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected> BC30512: Option Strict On disallows implicit conversions from '(Integer, Integer)' to '(Byte, Integer)'. Dim x3 as (Byte, Integer) = x ~ BC30512: Option Strict On disallows implicit conversions from '(Integer, Integer)' to '(Byte?, Integer?)'. Dim x4 as (Byte?, Integer?) = x ~ BC30512: Option Strict On disallows implicit conversions from '(Integer, Integer)' to '(Byte, Integer)?'. Dim x5 as (Byte, Integer)? = x ~ BC30512: Option Strict On disallows implicit conversions from '(Integer, Integer)' to '(Byte?, Integer?)?'. Dim x6 as (Byte?, Integer?)?= x ~ </expected>) End Sub <Fact> Public Sub OverloadResolution_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class C Shared Sub M1 (x as Short) System.Console.WriteLine("Short") End Sub Shared Sub M1 (x as Integer) System.Console.WriteLine("Integer") End Sub Shared Sub M2 (x as Short?) System.Console.WriteLine("Short") End Sub Shared Sub M2 (x as Integer?) System.Console.WriteLine("Integer") End Sub Shared Sub M3 (x as (Short, Short)) System.Console.WriteLine("Short") End Sub Shared Sub M3(x as (Integer, Integer)) System.Console.WriteLine("Integer") End Sub Shared Sub M4 (x as (Short?, Short?)) System.Console.WriteLine("Short") End Sub Shared Sub M4(x as (Integer?, Integer?)) System.Console.WriteLine("Integer") End Sub Shared Sub M5 (x as (Short, Short)?) System.Console.WriteLine("Short") End Sub Shared Sub M5(x as (Integer, Integer)?) System.Console.WriteLine("Integer") End Sub Shared Sub Main() Dim x as Byte = 1 M1(x) M2(x) M3((x, x)) M4((x, x)) M5((x, x)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected></expected>) CompileAndVerify(comp, expectedOutput:= "Short Short Short Short Short") End Sub <Fact> Public Sub FailedDueToNumericOverflow_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Public Class C Shared Sub Main() Dim x1 As Byte = 300 Dim x2 as (Integer, Byte) = (300, 300) Dim x3 As Byte? = 300 Dim x4 as (Integer?, Byte?) = (300, 300) Dim x5 as (Integer, Byte)? = (300, 300) Dim x6 as (Integer?, Byte?)? = (300, 300) System.Console.WriteLine(x1) System.Console.WriteLine(x2) System.Console.WriteLine(x3) System.Console.WriteLine(x4) System.Console.WriteLine(x5) System.Console.WriteLine(x6) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected></expected>) CompileAndVerify(comp, expectedOutput:= "44 (300, 44) 44 (300, 44) (300, 44) (300, 44)") comp = comp.WithOptions(comp.Options.WithOverflowChecks(True)) AssertTheseDiagnostics(comp, <expected> BC30439: Constant expression not representable in type 'Byte'. Dim x1 As Byte = 300 ~~~ BC30439: Constant expression not representable in type 'Byte'. Dim x2 as (Integer, Byte) = (300, 300) ~~~ BC30439: Constant expression not representable in type 'Byte?'. Dim x3 As Byte? = 300 ~~~ BC30439: Constant expression not representable in type 'Byte?'. Dim x4 as (Integer?, Byte?) = (300, 300) ~~~ BC30439: Constant expression not representable in type 'Byte'. Dim x5 as (Integer, Byte)? = (300, 300) ~~~ BC30439: Constant expression not representable in type 'Byte?'. Dim x6 as (Integer?, Byte?)? = (300, 300) ~~~ </expected>) End Sub <Fact> Public Sub MethodTypeInference001() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() System.Console.WriteLine(Test((1,"q"))) End Sub Function Test(of T1, T2)(x as (T1, T2)) as (T1, T2) Console.WriteLine(Gettype(T1)) Console.WriteLine(Gettype(T2)) return x End Function End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.Int32 System.String (1, q) ]]>) End Sub <Fact> Public Sub MethodTypeInference002() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim v = (new Object(),"q") Test(v) System.Console.WriteLine(v) End Sub Function Test(of T)(x as (T, T)) as (T, T) Console.WriteLine(Gettype(T)) return x End Function End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.Object (System.Object, q) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 51 (0x33) .maxstack 3 .locals init (System.ValueTuple(Of Object, String) V_0) IL_0000: newobj "Sub Object..ctor()" IL_0005: ldstr "q" IL_000a: newobj "Sub System.ValueTuple(Of Object, String)..ctor(Object, String)" IL_000f: dup IL_0010: stloc.0 IL_0011: ldloc.0 IL_0012: ldfld "System.ValueTuple(Of Object, String).Item1 As Object" IL_0017: ldloc.0 IL_0018: ldfld "System.ValueTuple(Of Object, String).Item2 As String" IL_001d: newobj "Sub System.ValueTuple(Of Object, Object)..ctor(Object, Object)" IL_0022: call "Function C.Test(Of Object)((Object, Object)) As (Object, Object)" IL_0027: pop IL_0028: box "System.ValueTuple(Of Object, String)" IL_002d: call "Sub System.Console.WriteLine(Object)" IL_0032: ret } ]]>) End Sub <Fact> Public Sub MethodTypeInference002Err() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim v = (new Object(),"q") Test(v) System.Console.WriteLine(v) TestRef(v) System.Console.WriteLine(v) End Sub Function Test(of T)(x as (T, T)) as (T, T) Console.WriteLine(Gettype(T)) return x End Function Function TestRef(of T)(ByRef x as (T, T)) as (T, T) Console.WriteLine(Gettype(T)) x.Item1 = x.Item2 return x End Function End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC36651: Data type(s) of the type parameter(s) in method 'Public Function TestRef(Of T)(ByRef x As (T, T)) As (T, T)' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error. TestRef(v) ~~~~~~~ </errors>) End Sub <Fact> Public Sub MethodTypeInference003() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() System.Console.WriteLine(Test((Nothing,"q"))) System.Console.WriteLine(Test(("q", Nothing))) System.Console.WriteLine(Test1((Nothing, Nothing), (Nothing,"q"))) System.Console.WriteLine(Test1(("q", Nothing), (Nothing, Nothing))) End Sub Function Test(of T)(x as (T, T)) as (T, T) Console.WriteLine(Gettype(T)) return x End Function Function Test1(of T)(x as (T, T), y as (T, T)) as (T, T) Console.WriteLine(Gettype(T)) return x End Function End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.String (, q) System.String (q, ) System.String (, ) System.String (q, ) ]]>) End Sub <Fact> Public Sub MethodTypeInference004() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim q = "q" Dim a As Object = "a" System.Console.WriteLine(Test((q, a))) System.Console.WriteLine(q) System.Console.WriteLine(a) System.Console.WriteLine(Test((Ps, Po))) System.Console.WriteLine(q) System.Console.WriteLine(a) End Sub Function Test(Of T)(ByRef x As (T, T)) As (T, T) Console.WriteLine(GetType(T)) x.Item1 = x.Item2 Return x End Function Public Property Ps As String Get Return "q" End Get Set(value As String) System.Console.WriteLine("written1 !!!") End Set End Property Public Property Po As Object Get Return "a" End Get Set(value As Object) System.Console.WriteLine("written2 !!!") End Set End Property End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.Object (a, a) q a System.Object (a, a) q a ]]>) End Sub <Fact> Public Sub MethodTypeInference004a() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() System.Console.WriteLine(Test((new Object(),"q"))) System.Console.WriteLine(Test1((new Object(),"q"))) End Sub Function Test(of T)(x as (T, T)) as (T, T) Console.WriteLine(Gettype(T)) return x End Function Function Test1(of T)(x as T) as T Console.WriteLine(Gettype(T)) return x End Function End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.Object (System.Object, q) System.ValueTuple`2[System.Object,System.String] (System.Object, q) ]]>) End Sub <Fact> Public Sub MethodTypeInference004Err() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim q = "q" Dim a as object = "a" Dim t = (q, a) System.Console.WriteLine(Test(t)) System.Console.WriteLine(q) System.Console.WriteLine(a) End Sub Function Test(of T)(byref x as (T, T)) as (T, T) Console.WriteLine(Gettype(T)) x.Item1 = x.Item2 return x End Function End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC36651: Data type(s) of the type parameter(s) in method 'Public Function Test(Of T)(ByRef x As (T, T)) As (T, T)' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error. System.Console.WriteLine(Test(t)) ~~~~ </errors>) End Sub <Fact> Public Sub MethodTypeInference005() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Module1 Sub Main() Dim ie As IEnumerable(Of String) = {1, 2} Dim t = (ie, ie) Test(t, New Object) Test((ie, ie), New Object) End Sub Sub Test(Of T)(a1 As (IEnumerable(Of T), IEnumerable(Of T)), a2 As T) System.Console.WriteLine(GetType(T)) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.Object System.Object ]]>) End Sub <Fact> Public Sub MethodTypeInference006() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Module1 Sub Main() Dim ie As IEnumerable(Of Integer) = {1, 2} Dim t = (ie, ie) Test(t) Test((1, 1)) End Sub Sub Test(Of T)(f1 As IComparable(Of (T, T))) System.Console.WriteLine(GetType(T)) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.Collections.Generic.IEnumerable`1[System.Int32] System.Int32 ]]>) End Sub <Fact> Public Sub MethodTypeInference007() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Module1 Sub Main() Dim ie As IEnumerable(Of Integer) = {1, 2} Dim t = (ie, ie) Test(t) Test((1, 1)) End Sub Sub Test(Of T)(f1 As IComparable(Of (T, T))) System.Console.WriteLine(GetType(T)) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.Collections.Generic.IEnumerable`1[System.Int32] System.Int32 ]]>) End Sub <Fact> Public Sub MethodTypeInference008() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Module1 Sub Main() Dim t = (1, 1L) ' these are valid Test1(t) Test1((1, 1L)) End Sub Sub Test1(Of T)(f1 As (T, T)) System.Console.WriteLine(GetType(T)) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.Int64 System.Int64 ]]>) End Sub <Fact> Public Sub MethodTypeInference008Err() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Module Module1 Sub Main() Dim t = (1, 1L) ' these are valid Test1(t) Test1((1, 1L)) ' these are not Test2(t) Test2((1, 1L)) End Sub Sub Test1(Of T)(f1 As (T, T)) System.Console.WriteLine(GetType(T)) End Sub Sub Test2(Of T)(f1 As IComparable(Of (T, T))) System.Console.WriteLine(GetType(T)) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC36657: Data type(s) of the type parameter(s) in method 'Public Sub Test2(Of T)(f1 As IComparable(Of (T, T)))' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error. Test2(t) ~~~~~ BC36657: Data type(s) of the type parameter(s) in method 'Public Sub Test2(Of T)(f1 As IComparable(Of (T, T)))' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error. Test2((1, 1L)) ~~~~~ </errors>) End Sub <Fact> Public Sub Inference04() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Test( Function(x)x.y ) Test( Function(x)x.bob ) End Sub Sub Test(of T)(x as Func(of (x as Byte, y As Byte), T)) System.Console.WriteLine("first") System.Console.WriteLine(x((2,3)).ToString()) End Sub Sub Test(of T)(x as Func(of (alice as integer, bob as integer), T)) System.Console.WriteLine("second") System.Console.WriteLine(x((4,5)).ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ first 3 second 5 ]]>) End Sub <Fact> Public Sub Inference07() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Test(Function(x)(x, x), Function(t)1) Test1(Function(x)(x, x), Function(t)1) Test2((a:= 1, b:= 2), Function(t)(t.a, t.b)) End Sub Sub Test(Of U)(f1 as Func(of Integer, ValueTuple(Of U, U)), f2 as Func(Of ValueTuple(Of U, U), Integer)) System.Console.WriteLine(f2(f1(1))) End Sub Sub Test1(of U)(f1 As Func(of integer, (U, U)), f2 as Func(Of (U, U), integer)) System.Console.WriteLine(f2(f1(1))) End Sub Sub Test2(of U, T)(f1 as U , f2 As Func(Of U, (x as T, y As T))) System.Console.WriteLine(f2(f1).y) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ 1 1 2 ]]>) End Sub <Fact> Public Sub InferenceChain001() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Test(Function(x As (Integer, Integer)) (x, x), Function(t) (t, t)) End Sub Sub Test(Of T, U, V)(f1 As Func(Of (T,T), (U,U)), f2 As Func(Of (U,U), (V,V))) System.Console.WriteLine(f2(f1(Nothing))) System.Console.WriteLine(GetType(T)) System.Console.WriteLine(GetType(U)) System.Console.WriteLine(GetType(V)) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (((0, 0), (0, 0)), ((0, 0), (0, 0))) System.Int32 System.ValueTuple`2[System.Int32,System.Int32] System.ValueTuple`2[System.ValueTuple`2[System.Int32,System.Int32],System.ValueTuple`2[System.Int32,System.Int32]] ]]>) End Sub <Fact> Public Sub InferenceChain002() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Test(Function(x As (Integer, Object)) (x, x), Function(t) (t, t)) End Sub Sub Test(Of T, U, V)(ByRef f1 As Func(Of (T, T), (U, U)), ByRef f2 As Func(Of (U, U), (V, V))) System.Console.WriteLine(f2(f1(Nothing))) System.Console.WriteLine(GetType(T)) System.Console.WriteLine(GetType(U)) System.Console.WriteLine(GetType(V)) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (((0, ), (0, )), ((0, ), (0, ))) System.Object System.ValueTuple`2[System.Int32,System.Object] System.ValueTuple`2[System.ValueTuple`2[System.Int32,System.Object],System.ValueTuple`2[System.Int32,System.Object]] ]]>) End Sub <Fact> Public Sub SimpleTupleNested() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = (1, (2, (3, 4)).ToString()) System.Console.Write(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(1, (2, (3, 4)))]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("Module1.Main", <![CDATA[ { // Code size 54 (0x36) .maxstack 5 .locals init (System.ValueTuple(Of Integer, String) V_0, //x System.ValueTuple(Of Integer, (Integer, Integer)) V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: ldc.i4.3 IL_0005: ldc.i4.4 IL_0006: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_000b: newobj "Sub System.ValueTuple(Of Integer, (Integer, Integer))..ctor(Integer, (Integer, Integer))" IL_0010: stloc.1 IL_0011: ldloca.s V_1 IL_0013: constrained. "System.ValueTuple(Of Integer, (Integer, Integer))" IL_0019: callvirt "Function Object.ToString() As String" IL_001e: call "Sub System.ValueTuple(Of Integer, String)..ctor(Integer, String)" IL_0023: ldloca.s V_0 IL_0025: constrained. "System.ValueTuple(Of Integer, String)" IL_002b: callvirt "Function Object.ToString() As String" IL_0030: call "Sub System.Console.Write(String)" IL_0035: ret } ]]>) End Sub <Fact> Public Sub TupleUnderlyingItemAccess() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = (1, 2) System.Console.WriteLine(x.Item2.ToString()) x.Item1 = 40 System.Console.WriteLine(x.Item1 + x.Item2) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[2 42]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("Module1.Main", <![CDATA[ { // Code size 54 (0x36) .maxstack 3 .locals init (System.ValueTuple(Of Integer, Integer) V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: call "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0009: ldloca.s V_0 IL_000b: ldflda "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0010: call "Function Integer.ToString() As String" IL_0015: call "Sub System.Console.WriteLine(String)" IL_001a: ldloca.s V_0 IL_001c: ldc.i4.s 40 IL_001e: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0023: ldloc.0 IL_0024: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0029: ldloc.0 IL_002a: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_002f: add.ovf IL_0030: call "Sub System.Console.WriteLine(Integer)" IL_0035: ret } ]]>) End Sub <Fact> Public Sub TupleUnderlyingItemAccess01() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = (A:=1, B:=2) System.Console.WriteLine(x.Item2.ToString()) x.Item1 = 40 System.Console.WriteLine(x.Item1 + x.Item2) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[2 42]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("Module1.Main", <![CDATA[ { // Code size 54 (0x36) .maxstack 3 .locals init (System.ValueTuple(Of Integer, Integer) V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: call "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0009: ldloca.s V_0 IL_000b: ldflda "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0010: call "Function Integer.ToString() As String" IL_0015: call "Sub System.Console.WriteLine(String)" IL_001a: ldloca.s V_0 IL_001c: ldc.i4.s 40 IL_001e: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0023: ldloc.0 IL_0024: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0029: ldloc.0 IL_002a: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_002f: add.ovf IL_0030: call "Sub System.Console.WriteLine(Integer)" IL_0035: ret } ]]>) End Sub <Fact> Public Sub TupleItemAccess() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = (A:=1, B:=2) System.Console.WriteLine(x.Item2.ToString()) x.A = 40 System.Console.WriteLine(x.A + x.B) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[2 42]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("Module1.Main", <![CDATA[ { // Code size 54 (0x36) .maxstack 3 .locals init (System.ValueTuple(Of Integer, Integer) V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: call "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0009: ldloca.s V_0 IL_000b: ldflda "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0010: call "Function Integer.ToString() As String" IL_0015: call "Sub System.Console.WriteLine(String)" IL_001a: ldloca.s V_0 IL_001c: ldc.i4.s 40 IL_001e: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0023: ldloc.0 IL_0024: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0029: ldloc.0 IL_002a: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_002f: add.ovf IL_0030: call "Sub System.Console.WriteLine(Integer)" IL_0035: ret } ]]>) End Sub <Fact> Public Sub TupleItemAccess01() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = (A:=1, B:=(C:=2, D:= 3)) System.Console.WriteLine(x.B.C.ToString()) x.B.D = 39 System.Console.WriteLine(x.A + x.B.C + x.B.D) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[2 42]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("Module1.Main", <![CDATA[ { // Code size 87 (0x57) .maxstack 4 .locals init (System.ValueTuple(Of Integer, (C As Integer, D As Integer)) V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: ldc.i4.3 IL_0005: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_000a: call "Sub System.ValueTuple(Of Integer, (C As Integer, D As Integer))..ctor(Integer, (C As Integer, D As Integer))" IL_000f: ldloca.s V_0 IL_0011: ldflda "System.ValueTuple(Of Integer, (C As Integer, D As Integer)).Item2 As (C As Integer, D As Integer)" IL_0016: ldflda "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_001b: call "Function Integer.ToString() As String" IL_0020: call "Sub System.Console.WriteLine(String)" IL_0025: ldloca.s V_0 IL_0027: ldflda "System.ValueTuple(Of Integer, (C As Integer, D As Integer)).Item2 As (C As Integer, D As Integer)" IL_002c: ldc.i4.s 39 IL_002e: stfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0033: ldloc.0 IL_0034: ldfld "System.ValueTuple(Of Integer, (C As Integer, D As Integer)).Item1 As Integer" IL_0039: ldloc.0 IL_003a: ldfld "System.ValueTuple(Of Integer, (C As Integer, D As Integer)).Item2 As (C As Integer, D As Integer)" IL_003f: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0044: add.ovf IL_0045: ldloc.0 IL_0046: ldfld "System.ValueTuple(Of Integer, (C As Integer, D As Integer)).Item2 As (C As Integer, D As Integer)" IL_004b: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0050: add.ovf IL_0051: call "Sub System.Console.WriteLine(Integer)" IL_0056: ret } ]]>) End Sub <Fact> Public Sub TupleTypeDeclaration() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As (Integer, String, Integer) = (1, "hello", 2) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(1, hello, 2)]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("Module1.Main", <![CDATA[ { // Code size 33 (0x21) .maxstack 4 .locals init (System.ValueTuple(Of Integer, String, Integer) V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldstr "hello" IL_0008: ldc.i4.2 IL_0009: call "Sub System.ValueTuple(Of Integer, String, Integer)..ctor(Integer, String, Integer)" IL_000e: ldloca.s V_0 IL_0010: constrained. "System.ValueTuple(Of Integer, String, Integer)" IL_0016: callvirt "Function Object.ToString() As String" IL_001b: call "Sub System.Console.WriteLine(String)" IL_0020: ret } ]]>) End Sub <Fact> Public Sub TupleTypeMismatch_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x As (Integer, String) = (1, "hello", 2) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30311: Value of type '(Integer, String, Integer)' cannot be converted to '(Integer, String)'. Dim x As (Integer, String) = (1, "hello", 2) ~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleTypeMismatch_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x As (Integer, String) = (1, Nothing, 2) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30311: Value of type '(Integer, Object, Integer)' cannot be converted to '(Integer, String)'. Dim x As (Integer, String) = (1, Nothing, 2) ~~~~~~~~~~~~~~~ </errors>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub LongTupleTypeMismatch() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = ("Alice", 2, 3, 4, 5, 6, 7, 8) Dim y As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = (1, 2, 3, 4, 5, 6, 7, 8) End Sub End Module ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC37267: Predefined type 'ValueTuple(Of )' is not defined or imported. Dim x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = ("Alice", 2, 3, 4, 5, 6, 7, 8) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of ,,,,,,,)' is not defined or imported. Dim x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = ("Alice", 2, 3, 4, 5, 6, 7, 8) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of )' is not defined or imported. Dim x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = ("Alice", 2, 3, 4, 5, 6, 7, 8) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of ,,,,,,,)' is not defined or imported. Dim x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = ("Alice", 2, 3, 4, 5, 6, 7, 8) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of )' is not defined or imported. Dim y As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = (1, 2, 3, 4, 5, 6, 7, 8) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of ,,,,,,,)' is not defined or imported. Dim y As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = (1, 2, 3, 4, 5, 6, 7, 8) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of )' is not defined or imported. Dim y As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = (1, 2, 3, 4, 5, 6, 7, 8) ~~~~~~~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of ,,,,,,,)' is not defined or imported. Dim y As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = (1, 2, 3, 4, 5, 6, 7, 8) ~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleTypeWithLateDiscoveredName() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x As (Integer, A As String) = (1, "hello", C:=2) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30311: Value of type '(Integer, String, C As Integer)' cannot be converted to '(Integer, A As String)'. Dim x As (Integer, A As String) = (1, "hello", C:=2) ~~~~~~~~~~~~~~~~~~ </errors>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(1, ""hello"", C:=2)", node.ToString()) Assert.Equal("(System.Int32, System.String, C As System.Int32)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Dim xSymbol = DirectCast(model.GetDeclaredSymbol(x), LocalSymbol).Type Assert.Equal("(System.Int32, A As System.String)", xSymbol.ToTestDisplayString()) Assert.True(xSymbol.IsTupleType) Assert.False(DirectCast(xSymbol, INamedTypeSymbol).IsSerializable) Assert.Equal({"System.Int32", "System.String"}, xSymbol.TupleElementTypes.SelectAsArray(Function(t) t.ToTestDisplayString())) Assert.Equal({Nothing, "A"}, xSymbol.TupleElementNames) End Sub <Fact> Public Sub TupleTypeDeclarationWithNames() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As (A As Integer, B As String) = (1, "hello") System.Console.WriteLine(x.A.ToString()) System.Console.WriteLine(x.B.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1 hello]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleDictionary01() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Collections.Generic Class C Shared Sub Main() Dim k = (1, 2) Dim v = (A:=1, B:=(C:=2, D:=(E:=3, F:=4))) Dim d = Test(k, v) System.Console.Write(d((1, 2)).B.D.Item2) End Sub Shared Function Test(Of K, V)(key As K, value As V) As Dictionary(Of K, V) Dim d = new Dictionary(Of K, V)() d(key) = value return d End Function End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[4]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 67 (0x43) .maxstack 6 .locals init (System.ValueTuple(Of Integer, (C As Integer, D As (E As Integer, F As Integer))) V_0) //v IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0007: ldloca.s V_0 IL_0009: ldc.i4.1 IL_000a: ldc.i4.2 IL_000b: ldc.i4.3 IL_000c: ldc.i4.4 IL_000d: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0012: newobj "Sub System.ValueTuple(Of Integer, (E As Integer, F As Integer))..ctor(Integer, (E As Integer, F As Integer))" IL_0017: call "Sub System.ValueTuple(Of Integer, (C As Integer, D As (E As Integer, F As Integer)))..ctor(Integer, (C As Integer, D As (E As Integer, F As Integer)))" IL_001c: ldloc.0 IL_001d: call "Function C.Test(Of (Integer, Integer), (A As Integer, B As (C As Integer, D As (E As Integer, F As Integer))))((Integer, Integer), (A As Integer, B As (C As Integer, D As (E As Integer, F As Integer)))) As System.Collections.Generic.Dictionary(Of (Integer, Integer), (A As Integer, B As (C As Integer, D As (E As Integer, F As Integer))))" IL_0022: ldc.i4.1 IL_0023: ldc.i4.2 IL_0024: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0029: callvirt "Function System.Collections.Generic.Dictionary(Of (Integer, Integer), (A As Integer, B As (C As Integer, D As (E As Integer, F As Integer)))).get_Item((Integer, Integer)) As (A As Integer, B As (C As Integer, D As (E As Integer, F As Integer)))" IL_002e: ldfld "System.ValueTuple(Of Integer, (C As Integer, D As (E As Integer, F As Integer))).Item2 As (C As Integer, D As (E As Integer, F As Integer))" IL_0033: ldfld "System.ValueTuple(Of Integer, (E As Integer, F As Integer)).Item2 As (E As Integer, F As Integer)" IL_0038: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_003d: call "Sub System.Console.Write(Integer)" IL_0042: ret } ]]>) End Sub <Fact> Public Sub TupleLambdaCapture01() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() System.Console.Write(Test(42)) End Sub Public Shared Function Test(Of T)(a As T) As T Dim x = (f1:=a, f2:=a) Dim f As System.Func(Of T) = Function() x.f2 return f() End Function End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("C._Closure$__2-0(Of $CLS0)._Lambda$__0()", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda "C._Closure$__2-0(Of $CLS0).$VB$Local_x As (f1 As $CLS0, f2 As $CLS0)" IL_0006: ldfld "System.ValueTuple(Of $CLS0, $CLS0).Item2 As $CLS0" IL_000b: ret } ]]>) End Sub <Fact> Public Sub TupleLambdaCapture02() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() System.Console.Write(Test(42)) End Sub Shared Function Test(Of T)(a As T) As String Dim x = (f1:=a, f2:=a) Dim f As System.Func(Of String) = Function() x.ToString() Return f() End Function End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(42, 42)]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("C._Closure$__2-0(Of $CLS0)._Lambda$__0()", <![CDATA[ { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda "C._Closure$__2-0(Of $CLS0).$VB$Local_x As (f1 As $CLS0, f2 As $CLS0)" IL_0006: constrained. "System.ValueTuple(Of $CLS0, $CLS0)" IL_000c: callvirt "Function Object.ToString() As String" IL_0011: ret } ]]>) End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/13298")> Public Sub TupleLambdaCapture03() ' This test crashes in TypeSubstitution Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() System.Console.Write(Test(42)) End Sub Shared Function Test(Of T)(a As T) As T Dim x = (f1:=a, f2:=b) Dim f As System.Func(Of T) = Function() x.Test(a) Return f() End Function End Class Namespace System Public Structure ValueTuple(Of T1, T2) Public Item1 As T1 Public Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}" End Function Public Function Test(Of U)(val As U) As U Return val End Function End Structure End Namespace </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("Module1.Main", <![CDATA[ ]]>) End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/pull/13209")> Public Sub TupleLambdaCapture04() ' this test crashes in TypeSubstitution Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() System.Console.Write(Test(42)) End Sub Shared Function Test(Of T)(a As T) As T Dim x = (f1:=1, f2:=2) Dim f As System.Func(Of T) = Function() x.Test(a) Return f() End Function End Class Namespace System Public Structure ValueTuple(Of T1, T2) Public Item1 As T1 Public Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}" End Function Public Function Test(Of U)(val As U) As U Return val End Function End Structure End Namespace </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("Module1.Main", <![CDATA[ ]]>) End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/pull/13209")> Public Sub TupleLambdaCapture05() ' this test crashes in TypeSubstitution Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() System.Console.Write(Test(42)) End Sub Shared Function Test(Of T)(a As T) As T Dim x = (f1:=a, f2:=a) Dim f As System.Func(Of T) = Function() x.P1 Return f() End Function End Class Namespace System Public Structure ValueTuple(Of T1, T2) Public Item1 As T1 Public Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}" End Function Public ReadOnly Property P1 As T1 Get Return Item1 End Get End Property End Structure End Namespace </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("Module1.Main", <![CDATA[ ]]>) End Sub <Fact> Public Sub TupleAsyncCapture01() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Threading.Tasks Class C Shared Sub Main() Console.Write(Test(42).Result) End Sub Shared Async Function Test(Of T)(a As T) As Task(Of T) Dim x = (f1:=a, f2:=a) Await Task.Yield() Return x.f1 End Function End Class </file> </compilation>, references:={ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef_v46}, expectedOutput:=<![CDATA[42]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("C.VB$StateMachine_2_Test(Of SM$T).MoveNext()", <![CDATA[ { // Code size 204 (0xcc) .maxstack 3 .locals init (SM$T V_0, Integer V_1, System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2, System.Runtime.CompilerServices.YieldAwaitable V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer" IL_0006: stloc.1 .try { IL_0007: ldloc.1 IL_0008: brfalse.s IL_0058 IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$VB$Local_a As SM$T" IL_0011: ldarg.0 IL_0012: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$VB$Local_a As SM$T" IL_0017: newobj "Sub System.ValueTuple(Of SM$T, SM$T)..ctor(SM$T, SM$T)" IL_001c: stfld "C.VB$StateMachine_2_Test(Of SM$T).$VB$ResumableLocal_x$0 As (f1 As SM$T, f2 As SM$T)" IL_0021: call "Function System.Threading.Tasks.Task.Yield() As System.Runtime.CompilerServices.YieldAwaitable" IL_0026: stloc.3 IL_0027: ldloca.s V_3 IL_0029: call "Function System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter() As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_002e: stloc.2 IL_002f: ldloca.s V_2 IL_0031: call "Function System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.get_IsCompleted() As Boolean" IL_0036: brtrue.s IL_0074 IL_0038: ldarg.0 IL_0039: ldc.i4.0 IL_003a: dup IL_003b: stloc.1 IL_003c: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer" IL_0041: ldarg.0 IL_0042: ldloc.2 IL_0043: stfld "C.VB$StateMachine_2_Test(Of SM$T).$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0048: ldarg.0 IL_0049: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of SM$T)" IL_004e: ldloca.s V_2 IL_0050: ldarg.0 IL_0051: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of SM$T).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.VB$StateMachine_2_Test(Of SM$T))(ByRef System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ByRef C.VB$StateMachine_2_Test(Of SM$T))" IL_0056: leave.s IL_00cb IL_0058: ldarg.0 IL_0059: ldc.i4.m1 IL_005a: dup IL_005b: stloc.1 IL_005c: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer" IL_0061: ldarg.0 IL_0062: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0067: stloc.2 IL_0068: ldarg.0 IL_0069: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_006e: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0074: ldloca.s V_2 IL_0076: call "Sub System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()" IL_007b: ldloca.s V_2 IL_007d: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0083: ldarg.0 IL_0084: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$VB$ResumableLocal_x$0 As (f1 As SM$T, f2 As SM$T)" IL_0089: ldfld "System.ValueTuple(Of SM$T, SM$T).Item1 As SM$T" IL_008e: stloc.0 IL_008f: leave.s IL_00b5 } catch System.Exception { IL_0091: dup IL_0092: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)" IL_0097: stloc.s V_4 IL_0099: ldarg.0 IL_009a: ldc.i4.s -2 IL_009c: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer" IL_00a1: ldarg.0 IL_00a2: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of SM$T)" IL_00a7: ldloc.s V_4 IL_00a9: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of SM$T).SetException(System.Exception)" IL_00ae: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_00b3: leave.s IL_00cb } IL_00b5: ldarg.0 IL_00b6: ldc.i4.s -2 IL_00b8: dup IL_00b9: stloc.1 IL_00ba: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer" IL_00bf: ldarg.0 IL_00c0: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of SM$T)" IL_00c5: ldloc.0 IL_00c6: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of SM$T).SetResult(SM$T)" IL_00cb: ret } ]]>) End Sub <Fact> Public Sub TupleAsyncCapture02() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Threading.Tasks Class C Shared Sub Main() Console.Write(Test(42).Result) End Sub Shared Async Function Test(Of T)(a As T) As Task(Of String) Dim x = (f1:=a, f2:=a) Await Task.Yield() Return x.ToString() End Function End Class </file> </compilation>, references:={ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef_v46}, expectedOutput:=<![CDATA[(42, 42)]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("C.VB$StateMachine_2_Test(Of SM$T).MoveNext()", <![CDATA[ { // Code size 210 (0xd2) .maxstack 3 .locals init (String V_0, Integer V_1, System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2, System.Runtime.CompilerServices.YieldAwaitable V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer" IL_0006: stloc.1 .try { IL_0007: ldloc.1 IL_0008: brfalse.s IL_0058 IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$VB$Local_a As SM$T" IL_0011: ldarg.0 IL_0012: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$VB$Local_a As SM$T" IL_0017: newobj "Sub System.ValueTuple(Of SM$T, SM$T)..ctor(SM$T, SM$T)" IL_001c: stfld "C.VB$StateMachine_2_Test(Of SM$T).$VB$ResumableLocal_x$0 As (f1 As SM$T, f2 As SM$T)" IL_0021: call "Function System.Threading.Tasks.Task.Yield() As System.Runtime.CompilerServices.YieldAwaitable" IL_0026: stloc.3 IL_0027: ldloca.s V_3 IL_0029: call "Function System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter() As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_002e: stloc.2 IL_002f: ldloca.s V_2 IL_0031: call "Function System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.get_IsCompleted() As Boolean" IL_0036: brtrue.s IL_0074 IL_0038: ldarg.0 IL_0039: ldc.i4.0 IL_003a: dup IL_003b: stloc.1 IL_003c: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer" IL_0041: ldarg.0 IL_0042: ldloc.2 IL_0043: stfld "C.VB$StateMachine_2_Test(Of SM$T).$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0048: ldarg.0 IL_0049: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)" IL_004e: ldloca.s V_2 IL_0050: ldarg.0 IL_0051: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.VB$StateMachine_2_Test(Of SM$T))(ByRef System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ByRef C.VB$StateMachine_2_Test(Of SM$T))" IL_0056: leave.s IL_00d1 IL_0058: ldarg.0 IL_0059: ldc.i4.m1 IL_005a: dup IL_005b: stloc.1 IL_005c: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer" IL_0061: ldarg.0 IL_0062: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0067: stloc.2 IL_0068: ldarg.0 IL_0069: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_006e: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0074: ldloca.s V_2 IL_0076: call "Sub System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()" IL_007b: ldloca.s V_2 IL_007d: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0083: ldarg.0 IL_0084: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$VB$ResumableLocal_x$0 As (f1 As SM$T, f2 As SM$T)" IL_0089: constrained. "System.ValueTuple(Of SM$T, SM$T)" IL_008f: callvirt "Function Object.ToString() As String" IL_0094: stloc.0 IL_0095: leave.s IL_00bb } catch System.Exception { IL_0097: dup IL_0098: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)" IL_009d: stloc.s V_4 IL_009f: ldarg.0 IL_00a0: ldc.i4.s -2 IL_00a2: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer" IL_00a7: ldarg.0 IL_00a8: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)" IL_00ad: ldloc.s V_4 IL_00af: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).SetException(System.Exception)" IL_00b4: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_00b9: leave.s IL_00d1 } IL_00bb: ldarg.0 IL_00bc: ldc.i4.s -2 IL_00be: dup IL_00bf: stloc.1 IL_00c0: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer" IL_00c5: ldarg.0 IL_00c6: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)" IL_00cb: ldloc.0 IL_00cc: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).SetResult(String)" IL_00d1: ret } ]]>) End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/pull/13209")> Public Sub TupleAsyncCapture03() ' this test crashes in TypeSubstitution Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Threading.Tasks Class C Shared Sub Main() Console.Write(Test(42).Result) End Sub Shared Async Function Test(Of T)(a As T) As Task(Of String) Dim x = (f1:=a, f2:=a) Await Task.Yield() Return x.Test(a) End Function End Class Namespace System Public Structure ValueTuple(Of T1, T2) Public Item1 As T1 Public Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}" End Function Public Function Test(Of U)(val As U) As U Return val End Function End Structure End Namespace </file> </compilation>, references:={MscorlibRef_v46}, expectedOutput:=<![CDATA[42]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("C.VB$StateMachine_2_Test(Of SM$T).MoveNext()", <![CDATA[ ]]>) End Sub <Fact> Public Sub LongTupleWithSubstitution() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Threading.Tasks Class C Shared Sub Main() Console.Write(Test(42).Result) End Sub Shared Async Function Test(Of T)(a As T) As Task(Of T) Dim x = (f1:=1, f2:=2, f3:=3, f4:=4, f5:=5, f6:=6, f7:=7, f8:=a) Await Task.Yield() Return x.f8 End Function End Class </file> </compilation>, references:={ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef_v46}, expectedOutput:=<![CDATA[42]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleUsageWithoutTupleLibrary() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x As (Integer, String) = (1, "hello") End Sub End Module ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported. Dim x As (Integer, String) = (1, "hello") ~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported. Dim x As (Integer, String) = (1, "hello") ~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleUsageWithMissingTupleMembers() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x As (Integer, String) = (1, 2) End Sub End Module Namespace System Public Structure ValueTuple(Of T1, T2) End Structure End Namespace ]]></file> </compilation>) comp.AssertTheseEmitDiagnostics( <errors> BC35000: Requested operation is not available because the runtime library function 'ValueTuple..ctor' is not defined. Dim x As (Integer, String) = (1, 2) ~~~~~~ </errors>) End Sub <Fact> Public Sub TupleWithDuplicateNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x As (a As Integer, a As String) = (b:=1, b:="hello", b:=2) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37262: Tuple element names must be unique. Dim x As (a As Integer, a As String) = (b:=1, b:="hello", b:=2) ~ BC37262: Tuple element names must be unique. Dim x As (a As Integer, a As String) = (b:=1, b:="hello", b:=2) ~ BC37262: Tuple element names must be unique. Dim x As (a As Integer, a As String) = (b:=1, b:="hello", b:=2) ~ </errors>) End Sub <Fact> Public Sub TupleWithDuplicateReservedNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x As (Item1 As Integer, Item1 As String) = (Item1:=1, Item1:="hello") Dim y As (Item2 As Integer, Item2 As String) = (Item2:=1, Item2:="hello") End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37261: Tuple element name 'Item1' is only allowed at position 1. Dim x As (Item1 As Integer, Item1 As String) = (Item1:=1, Item1:="hello") ~~~~~ BC37261: Tuple element name 'Item1' is only allowed at position 1. Dim x As (Item1 As Integer, Item1 As String) = (Item1:=1, Item1:="hello") ~~~~~ BC37261: Tuple element name 'Item2' is only allowed at position 2. Dim y As (Item2 As Integer, Item2 As String) = (Item2:=1, Item2:="hello") ~~~~~ BC37261: Tuple element name 'Item2' is only allowed at position 2. Dim y As (Item2 As Integer, Item2 As String) = (Item2:=1, Item2:="hello") ~~~~~ </errors>) End Sub <Fact> Public Sub TupleWithNonReservedNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x As (Item1 As Integer, Item01 As Integer, Item10 As Integer) = (Item01:=1, Item1:=2, Item10:=3) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37261: Tuple element name 'Item10' is only allowed at position 10. Dim x As (Item1 As Integer, Item01 As Integer, Item10 As Integer) = (Item01:=1, Item1:=2, Item10:=3) ~~~~~~ BC37261: Tuple element name 'Item1' is only allowed at position 1. Dim x As (Item1 As Integer, Item01 As Integer, Item10 As Integer) = (Item01:=1, Item1:=2, Item10:=3) ~~~~~ BC37261: Tuple element name 'Item10' is only allowed at position 10. Dim x As (Item1 As Integer, Item01 As Integer, Item10 As Integer) = (Item01:=1, Item1:=2, Item10:=3) ~~~~~~ </errors>) End Sub <Fact> Public Sub DefaultValueForTuple() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x As (a As Integer, b As String) = (1, "hello") x = Nothing System.Console.WriteLine(x.a) System.Console.WriteLine(If(x.b, "null")) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[0 null]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleWithDuplicateMemberNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x As (a As Integer, a As String) = (b:=1, c:="hello", b:=2) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37262: Tuple element names must be unique. Dim x As (a As Integer, a As String) = (b:=1, c:="hello", b:=2) ~ BC37262: Tuple element names must be unique. Dim x As (a As Integer, a As String) = (b:=1, c:="hello", b:=2) ~ </errors>) End Sub <Fact> Public Sub TupleWithReservedMemberNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x As (Item1 As Integer, Item3 As String, Item2 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Rest As Integer) = (Item2:="bad", Item4:="bad", Item3:=3, Item4:=4, Item5:=5, Item6:=6, Item7:=7, Rest:="bad") End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37261: Tuple element name 'Item3' is only allowed at position 3. Dim x As (Item1 As Integer, Item3 As String, Item2 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Rest As Integer) = ~~~~~ BC37261: Tuple element name 'Item2' is only allowed at position 2. Dim x As (Item1 As Integer, Item3 As String, Item2 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Rest As Integer) = ~~~~~ BC37260: Tuple element name 'Rest' is disallowed at any position. Dim x As (Item1 As Integer, Item3 As String, Item2 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Rest As Integer) = ~~~~ BC37261: Tuple element name 'Item2' is only allowed at position 2. (Item2:="bad", Item4:="bad", Item3:=3, Item4:=4, Item5:=5, Item6:=6, Item7:=7, Rest:="bad") ~~~~~ BC37261: Tuple element name 'Item4' is only allowed at position 4. (Item2:="bad", Item4:="bad", Item3:=3, Item4:=4, Item5:=5, Item6:=6, Item7:=7, Rest:="bad") ~~~~~ BC37260: Tuple element name 'Rest' is disallowed at any position. (Item2:="bad", Item4:="bad", Item3:=3, Item4:=4, Item5:=5, Item6:=6, Item7:=7, Rest:="bad") ~~~~ </errors>) End Sub <Fact> Public Sub TupleWithExistingUnderlyingMemberNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x = (CompareTo:=2, Create:=3, Deconstruct:=4, Equals:=5, GetHashCode:=6, Rest:=8, ToString:=10) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37260: Tuple element name 'CompareTo' is disallowed at any position. Dim x = (CompareTo:=2, Create:=3, Deconstruct:=4, Equals:=5, GetHashCode:=6, Rest:=8, ToString:=10) ~~~~~~~~~ BC37260: Tuple element name 'Deconstruct' is disallowed at any position. Dim x = (CompareTo:=2, Create:=3, Deconstruct:=4, Equals:=5, GetHashCode:=6, Rest:=8, ToString:=10) ~~~~~~~~~~~ BC37260: Tuple element name 'Equals' is disallowed at any position. Dim x = (CompareTo:=2, Create:=3, Deconstruct:=4, Equals:=5, GetHashCode:=6, Rest:=8, ToString:=10) ~~~~~~ BC37260: Tuple element name 'GetHashCode' is disallowed at any position. Dim x = (CompareTo:=2, Create:=3, Deconstruct:=4, Equals:=5, GetHashCode:=6, Rest:=8, ToString:=10) ~~~~~~~~~~~ BC37260: Tuple element name 'Rest' is disallowed at any position. Dim x = (CompareTo:=2, Create:=3, Deconstruct:=4, Equals:=5, GetHashCode:=6, Rest:=8, ToString:=10) ~~~~ BC37260: Tuple element name 'ToString' is disallowed at any position. Dim x = (CompareTo:=2, Create:=3, Deconstruct:=4, Equals:=5, GetHashCode:=6, Rest:=8, ToString:=10) ~~~~~~~~ </errors>) End Sub <Fact> Public Sub LongTupleDeclaration() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer) = (1, 2, 3, 4, 5, 6, 7, "Alice", 2, 3, 4, 5) System.Console.Write($"{x.Item1} {x.Item2} {x.Item3} {x.Item4} {x.Item5} {x.Item6} {x.Item7} {x.Item8} {x.Item9} {x.Item10} {x.Item11} {x.Item12}") End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1 2 3 4 5 6 7 Alice 2 3 4 5]]>, sourceSymbolValidator:= Sub(m As ModuleSymbol) Dim compilation = m.DeclaringCompilation Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().Single().Names(0) Assert.Equal("x As (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, " _ + "System.String, System.Int32, System.Int32, System.Int32, System.Int32)", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub LongTupleDeclarationWithNames() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x As (a As Integer, b As Integer, c As Integer, d As Integer, e As Integer, f As Integer, g As Integer, _ h As String, i As Integer, j As Integer, k As Integer, l As Integer) = (1, 2, 3, 4, 5, 6, 7, "Alice", 2, 3, 4, 5) System.Console.Write($"{x.a} {x.b} {x.c} {x.d} {x.e} {x.f} {x.g} {x.h} {x.i} {x.j} {x.k} {x.l}") End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1 2 3 4 5 6 7 Alice 2 3 4 5]]>, sourceSymbolValidator:=Sub(m As ModuleSymbol) Dim compilation = m.DeclaringCompilation Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().Single().Names(0) Assert.Equal("x As (a As System.Int32, b As System.Int32, c As System.Int32, d As System.Int32, " _ + "e As System.Int32, f As System.Int32, g As System.Int32, h As System.String, " _ + "i As System.Int32, j As System.Int32, k As System.Int32, l As System.Int32)", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub) verifier.VerifyDiagnostics() End Sub <ConditionalFact(GetType(NoIOperationValidation))> Public Sub HugeTupleCreationParses() Dim b = New StringBuilder() b.Append("(") For i As Integer = 0 To 2000 b.Append("1, ") Next b.Append("1)") Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x = <%= b.ToString() %> End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertNoDiagnostics() End Sub <ConditionalFact(GetType(NoIOperationValidation))> Public Sub HugeTupleDeclarationParses() Dim b = New StringBuilder() b.Append("(") For i As Integer = 0 To 3000 b.Append("Integer, ") Next b.Append("Integer)") Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x As <%= b.ToString() %>; End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) End Sub <Fact> <WorkItem(13302, "https://github.com/dotnet/roslyn/issues/13302")> Public Sub GenericTupleWithoutTupleLibrary_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub Main() Dim x = M(Of Integer, Boolean)() System.Console.Write($"{x.first} {x.second}") End Sub Public Shared Function M(Of T1, T2)() As (first As T1, second As T2) return (Nothing, Nothing) End Function End Class ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported. Public Shared Function M(Of T1, T2)() As (first As T1, second As T2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Function M(Of T1, T2)() As (first As T1, second As T2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported. return (Nothing, Nothing) ~~~~~~~~~~~~~~~~~~ </errors>) Dim mTuple = DirectCast(comp.GetMember(Of MethodSymbol)("C.M").ReturnType, NamedTypeSymbol) Assert.True(mTuple.IsTupleType) Assert.Equal(TypeKind.Error, mTuple.TupleUnderlyingType.TypeKind) Assert.Equal(SymbolKind.ErrorType, mTuple.TupleUnderlyingType.Kind) Assert.IsAssignableFrom(Of ErrorTypeSymbol)(mTuple.TupleUnderlyingType) Assert.Equal(TypeKind.Struct, mTuple.TypeKind) 'AssertTupleTypeEquality(mTuple) Assert.False(mTuple.IsImplicitlyDeclared) 'Assert.Equal("Predefined type 'System.ValueTuple`2' is not defined or imported", mTuple.GetUseSiteDiagnostic().GetMessage(CultureInfo.InvariantCulture)) Assert.Null(mTuple.BaseType) Assert.False(DirectCast(mTuple, TupleTypeSymbol).UnderlyingDefinitionToMemberMap.Any()) Dim mFirst = DirectCast(mTuple.GetMembers("first").Single(), FieldSymbol) Assert.IsType(Of TupleErrorFieldSymbol)(mFirst) Assert.True(mFirst.IsTupleField) Assert.Equal("first", mFirst.Name) Assert.Same(mFirst, mFirst.OriginalDefinition) Assert.True(mFirst.Equals(mFirst)) Assert.Null(mFirst.TupleUnderlyingField) Assert.Null(mFirst.AssociatedSymbol) Assert.Same(mTuple, mFirst.ContainingSymbol) Assert.True(mFirst.CustomModifiers.IsEmpty) Assert.True(mFirst.GetAttributes().IsEmpty) 'Assert.Null(mFirst.GetUseSiteDiagnostic()) Assert.False(mFirst.Locations.IsEmpty) Assert.Equal("first As T1", mFirst.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.False(mFirst.IsImplicitlyDeclared) Assert.Null(mFirst.TypeLayoutOffset) Assert.True(DirectCast(mFirst, IFieldSymbol).IsExplicitlyNamedTupleElement) Dim mItem1 = DirectCast(mTuple.GetMembers("Item1").Single(), FieldSymbol) Assert.IsType(Of TupleErrorFieldSymbol)(mItem1) Assert.True(mItem1.IsTupleField) Assert.Equal("Item1", mItem1.Name) Assert.Same(mItem1, mItem1.OriginalDefinition) Assert.True(mItem1.Equals(mItem1)) Assert.Null(mItem1.TupleUnderlyingField) Assert.Null(mItem1.AssociatedSymbol) Assert.Same(mTuple, mItem1.ContainingSymbol) Assert.True(mItem1.CustomModifiers.IsEmpty) Assert.True(mItem1.GetAttributes().IsEmpty) 'Assert.Null(mItem1.GetUseSiteDiagnostic()) Assert.True(mItem1.Locations.IsEmpty) Assert.True(mItem1.IsImplicitlyDeclared) Assert.Null(mItem1.TypeLayoutOffset) Assert.False(DirectCast(mItem1, IFieldSymbol).IsExplicitlyNamedTupleElement) End Sub <Fact> <WorkItem(13300, "https://github.com/dotnet/roslyn/issues/13300")> Public Sub GenericTupleWithoutTupleLibrary_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class C Function M(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)() As (T1, T2, T3, T4, T5, T6, T7, T8, T9) Throw New System.NotSupportedException() End Function End Class Namespace System Public Structure ValueTuple(Of T1, T2) End Structure End Namespace ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC37267: Predefined type 'ValueTuple(Of ,,,,,,,)' is not defined or imported. Function M(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)() As (T1, T2, T3, T4, T5, T6, T7, T8, T9) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub GenericTuple() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x = M(Of Integer, Boolean)() System.Console.Write($"{x.first} {x.second}") End Sub Shared Function M(Of T1, T2)() As (first As T1, second As T2) Return (Nothing, Nothing) End Function End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[0 False]]>) End Sub <Fact> Public Sub LongTupleCreation() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x = (1, 2, 3, 4, 5, 6, 7, "Alice", 2, 3, 4, 5, 6, 7, "Bob", 2, 3) System.Console.Write($"{x.Item1} {x.Item2} {x.Item3} {x.Item4} {x.Item5} {x.Item6} {x.Item7} {x.Item8} " _ + $"{x.Item9} {x.Item10} {x.Item11} {x.Item12} {x.Item13} {x.Item14} {x.Item15} {x.Item16} {x.Item17}") End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1 2 3 4 5 6 7 Alice 2 3 4 5 6 7 Bob 2 3]]>, sourceSymbolValidator:= Sub(m As ModuleSymbol) Dim compilation = m.DeclaringCompilation Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim x = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, " _ + "System.String, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, " _ + "System.String, System.Int32, System.Int32)", model.GetTypeInfo(x).Type.ToTestDisplayString()) End Sub) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleInLambda() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim f As System.Action(Of (Integer, String)) = Sub(x As (Integer, String)) System.Console.Write($"{x.Item1} {x.Item2}") f((42, "Alice")) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42 Alice]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleWithNamesInLambda() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim f As System.Action(Of (Integer, String)) = Sub(x As (a As Integer, b As String)) System.Console.Write($"{x.Item1} {x.Item2}") f((c:=42, d:="Alice")) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42 Alice]]>) End Sub <Fact> Public Sub TupleInProperty() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Property P As (a As Integer, b As String) Shared Sub Main() P = (42, "Alice") System.Console.Write($"{P.a} {P.b}") End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42 Alice]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub ExtensionMethodOnTuple() Dim comp = CompileAndVerify( <compilation> <file name="a.vb"> Module M &lt;System.Runtime.CompilerServices.Extension()&gt; Sub Extension(x As (a As Integer, b As String)) System.Console.Write($"{x.a} {x.b}") End Sub End Module Class C Shared Sub Main() Call (42, "Alice").Extension() End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:="42 Alice") End Sub <Fact> Public Sub TupleInOptionalParam() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Sub M(x As Integer, Optional y As (a As Integer, b As String) = (42, "Alice")) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics(<![CDATA[ BC30059: Constant expression is required. Sub M(x As Integer, Optional y As (a As Integer, b As String) = (42, "Alice")) ~~~~~~~~~~~~~ ]]>) End Sub <Fact> Public Sub TupleDefaultInOptionalParam() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() M() End Sub Shared Sub M(Optional x As (a As Integer, b As String) = Nothing) System.Console.Write($"{x.a} {x.b}") End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[0 ]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleAsNamedParam() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() M(y:=(42, "Alice"), x:=1) End Sub Shared Sub M(x As Integer, y As (a As Integer, b As String)) System.Console.Write($"{y.a} {y.Item2}") End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42 Alice]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub LongTupleCreationWithNames() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x = (a:=1, b:=2, c:=3, d:=4, e:=5, f:=6, g:=7, h:="Alice", i:=2, j:=3, k:=4, l:=5, m:=6, n:=7, o:="Bob", p:=2, q:=3) System.Console.Write($"{x.a} {x.b} {x.c} {x.d} {x.e} {x.f} {x.g} {x.h} {x.i} {x.j} {x.k} {x.l} {x.m} {x.n} {x.o} {x.p} {x.q}") End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1 2 3 4 5 6 7 Alice 2 3 4 5 6 7 Bob 2 3]]>, sourceSymbolValidator:= Sub(m As ModuleSymbol) Dim compilation = m.DeclaringCompilation Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim x = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(a As System.Int32, b As System.Int32, c As System.Int32, d As System.Int32, e As System.Int32, f As System.Int32, g As System.Int32, " _ + "h As System.String, i As System.Int32, j As System.Int32, k As System.Int32, l As System.Int32, m As System.Int32, n As System.Int32, " _ + "o As System.String, p As System.Int32, q As System.Int32)", model.GetTypeInfo(x).Type.ToTestDisplayString()) End Sub) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleCreationWithInferredNamesWithVB15() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Dim e As Integer = 5 Dim f As Integer = 6 Dim instance As C = Nothing Sub M() Dim a As Integer = 1 Dim b As Integer = 3 Dim Item4 As Integer = 4 Dim g As Integer = 7 Dim Rest As Integer = 9 Dim y As (x As Integer, Integer, b As Integer, Integer, Integer, Integer, f As Integer, Integer, Integer, Integer) = (a, (a), b:=2, b, Item4, instance.e, Me.f, g, g, Rest) Dim z = (x:=b, b) System.Console.Write(y) System.Console.Write(z) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15), sourceSymbolValidator:= Sub(m As ModuleSymbol) Dim compilation = m.DeclaringCompilation Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim yTuple = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(0) Assert.Equal("(a As System.Int32, System.Int32, b As System.Int32, System.Int32, System.Int32, e As System.Int32, f As System.Int32, System.Int32, System.Int32, System.Int32)", model.GetTypeInfo(yTuple).Type.ToTestDisplayString()) Dim zTuple = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(1) Assert.Equal("(x As System.Int32, b As System.Int32)", model.GetTypeInfo(zTuple).Type.ToTestDisplayString()) End Sub) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleCreationWithInferredNames() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Dim e As Integer = 5 Dim f As Integer = 6 Dim instance As C = Nothing Sub M() Dim a As Integer = 1 Dim b As Integer = 3 Dim Item4 As Integer = 4 Dim g As Integer = 7 Dim Rest As Integer = 9 Dim y As (x As Integer, Integer, b As Integer, Integer, Integer, Integer, f As Integer, Integer, Integer, Integer) = (a, (a), b:=2, b, Item4, instance.e, Me.f, g, g, Rest) Dim z = (x:=b, b) System.Console.Write(y) System.Console.Write(z) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3), sourceSymbolValidator:= Sub(m As ModuleSymbol) Dim compilation = m.DeclaringCompilation Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim yTuple = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(0) Assert.Equal("(a As System.Int32, System.Int32, b As System.Int32, System.Int32, System.Int32, e As System.Int32, f As System.Int32, System.Int32, System.Int32, System.Int32)", model.GetTypeInfo(yTuple).Type.ToTestDisplayString()) Dim zTuple = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(1) Assert.Equal("(x As System.Int32, b As System.Int32)", model.GetTypeInfo(zTuple).Type.ToTestDisplayString()) End Sub) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleCreationWithInferredNames2() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Dim e As Integer = 5 Dim instance As C = Nothing Function M() As Integer Dim y As (Integer?, object) = (instance?.e, (e, instance.M())) System.Console.Write(y) Return 42 End Function End Class </file> </compilation>, references:=s_valueTupleRefs, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3), sourceSymbolValidator:= Sub(m As ModuleSymbol) Dim compilation = m.DeclaringCompilation Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim yTuple = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(0) Assert.Equal("(e As System.Nullable(Of System.Int32), (e As System.Int32, M As System.Int32))", model.GetTypeInfo(yTuple).Type.ToTestDisplayString()) End Sub) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub MissingMemberAccessWithVB15() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Sub M() Dim a As Integer = 1 Dim t = (a, 2) System.Console.Write(t.A) System.Console.Write(GetTuple().a) End Sub Function GetTuple() As (Integer, Integer) Return (1, 2) End Function End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15)) comp.AssertTheseDiagnostics(<errors> BC37289: Tuple element name 'a' is inferred. Please use language version 15.3 or greater to access an element by its inferred name. System.Console.Write(t.A) ~~~ BC30456: 'a' is not a member of '(Integer, Integer)'. System.Console.Write(GetTuple().a) ~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub UseSiteDiagnosticOnTupleField() Dim missingComp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UseSiteDiagnosticOnTupleField_missingComp"> <file name="missing.vb"> Public Class Missing End Class </file> </compilation>) missingComp.VerifyDiagnostics() Dim libComp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="lib.vb"> Public Class C Public Shared Function GetTuple() As (Missing, Integer) Throw New System.Exception() End Function End Class </file> </compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef, missingComp.ToMetadataReference()}) libComp.VerifyDiagnostics() Dim source = <compilation> <file name="a.vb"> Class D Sub M() System.Console.Write(C.GetTuple().Item1) End Sub End Class </file> </compilation> Dim comp15 = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef, libComp.ToMetadataReference()}, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15)) comp15.AssertTheseDiagnostics(<errors> BC30652: Reference required to assembly 'UseSiteDiagnosticOnTupleField_missingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'Missing'. Add one to your project. System.Console.Write(C.GetTuple().Item1) ~~~~~~~~~~~~ </errors>) Dim comp15_3 = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef, libComp.ToMetadataReference()}, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3)) comp15_3.AssertTheseDiagnostics(<errors> BC30652: Reference required to assembly 'UseSiteDiagnosticOnTupleField_missingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'Missing'. Add one to your project. System.Console.Write(C.GetTuple().Item1) ~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub UseSiteDiagnosticOnTupleField2() Dim source = <compilation> <file name="a.vb"> Class C Sub M() Dim a = 1 Dim t = (a, 2) System.Console.Write(t.a) End Sub End Class Namespace System Public Structure ValueTuple(Of T1, T2) Public Sub New(item1 As T1, item2 As T2) End Sub End Structure End Namespace </file> </compilation> Dim comp15 = CreateCompilationWithMscorlib40AndVBRuntime(source, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15)) comp15.AssertTheseDiagnostics(<errors> BC35000: Requested operation is not available because the runtime library function 'ValueTuple.Item1' is not defined. System.Console.Write(t.a) ~~~ </errors>) Dim comp15_3 = CreateCompilationWithMscorlib40AndVBRuntime(source, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3)) comp15_3.AssertTheseDiagnostics(<errors> BC35000: Requested operation is not available because the runtime library function 'ValueTuple.Item1' is not defined. System.Console.Write(t.a) ~~~ </errors>) End Sub <Fact> Public Sub MissingMemberAccessWithExtensionWithVB15() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime( <compilation> <file name="a.vb"> Imports System Class C Sub M() Dim a As Integer = 1 Dim t = (a, 2) System.Console.Write(t.A) System.Console.Write(GetTuple().a) End Sub Function GetTuple() As (Integer, Integer) Return (1, 2) End Function End Class Module Extensions &lt;System.Runtime.CompilerServices.Extension()&gt; Public Function A(self As (Integer, Action)) As String Return Nothing End Function End Module </file> </compilation>, references:={ValueTupleRef, Net451.SystemRuntime, Net451.SystemCore}, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15)) comp.AssertTheseDiagnostics(<errors> BC37289: Tuple element name 'a' is inferred. Please use language version 15.3 or greater to access an element by its inferred name. System.Console.Write(t.A) ~~~ BC30456: 'a' is not a member of '(Integer, Integer)'. System.Console.Write(GetTuple().a) ~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub MissingMemberAccessWithVB15_3() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Sub M() Dim a As Integer = 1 Dim t = (a, 2) System.Console.Write(t.b) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3)) comp.AssertTheseDiagnostics(<errors> BC30456: 'b' is not a member of '(a As Integer, Integer)'. System.Console.Write(t.b) ~~~ </errors>) End Sub <Fact> Public Sub InferredNamesInLinq() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Collections.Generic Imports System.Linq Class C Dim f1 As Integer = 0 Dim f2 As Integer = 1 Shared Sub Main(list As IEnumerable(Of C)) Dim result = list.Select(Function(c) (c.f1, c.f2)).Where(Function(t) t.f2 = 1) ' t and result have names f1 and f2 System.Console.Write(result.Count()) End Sub End Class </file> </compilation>, references:={ValueTupleRef, SystemRuntimeFacadeRef, LinqAssemblyRef}, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3), sourceSymbolValidator:= Sub(m As ModuleSymbol) Dim compilation = m.DeclaringCompilation Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Dim result = tree.GetRoot().DescendantNodes().OfType(Of VariableDeclaratorSyntax)().ElementAt(2).Names(0) Dim resultSymbol = model.GetDeclaredSymbol(result) Assert.Equal("result As System.Collections.Generic.IEnumerable(Of (f1 As System.Int32, f2 As System.Int32))", resultSymbol.ToTestDisplayString()) End Sub) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub InferredNamesInTernary() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim i = 1 Dim flag = False Dim t = If(flag, (i, 2), (i, 3)) System.Console.Write(t.i) End Sub End Class </file> </compilation>, references:={ValueTupleRef, SystemRuntimeFacadeRef, LinqAssemblyRef}, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3), expectedOutput:="1") verifier.VerifyDiagnostics() End Sub <Fact> Public Sub InferredNames_ExtensionNowFailsInVB15ButNotVB15_3() Dim source = <compilation> <file name="a.vb"> Imports System Class C Shared Sub Main() Dim M As Action = Sub() Console.Write("lambda") Dim t = (1, M) t.M() End Sub End Class Module Extensions &lt;System.Runtime.CompilerServices.Extension()&gt; Public Sub M(self As (Integer, Action)) Console.Write("extension") End Sub End Module </file> </compilation> ' When VB 15 shipped, no tuple element would be found/inferred, so the extension method was called. ' The VB 15.3 compiler disallows that, even when LanguageVersion is 15. Dim comp15 = CreateCompilationWithMscorlib45AndVBRuntime(source, references:={ValueTupleRef, Net451.SystemRuntime, Net451.SystemCore}, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15)) comp15.AssertTheseDiagnostics(<errors> BC37289: Tuple element name 'M' is inferred. Please use language version 15.3 or greater to access an element by its inferred name. t.M() ~~~ </errors>) Dim verifier15_3 = CompileAndVerify(source, allReferences:={ValueTupleRef, Net451.mscorlib, Net451.SystemCore, Net451.SystemRuntime, Net451.MicrosoftVisualBasic}, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3), expectedOutput:="lambda") verifier15_3.VerifyDiagnostics() End Sub <Fact> Public Sub InferredName_Conversion() Dim source = <compilation> <file> Class C Shared Sub F(t As (Object, Object)) End Sub Shared Sub G(o As Object) Dim t = (1, o) F(t) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef, SystemCoreRef}, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15)) comp.AssertTheseEmitDiagnostics(<errors/>) End Sub <Fact> Public Sub LongTupleWithArgumentEvaluation() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x = (a:=PrintAndReturn(1), b:=2, c:=3, d:=PrintAndReturn(4), e:=5, f:=6, g:=PrintAndReturn(7), h:=PrintAndReturn("Alice"), i:=2, j:=3, k:=4, l:=5, m:=6, n:=PrintAndReturn(7), o:=PrintAndReturn("Bob"), p:=2, q:=PrintAndReturn(3)) End Sub Shared Function PrintAndReturn(Of T)(i As T) System.Console.Write($"{i} ") Return i End Function End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1 4 7 Alice 7 Bob 3]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DuplicateTupleMethodsNotAllowed() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C Function M(a As (String, String)) As (Integer, Integer) Return new System.ValueTuple(Of Integer, Integer)(a.Item1.Length, a.Item2.Length) End Function Function M(a As System.ValueTuple(Of String, String)) As System.ValueTuple(Of Integer, Integer) Return (a.Item1.Length, a.Item2.Length) End Function End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30269: 'Public Function M(a As (String, String)) As (Integer, Integer)' has multiple definitions with identical signatures. Function M(a As (String, String)) As (Integer, Integer) ~ </errors>) End Sub <Fact> Public Sub TupleArrays() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Interface I Function M(a As (Integer, Integer)()) As System.ValueTuple(Of Integer, Integer)() End Interface Class C Implements I Shared Sub Main() Dim i As I = new C() Dim r = i.M(new System.ValueTuple(Of Integer, Integer)() { new System.ValueTuple(Of Integer, Integer)(1, 2) }) System.Console.Write($"{r(0).Item1} {r(0).Item2}") End Sub Public Function M(a As (Integer, Integer)()) As System.ValueTuple(Of Integer, Integer)() Implements I.M Return New System.ValueTuple(Of Integer, Integer)() { (a(0).Item1, a(0).Item2) } End Function End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1 2]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleRef() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim r = (1, 2) M(r) System.Console.Write($"{r.Item1} {r.Item2}") End Sub Shared Sub M(ByRef a As (Integer, Integer)) System.Console.WriteLine($"{a.Item1} {a.Item2}") a = (3, 4) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1 2 3 4]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleOut() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim r As (Integer, Integer) M(r) System.Console.Write($"{r.Item1} {r.Item2}") End Sub Shared Sub M(ByRef a As (Integer, Integer)) System.Console.WriteLine($"{a.Item1} {a.Item2}") a = (1, 2) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[0 0 1 2]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleTypeArgs() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim a = (1, "Alice") Dim r = M(Of Integer, String)(a) System.Console.Write($"{r.Item1} {r.Item2}") End Sub Shared Function M(Of T1, T2)(a As (T1, T2)) As (T1, T2) Return a End Function End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1 Alice]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub NullableTuple() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() M((1, "Alice")) End Sub Shared Sub M(a As (Integer, String)?) System.Console.Write($"{a.HasValue} {a.Value.Item1} {a.Value.Item2}") End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[True 1 Alice]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleUnsupportedInUsingStatement() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports VT2 = (Integer, Integer) ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC30203: Identifier expected. Imports VT2 = (Integer, Integer) ~ BC40056: Namespace or type specified in the Imports '' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. Imports VT2 = (Integer, Integer) ~~~~~~~~~~~~~~~~~~ BC32093: 'Of' required when specifying type arguments for a generic type or method. Imports VT2 = (Integer, Integer) ~ </errors>) End Sub <Fact> Public Sub MissingTypeInAlias() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports VT2 = System.ValueTuple(Of Integer, Integer) ' ValueTuple is referenced but does not exist Namespace System Public Class Bogus End Class End Namespace Namespace TuplesCrash2 Class C Shared Sub Main() End Sub End Class End Namespace ]]></file> </compilation>) Dim tree = comp.SyntaxTrees.First() Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = model.LookupStaticMembers(234) For i As Integer = 0 To tree.GetText().Length model.LookupStaticMembers(i) Next ' Didn't crash End Sub <Fact> Public Sub MultipleDefinitionsOfValueTuple() Dim source1 = <compilation> <file name="a.vb"> Public Module M1 &lt;System.Runtime.CompilerServices.Extension()&gt; Public Sub Extension(x As Integer, y As (Integer, Integer)) System.Console.Write("M1.Extension") End Sub End Module <%= s_trivial2uple %></file> </compilation> Dim source2 = <compilation> <file name="a.vb"> Public Module M2 &lt;System.Runtime.CompilerServices.Extension()&gt; Public Sub Extension(x As Integer, y As (Integer, Integer)) System.Console.Write("M2.Extension") End Sub End Module <%= s_trivial2uple %></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40AndVBRuntime(source1, additionalRefs:={MscorlibRef_v46}, assemblyName:="comp1") comp1.AssertNoDiagnostics() Dim comp2 = CreateCompilationWithMscorlib40AndVBRuntime(source2, additionalRefs:={MscorlibRef_v46}, assemblyName:="comp2") comp2.AssertNoDiagnostics() Dim source = <compilation> <file name="a.vb"> Imports System Imports M1 Imports M2 Class C Public Shared Sub Main() Dim x As Integer = 0 x.Extension((1, 1)) End Sub End Class </file> </compilation> Dim comp3 = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={comp1.ToMetadataReference(), comp2.ToMetadataReference()}) comp3.AssertTheseDiagnostics( <errors> BC30521: Overload resolution failed because no accessible 'Extension' is most specific for these arguments: Extension method 'Public Sub Extension(y As (Integer, Integer))' defined in 'M1': Not most specific. Extension method 'Public Sub Extension(y As (Integer, Integer))' defined in 'M2': Not most specific. x.Extension((1, 1)) ~~~~~~~~~ BC37305: Predefined type 'ValueTuple(Of ,)' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' x.Extension((1, 1)) ~~~~~~ </errors>) Dim comp4 = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={comp1.ToMetadataReference()}, options:=TestOptions.DebugExe) comp4.AssertTheseDiagnostics( <errors> BC40056: Namespace or type specified in the Imports 'M2' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. Imports M2 ~~ </errors>) CompileAndVerify(comp4, expectedOutput:=<![CDATA[M1.Extension]]>) End Sub <Fact> Public Sub Tuple2To8Members() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Console Class C Shared Sub Main() Write((1, 2).Item1) Write((1, 2).Item2) WriteLine() Write((1, 2, 3).Item1) Write((1, 2, 3).Item2) Write((1, 2, 3).Item3) WriteLine() Write((1, 2, 3, 4).Item1) Write((1, 2, 3, 4).Item2) Write((1, 2, 3, 4).Item3) Write((1, 2, 3, 4).Item4) WriteLine() Write((1, 2, 3, 4, 5).Item1) Write((1, 2, 3, 4, 5).Item2) Write((1, 2, 3, 4, 5).Item3) Write((1, 2, 3, 4, 5).Item4) Write((1, 2, 3, 4, 5).Item5) WriteLine() Write((1, 2, 3, 4, 5, 6).Item1) Write((1, 2, 3, 4, 5, 6).Item2) Write((1, 2, 3, 4, 5, 6).Item3) Write((1, 2, 3, 4, 5, 6).Item4) Write((1, 2, 3, 4, 5, 6).Item5) Write((1, 2, 3, 4, 5, 6).Item6) WriteLine() Write((1, 2, 3, 4, 5, 6, 7).Item1) Write((1, 2, 3, 4, 5, 6, 7).Item2) Write((1, 2, 3, 4, 5, 6, 7).Item3) Write((1, 2, 3, 4, 5, 6, 7).Item4) Write((1, 2, 3, 4, 5, 6, 7).Item5) Write((1, 2, 3, 4, 5, 6, 7).Item6) Write((1, 2, 3, 4, 5, 6, 7).Item7) WriteLine() Write((1, 2, 3, 4, 5, 6, 7, 8).Item1) Write((1, 2, 3, 4, 5, 6, 7, 8).Item2) Write((1, 2, 3, 4, 5, 6, 7, 8).Item3) Write((1, 2, 3, 4, 5, 6, 7, 8).Item4) Write((1, 2, 3, 4, 5, 6, 7, 8).Item5) Write((1, 2, 3, 4, 5, 6, 7, 8).Item6) Write((1, 2, 3, 4, 5, 6, 7, 8).Item7) Write((1, 2, 3, 4, 5, 6, 7, 8).Item8) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[12 123 1234 12345 123456 1234567 12345678]]>) End Sub <Fact> Public Sub CreateTupleTypeSymbol_BadArguments() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Assert.Throws(Of ArgumentNullException)(Sub() comp.CreateTupleTypeSymbol(underlyingType:=Nothing, elementNames:=Nothing)) Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, intType) Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("Item1"))) Assert.Contains(CodeAnalysisResources.TupleElementNameCountMismatch, ex.Message) Dim tree = VisualBasicSyntaxTree.ParseText("Class C") Dim loc1 = Location.Create(tree, New TextSpan(0, 1)) ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(vt2, elementLocations:=ImmutableArray.Create(loc1))) Assert.Contains(CodeAnalysisResources.TupleElementLocationCountMismatch, ex.Message) End Sub <Fact> Public Sub CreateTupleTypeSymbol_WithValueTuple() Dim tupleComp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><%= s_trivial2uple %></file> </compilation>) Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef, tupleComp.ToMetadataReference()}) Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType) Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create(Of String)(Nothing, Nothing)) Assert.True(tupleWithoutNames.IsTupleType) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.TupleUnderlyingType.Kind) Assert.Equal("(System.Int32, System.String)", tupleWithoutNames.ToTestDisplayString()) Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault) Assert.Equal((New String() {"System.Int32", "System.String"}), ElementTypeNames(tupleWithoutNames)) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind) Assert.All(tupleWithoutNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()), Sub(Loc) Assert.Equal(Loc, Nothing)) End Sub Private Shared Function ElementTypeNames(tuple As INamedTypeSymbol) As IEnumerable(Of String) Return tuple.TupleElements.Select(Function(t) t.Type.ToTestDisplayString()) End Function <Fact> Public Sub CreateTupleTypeSymbol_Locations() Dim tupleComp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><%= s_trivial2uple %></file> </compilation>) Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef, tupleComp.ToMetadataReference()}) Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType) Dim tree = VisualBasicSyntaxTree.ParseText("Class C") Dim loc1 = Location.Create(tree, New TextSpan(0, 1)) Dim loc2 = Location.Create(tree, New TextSpan(1, 1)) Dim tuple = comp.CreateTupleTypeSymbol( vt2, ImmutableArray.Create("i1", "i2"), ImmutableArray.Create(loc1, loc2)) Assert.True(tuple.IsTupleType) Assert.Equal(SymbolKind.NamedType, tuple.TupleUnderlyingType.Kind) Assert.Equal("(i1 As System.Int32, i2 As System.String)", tuple.ToTestDisplayString()) Assert.Equal(New String() {"System.Int32", "System.String"}, ElementTypeNames(tuple)) Assert.Equal(SymbolKind.NamedType, tuple.Kind) Assert.Equal(loc1, tuple.GetMembers("i1").Single.Locations.Single()) Assert.Equal(loc2, tuple.GetMembers("i2").Single.Locations.Single()) End Sub <Fact> Public Sub CreateTupleTypeSymbol_NoNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType) Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(vt2, Nothing) Assert.True(tupleWithoutNames.IsTupleType) Assert.Equal(SymbolKind.ErrorType, tupleWithoutNames.TupleUnderlyingType.Kind) Assert.Equal("(System.Int32, System.String)", tupleWithoutNames.ToTestDisplayString()) Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault) Assert.Equal(New String() {"System.Int32", "System.String"}, ElementTypeNames(tupleWithoutNames)) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind) Assert.All(tupleWithoutNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()), Sub(Loc) Assert.Equal(Loc, Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_WithNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType) Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("Alice", "Bob")) Assert.True(tupleWithoutNames.IsTupleType) Assert.Equal(SymbolKind.ErrorType, tupleWithoutNames.TupleUnderlyingType.Kind) Assert.Equal("(Alice As System.Int32, Bob As System.String)", tupleWithoutNames.ToTestDisplayString()) Assert.Equal(New String() {"Alice", "Bob"}, GetTupleElementNames(tupleWithoutNames)) Assert.Equal(New String() {"System.Int32", "System.String"}, ElementTypeNames(tupleWithoutNames)) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind) Assert.All(tupleWithoutNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()), Sub(Loc) Assert.Equal(Loc, Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_WithSomeNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim vt3 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T3).Construct(intType, stringType, intType) Dim tupleWithSomeNames = comp.CreateTupleTypeSymbol(vt3, ImmutableArray.Create(Nothing, "Item2", "Charlie")) Assert.True(tupleWithSomeNames.IsTupleType) Assert.Equal(SymbolKind.ErrorType, tupleWithSomeNames.TupleUnderlyingType.Kind) Assert.Equal("(System.Int32, Item2 As System.String, Charlie As System.Int32)", tupleWithSomeNames.ToTestDisplayString()) Assert.Equal(New String() {Nothing, "Item2", "Charlie"}, GetTupleElementNames(tupleWithSomeNames)) Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32"}, ElementTypeNames(tupleWithSomeNames)) Assert.Equal(SymbolKind.NamedType, tupleWithSomeNames.Kind) Assert.All(tupleWithSomeNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()), Sub(Loc) Assert.Equal(Loc, Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_WithBadNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, intType) Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("Item2", "Item1")) Assert.True(tupleWithoutNames.IsTupleType) Assert.Equal("(Item2 As System.Int32, Item1 As System.Int32)", tupleWithoutNames.ToTestDisplayString()) Assert.Equal(New String() {"Item2", "Item1"}, GetTupleElementNames(tupleWithoutNames)) Assert.Equal(New String() {"System.Int32", "System.Int32"}, ElementTypeNames(tupleWithoutNames)) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind) Assert.All(tupleWithoutNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()), Sub(Loc) Assert.Equal(Loc, Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_Tuple8NoNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim vt8 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest). Construct(intType, stringType, intType, stringType, intType, stringType, intType, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T1).Construct(stringType)) Dim tuple8WithoutNames = comp.CreateTupleTypeSymbol(vt8, Nothing) Assert.True(tuple8WithoutNames.IsTupleType) Assert.Equal("(System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, System.String)", tuple8WithoutNames.ToTestDisplayString()) Assert.True(GetTupleElementNames(tuple8WithoutNames).IsDefault) Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String"}, ElementTypeNames(tuple8WithoutNames)) Assert.All(tuple8WithoutNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()), Sub(Loc) Assert.Equal(Loc, Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_Tuple8WithNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim vt8 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest). Construct(intType, stringType, intType, stringType, intType, stringType, intType, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T1).Construct(stringType)) Dim tuple8WithNames = comp.CreateTupleTypeSymbol(vt8, ImmutableArray.Create("Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8")) Assert.True(tuple8WithNames.IsTupleType) Assert.Equal("(Alice1 As System.Int32, Alice2 As System.String, Alice3 As System.Int32, Alice4 As System.String, Alice5 As System.Int32, Alice6 As System.String, Alice7 As System.Int32, Alice8 As System.String)", tuple8WithNames.ToTestDisplayString()) Assert.Equal(New String() {"Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8"}, GetTupleElementNames(tuple8WithNames)) Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String"}, ElementTypeNames(tuple8WithNames)) Assert.All(tuple8WithNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()), Sub(Loc) Assert.Equal(Loc, Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_Tuple9NoNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim vt9 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest). Construct(intType, stringType, intType, stringType, intType, stringType, intType, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(stringType, intType)) Dim tuple9WithoutNames = comp.CreateTupleTypeSymbol(vt9, Nothing) Assert.True(tuple9WithoutNames.IsTupleType) Assert.Equal("(System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32)", tuple9WithoutNames.ToTestDisplayString()) Assert.True(GetTupleElementNames(tuple9WithoutNames).IsDefault) Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32"}, ElementTypeNames(tuple9WithoutNames)) Assert.All(tuple9WithoutNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()), Sub(Loc) Assert.Equal(Loc, Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_Tuple9WithNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim vt9 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest). Construct(intType, stringType, intType, stringType, intType, stringType, intType, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(stringType, intType)) Dim tuple9WithNames = comp.CreateTupleTypeSymbol(vt9, ImmutableArray.Create("Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8", "Alice9")) Assert.True(tuple9WithNames.IsTupleType) Assert.Equal("(Alice1 As System.Int32, Alice2 As System.String, Alice3 As System.Int32, Alice4 As System.String, Alice5 As System.Int32, Alice6 As System.String, Alice7 As System.Int32, Alice8 As System.String, Alice9 As System.Int32)", tuple9WithNames.ToTestDisplayString()) Assert.Equal(New String() {"Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8", "Alice9"}, GetTupleElementNames(tuple9WithNames)) Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32"}, ElementTypeNames(tuple9WithNames)) Assert.All(tuple9WithNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()), Sub(Loc) Assert.Equal(Loc, Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_Tuple9WithDefaultNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim vt9 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest). Construct(intType, stringType, intType, stringType, intType, stringType, intType, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(stringType, intType)) Dim tuple9WithNames = comp.CreateTupleTypeSymbol(vt9, ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9")) Assert.True(tuple9WithNames.IsTupleType) Assert.Equal("(Item1 As System.Int32, Item2 As System.String, Item3 As System.Int32, Item4 As System.String, Item5 As System.Int32, Item6 As System.String, Item7 As System.Int32, Item8 As System.String, Item9 As System.Int32)", tuple9WithNames.ToTestDisplayString()) Assert.Equal(New String() {"Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9"}, GetTupleElementNames(tuple9WithNames)) Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32"}, ElementTypeNames(tuple9WithNames)) Assert.All(tuple9WithNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()), Sub(Loc) Assert.Equal(Loc, Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_ElementTypeIsError() Dim tupleComp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><%= s_trivial2uple %></file> </compilation>) Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef, tupleComp.ToMetadataReference()}) Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, ErrorTypeSymbol.UnknownResultType) Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(vt2, Nothing) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind) Dim types = tupleWithoutNames.TupleElements.SelectAsArray(Function(e) e.Type) Assert.Equal(2, types.Length) Assert.Equal(SymbolKind.NamedType, types(0).Kind) Assert.Equal(SymbolKind.ErrorType, types(1).Kind) Assert.All(tupleWithoutNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()), Sub(Loc) Assert.Equal(Loc, Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_BadNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) Dim intType As NamedTypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, intType) Dim vt3 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T3).Construct(intType, intType, intType) ' Illegal VB identifier, space and null Dim tuple2 = comp.CreateTupleTypeSymbol(vt3, ImmutableArray.Create("123", " ", Nothing)) Assert.Equal({"123", " ", Nothing}, GetTupleElementNames(tuple2)) ' Reserved keywords Dim tuple3 = comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("return", "class")) Assert.Equal({"return", "class"}, GetTupleElementNames(tuple3)) Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(underlyingType:=intType)) Assert.Contains(CodeAnalysisResources.TupleUnderlyingTypeMustBeTupleCompatible, ex.Message) End Sub <Fact> Public Sub CreateTupleTypeSymbol_EmptyNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) Dim intType As NamedTypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, intType) ' Illegal VB identifier and empty Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("123", ""))) Assert.Contains(CodeAnalysisResources.TupleElementNameEmpty, ex.Message) Assert.Contains("1", ex.Message) End Sub <Fact> Public Sub CreateTupleTypeSymbol_CSharpElements() Dim csSource = "public class C { }" Dim csComp = CreateCSharpCompilation("CSharp", csSource, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) csComp.VerifyDiagnostics() Dim csType = DirectCast(csComp.GlobalNamespace.GetMembers("C").Single(), INamedTypeSymbol) Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(csType, Nothing)) Assert.Contains(VBResources.NotAVbSymbol, ex.Message) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_BadArguments() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Assert.Throws(Of ArgumentNullException)(Sub() comp.CreateTupleTypeSymbol(elementTypes:=Nothing, elementNames:=Nothing)) ' 0-tuple and 1-tuple are not supported at this point Assert.Throws(Of ArgumentException)(Sub() comp.CreateTupleTypeSymbol(elementTypes:=ImmutableArray(Of ITypeSymbol).Empty, elementNames:=Nothing)) Assert.Throws(Of ArgumentException)(Sub() comp.CreateTupleTypeSymbol(elementTypes:=ImmutableArray.Create(intType), elementNames:=Nothing)) ' If names are provided, you need as many as element types Assert.Throws(Of ArgumentException)(Sub() comp.CreateTupleTypeSymbol(elementTypes:=ImmutableArray.Create(intType, intType), elementNames:=ImmutableArray.Create("Item1"))) ' null types aren't allowed Assert.Throws(Of ArgumentNullException)(Sub() comp.CreateTupleTypeSymbol(elementTypes:=ImmutableArray.Create(intType, Nothing), elementNames:=Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_WithValueTuple() Dim tupleComp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><%= s_trivial2uple %></file> </compilation>) Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef, tupleComp.ToMetadataReference()}) Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType), ImmutableArray.Create(Of String)(Nothing, Nothing)) Assert.True(tupleWithoutNames.IsTupleType) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.TupleUnderlyingType.Kind) Assert.Equal("(System.Int32, System.String)", tupleWithoutNames.ToTestDisplayString()) Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault) Assert.Equal(New String() {"System.Int32", "System.String"}, ElementTypeNames(tupleWithoutNames)) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_Locations() Dim tupleComp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><%= s_trivial2uple %></file> </compilation>) Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef, tupleComp.ToMetadataReference()}) Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim tree = VisualBasicSyntaxTree.ParseText("Class C") Dim loc1 = Location.Create(tree, New TextSpan(0, 1)) Dim loc2 = Location.Create(tree, New TextSpan(1, 1)) Dim tuple = comp.CreateTupleTypeSymbol( ImmutableArray.Create(intType, stringType), ImmutableArray.Create("i1", "i2"), ImmutableArray.Create(loc1, loc2)) Assert.True(tuple.IsTupleType) Assert.Equal(SymbolKind.NamedType, tuple.TupleUnderlyingType.Kind) Assert.Equal("(i1 As System.Int32, i2 As System.String)", tuple.ToTestDisplayString()) Assert.Equal(New String() {"System.Int32", "System.String"}, ElementTypeNames(tuple)) Assert.Equal(SymbolKind.NamedType, tuple.Kind) Assert.Equal(loc1, tuple.GetMembers("i1").Single().Locations.Single()) Assert.Equal(loc2, tuple.GetMembers("i2").Single().Locations.Single()) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_NoNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType), Nothing) Assert.True(tupleWithoutNames.IsTupleType) Assert.Equal(SymbolKind.ErrorType, tupleWithoutNames.TupleUnderlyingType.Kind) Assert.Equal("(System.Int32, System.String)", tupleWithoutNames.ToTestDisplayString()) Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault) Assert.Equal(New String() {"System.Int32", "System.String"}, ElementTypeNames(tupleWithoutNames)) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_WithNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType), ImmutableArray.Create("Alice", "Bob")) Assert.True(tupleWithoutNames.IsTupleType) Assert.Equal(SymbolKind.ErrorType, tupleWithoutNames.TupleUnderlyingType.Kind) Assert.Equal("(Alice As System.Int32, Bob As System.String)", tupleWithoutNames.ToTestDisplayString()) Assert.Equal(New String() {"Alice", "Bob"}, GetTupleElementNames(tupleWithoutNames)) Assert.Equal(New String() {"System.Int32", "System.String"}, ElementTypeNames(tupleWithoutNames)) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_WithBadNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, intType), ImmutableArray.Create("Item2", "Item1")) Assert.True(tupleWithoutNames.IsTupleType) Assert.Equal("(Item2 As System.Int32, Item1 As System.Int32)", tupleWithoutNames.ToTestDisplayString()) Assert.Equal(New String() {"Item2", "Item1"}, GetTupleElementNames(tupleWithoutNames)) Assert.Equal(New String() {"System.Int32", "System.Int32"}, ElementTypeNames(tupleWithoutNames)) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_Tuple8NoNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim tuple8WithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType, intType, stringType, intType, stringType, intType, stringType), Nothing) Assert.True(tuple8WithoutNames.IsTupleType) Assert.Equal("(System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, System.String)", tuple8WithoutNames.ToTestDisplayString()) Assert.True(GetTupleElementNames(tuple8WithoutNames).IsDefault) Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String"}, ElementTypeNames(tuple8WithoutNames)) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_Tuple8WithNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim tuple8WithNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType, intType, stringType, intType, stringType, intType, stringType), ImmutableArray.Create("Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8")) Assert.True(tuple8WithNames.IsTupleType) Assert.Equal("(Alice1 As System.Int32, Alice2 As System.String, Alice3 As System.Int32, Alice4 As System.String, Alice5 As System.Int32, Alice6 As System.String, Alice7 As System.Int32, Alice8 As System.String)", tuple8WithNames.ToTestDisplayString()) Assert.Equal(New String() {"Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8"}, GetTupleElementNames(tuple8WithNames)) Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String"}, ElementTypeNames(tuple8WithNames)) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_Tuple9NoNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim tuple9WithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType, intType, stringType, intType, stringType, intType, stringType, intType), Nothing) Assert.True(tuple9WithoutNames.IsTupleType) Assert.Equal("(System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32)", tuple9WithoutNames.ToTestDisplayString()) Assert.True(GetTupleElementNames(tuple9WithoutNames).IsDefault) Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32"}, ElementTypeNames(tuple9WithoutNames)) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_Tuple9WithNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim tuple9WithNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType, intType, stringType, intType, stringType, intType, stringType, intType), ImmutableArray.Create("Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8", "Alice9")) Assert.True(tuple9WithNames.IsTupleType) Assert.Equal("(Alice1 As System.Int32, Alice2 As System.String, Alice3 As System.Int32, Alice4 As System.String, Alice5 As System.Int32, Alice6 As System.String, Alice7 As System.Int32, Alice8 As System.String, Alice9 As System.Int32)", tuple9WithNames.ToTestDisplayString()) Assert.Equal(New String() {"Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8", "Alice9"}, GetTupleElementNames(tuple9WithNames)) Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32"}, ElementTypeNames(tuple9WithNames)) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_ElementTypeIsError() Dim tupleComp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><%= s_trivial2uple %></file> </compilation>) Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef, tupleComp.ToMetadataReference()}) Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, ErrorTypeSymbol.UnknownResultType), Nothing) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind) Dim types = tupleWithoutNames.TupleElements.SelectAsArray(Function(e) e.Type) Assert.Equal(2, types.Length) Assert.Equal(SymbolKind.NamedType, types(0).Kind) Assert.Equal(SymbolKind.ErrorType, types(1).Kind) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_BadNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) ' Illegal VB identifier and blank Dim tuple2 = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, intType), ImmutableArray.Create("123", " ")) Assert.Equal({"123", " "}, GetTupleElementNames(tuple2)) ' Reserved keywords Dim tuple3 = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, intType), ImmutableArray.Create("return", "class")) Assert.Equal({"return", "class"}, GetTupleElementNames(tuple3)) End Sub Private Shared Function GetTupleElementNames(tuple As INamedTypeSymbol) As ImmutableArray(Of String) Dim elements = tuple.TupleElements If elements.All(Function(e) e.IsImplicitlyDeclared) Then Return Nothing End If Return elements.SelectAsArray(Function(e) e.ProvidedTupleElementNameOrNull) End Function <Fact> Public Sub CreateTupleTypeSymbol2_CSharpElements() Dim csSource = "public class C { }" Dim csComp = CreateCSharpCompilation("CSharp", csSource, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) csComp.VerifyDiagnostics() Dim csType = DirectCast(csComp.GlobalNamespace.GetMembers("C").Single(), INamedTypeSymbol) Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String) Assert.Throws(Of ArgumentException)(Sub() comp.CreateTupleTypeSymbol(ImmutableArray.Create(stringType, csType), Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_ComparingSymbols() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Dim F As System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (a As String, b As String)) End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) Dim tuple1 = comp.GlobalNamespace.GetMember(Of SourceMemberFieldSymbol)("C.F").Type Dim intType = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType = comp.GetSpecialType(SpecialType.System_String) Dim twoStrings = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(stringType, stringType) Dim twoStringsWithNames = DirectCast(comp.CreateTupleTypeSymbol(twoStrings, ImmutableArray.Create("a", "b")), TypeSymbol) Dim tuple2Underlying = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest).Construct(intType, intType, intType, intType, intType, intType, intType, twoStringsWithNames) Dim tuple2 = DirectCast(comp.CreateTupleTypeSymbol(tuple2Underlying), TypeSymbol) Dim tuple3 = DirectCast(comp.CreateTupleTypeSymbol(ImmutableArray.Create(Of ITypeSymbol)(intType, intType, intType, intType, intType, intType, intType, stringType, stringType), ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "a", "b")), TypeSymbol) Dim tuple4 = DirectCast(comp.CreateTupleTypeSymbol(CType(tuple1.TupleUnderlyingType, INamedTypeSymbol), ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "a", "b")), TypeSymbol) Assert.True(tuple1.Equals(tuple2)) 'Assert.True(tuple1.Equals(tuple2, TypeCompareKind.IgnoreDynamicAndTupleNames)) Assert.False(tuple1.Equals(tuple3)) 'Assert.True(tuple1.Equals(tuple3, TypeCompareKind.IgnoreDynamicAndTupleNames)) Assert.False(tuple1.Equals(tuple4)) 'Assert.True(tuple1.Equals(tuple4, TypeCompareKind.IgnoreDynamicAndTupleNames)) End Sub <Fact> Public Sub TupleMethodsOnNonTupleType() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) Dim intType As NamedTypeSymbol = comp.GetSpecialType(SpecialType.System_String) Assert.False(intType.IsTupleType) Assert.True(intType.TupleElementNames.IsDefault) Assert.True(intType.TupleElementTypes.IsDefault) End Sub <Fact> <WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")> Public Sub CreateTupleTypeSymbol_UnderlyingType_DefaultArgs() Dim comp = CreateCompilation( "Module Program Private F As (Integer, String) End Module") Dim tuple1 = DirectCast(DirectCast(comp.GetMember("Program.F"), IFieldSymbol).Type, INamedTypeSymbol) Dim underlyingType = tuple1.TupleUnderlyingType Dim tuple2 = comp.CreateTupleTypeSymbol(underlyingType) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(underlyingType, Nothing) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(underlyingType, Nothing, Nothing) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(underlyingType, Nothing, Nothing, Nothing) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNames:=Nothing) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementLocations:=Nothing) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations:=Nothing) Assert.True(tuple1.Equals(tuple2)) End Sub <Fact> <WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")> Public Sub CreateTupleTypeSymbol_ElementTypes_DefaultArgs() Dim comp = CreateCompilation( "Module Program Private F As (Integer, String) End Module") Dim tuple1 = DirectCast(DirectCast(comp.GetMember("Program.F"), IFieldSymbol).Type, INamedTypeSymbol) Dim elementTypes = tuple1.TupleElements.SelectAsArray(Function(e) e.Type) Dim tuple2 = comp.CreateTupleTypeSymbol(elementTypes) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(elementTypes, Nothing) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(elementTypes, Nothing, Nothing) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(elementTypes, Nothing, Nothing, Nothing) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNames:=Nothing) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementLocations:=Nothing) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations:=Nothing) Assert.True(tuple1.Equals(tuple2)) End Sub <Fact> <WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")> Public Sub CreateTupleTypeSymbol_UnderlyingType_WithNullableAnnotations_01() Dim comp = CreateCompilation( "Module Program Private F As (Integer, String) End Module") Dim tuple1 = DirectCast(DirectCast(comp.GetMember("Program.F"), IFieldSymbol).Type, INamedTypeSymbol) Dim underlyingType = tuple1.TupleUnderlyingType Dim tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations:=Nothing) Assert.True(tuple1.Equals(tuple2)) Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations:=ImmutableArray(Of NullableAnnotation).Empty)) Assert.Contains(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, ex.Message) tuple2 = comp.CreateTupleTypeSymbol( underlyingType, elementNullableAnnotations:=ImmutableArray.Create(CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None)) Assert.True(tuple1.Equals(tuple2)) Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString()) tuple2 = comp.CreateTupleTypeSymbol( underlyingType, elementNullableAnnotations:=ImmutableArray.Create(CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableAnnotation.Annotated)) Assert.True(tuple1.Equals(tuple2)) Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString()) tuple2 = comp.CreateTupleTypeSymbol( underlyingType, elementNullableAnnotations:=ImmutableArray.Create(CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.None)) Assert.True(tuple1.Equals(tuple2)) Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString()) End Sub <Fact> <WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")> Public Sub CreateTupleTypeSymbol_UnderlyingType_WithNullableAnnotations_02() Dim comp = CreateCompilation( "Module Program Private F As (_1 As Object, _2 As Object, _3 As Object, _4 As Object, _5 As Object, _6 As Object, _7 As Object, _8 As Object, _9 As Object) End Module") Dim tuple1 = DirectCast(DirectCast(comp.GetMember("Program.F"), IFieldSymbol).Type, INamedTypeSymbol) Dim underlyingType = tuple1.TupleUnderlyingType Dim tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations:=Nothing) Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)) Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString()) Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations:=CreateAnnotations(CodeAnalysis.NullableAnnotation.NotAnnotated, 8))) Assert.Contains(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, ex.Message) tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations:=CreateAnnotations(CodeAnalysis.NullableAnnotation.None, 9)) Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)) Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString()) tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations:=CreateAnnotations(CodeAnalysis.NullableAnnotation.Annotated, 9)) Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)) Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString()) End Sub <Fact> <WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")> Public Sub CreateTupleTypeSymbol_ElementTypes_WithNullableAnnotations_01() Dim comp = CreateCompilation( "Module Program Private F As (Integer, String) End Module") Dim tuple1 = DirectCast(DirectCast(comp.GetMember("Program.F"), IFieldSymbol).Type, INamedTypeSymbol) Dim elementTypes = tuple1.TupleElements.SelectAsArray(Function(e) e.Type) Dim tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations:=Nothing) Assert.True(tuple1.Equals(tuple2)) Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations:=ImmutableArray(Of NullableAnnotation).Empty)) Assert.Contains(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, ex.Message) tuple2 = comp.CreateTupleTypeSymbol( elementTypes, elementNullableAnnotations:=ImmutableArray.Create(CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None)) Assert.True(tuple1.Equals(tuple2)) Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString()) tuple2 = comp.CreateTupleTypeSymbol( elementTypes, elementNullableAnnotations:=ImmutableArray.Create(CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableAnnotation.Annotated)) Assert.True(tuple1.Equals(tuple2)) Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString()) tuple2 = comp.CreateTupleTypeSymbol( elementTypes, elementNullableAnnotations:=ImmutableArray.Create(CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.None)) Assert.True(tuple1.Equals(tuple2)) Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString()) End Sub <Fact> <WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")> Public Sub CreateTupleTypeSymbol_ElementTypes_WithNullableAnnotations_02() Dim comp = CreateCompilation( "Module Program Private F As (_1 As Object, _2 As Object, _3 As Object, _4 As Object, _5 As Object, _6 As Object, _7 As Object, _8 As Object, _9 As Object) End Module") Dim tuple1 = DirectCast(DirectCast(comp.GetMember("Program.F"), IFieldSymbol).Type, INamedTypeSymbol) Dim elementTypes = tuple1.TupleElements.SelectAsArray(Function(e) e.Type) Dim tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations:=Nothing) Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)) Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString()) Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations:=CreateAnnotations(CodeAnalysis.NullableAnnotation.NotAnnotated, 8))) Assert.Contains(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, ex.Message) tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations:=CreateAnnotations(CodeAnalysis.NullableAnnotation.None, 9)) Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)) Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString()) tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations:=CreateAnnotations(CodeAnalysis.NullableAnnotation.Annotated, 9)) Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)) Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString()) End Sub Private Shared Function CreateAnnotations(annotation As CodeAnalysis.NullableAnnotation, n As Integer) As ImmutableArray(Of CodeAnalysis.NullableAnnotation) Return ImmutableArray.CreateRange(Enumerable.Range(0, n).Select(Function(i) annotation)) End Function Private Shared Function TypeEquals(a As ITypeSymbol, b As ITypeSymbol, compareKind As TypeCompareKind) As Boolean Return TypeSymbol.Equals(DirectCast(a, TypeSymbol), DirectCast(b, TypeSymbol), compareKind) End Function <Fact> Public Sub TupleTargetTypeAndConvert01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class C Shared Sub Main() ' This works Dim x1 As (Short, String) = (1, "hello") Dim x2 As (Short, String) = DirectCast((1, "hello"), (Long, String)) Dim x3 As (a As Short, b As String) = DirectCast((1, "hello"), (c As Long, d As String)) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30512: Option Strict On disallows implicit conversions from '(Long, String)' to '(Short, String)'. Dim x2 As (Short, String) = DirectCast((1, "hello"), (Long, String)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from '(c As Long, d As String)' to '(a As Short, b As String)'. Dim x3 As (a As Short, b As String) = DirectCast((1, "hello"), (c As Long, d As String)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleTargetTypeAndConvert02() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x2 As (Short, String) = DirectCast((1, "hello"), (Byte, String)) System.Console.WriteLine(x2) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(1, hello)]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 41 (0x29) .maxstack 3 .locals init (System.ValueTuple(Of Byte, String) V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldstr "hello" IL_0008: call "Sub System.ValueTuple(Of Byte, String)..ctor(Byte, String)" IL_000d: ldloc.0 IL_000e: ldfld "System.ValueTuple(Of Byte, String).Item1 As Byte" IL_0013: ldloc.0 IL_0014: ldfld "System.ValueTuple(Of Byte, String).Item2 As String" IL_0019: newobj "Sub System.ValueTuple(Of Short, String)..ctor(Short, String)" IL_001e: box "System.ValueTuple(Of Short, String)" IL_0023: call "Sub System.Console.WriteLine(Object)" IL_0028: ret } ]]>) End Sub <Fact> Public Sub TupleImplicitConversionFail01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class C Shared Sub Main() Dim x As (Integer, Integer) x = (Nothing, Nothing, Nothing) x = (1, 2, 3) x = (1, "string") x = (1, 1, garbage) x = (1, 1, ) x = (Nothing, Nothing) ' ok x = (1, Nothing) ' ok x = (1, Function(t) t) x = Nothing ' ok End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30311: Value of type '(Object, Object, Object)' cannot be converted to '(Integer, Integer)'. x = (Nothing, Nothing, Nothing) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30311: Value of type '(Integer, Integer, Integer)' cannot be converted to '(Integer, Integer)'. x = (1, 2, 3) ~~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Integer'. x = (1, "string") ~~~~~~~~ BC30451: 'garbage' is not declared. It may be inaccessible due to its protection level. x = (1, 1, garbage) ~~~~~~~ BC30201: Expression expected. x = (1, 1, ) ~ BC36625: Lambda expression cannot be converted to 'Integer' because 'Integer' is not a delegate type. x = (1, Function(t) t) ~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleExplicitConversionFail01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class C Shared Sub Main() Dim x As (Integer, Integer) x = DirectCast((Nothing, Nothing, Nothing), (Integer, Integer)) x = DirectCast((1, 2, 3), (Integer, Integer)) x = DirectCast((1, "string"), (Integer, Integer)) ' ok x = DirectCast((1, 1, garbage), (Integer, Integer)) x = DirectCast((1, 1, ), (Integer, Integer)) x = DirectCast((Nothing, Nothing), (Integer, Integer)) ' ok x = DirectCast((1, Nothing), (Integer, Integer)) ' ok x = DirectCast((1, Function(t) t), (Integer, Integer)) x = DirectCast(Nothing, (Integer, Integer)) ' ok End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30311: Value of type '(Object, Object, Object)' cannot be converted to '(Integer, Integer)'. x = DirectCast((Nothing, Nothing, Nothing), (Integer, Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30311: Value of type '(Integer, Integer, Integer)' cannot be converted to '(Integer, Integer)'. x = DirectCast((1, 2, 3), (Integer, Integer)) ~~~~~~~~~ BC30451: 'garbage' is not declared. It may be inaccessible due to its protection level. x = DirectCast((1, 1, garbage), (Integer, Integer)) ~~~~~~~ BC30201: Expression expected. x = DirectCast((1, 1, ), (Integer, Integer)) ~ BC36625: Lambda expression cannot be converted to 'Integer' because 'Integer' is not a delegate type. x = DirectCast((1, Function(t) t), (Integer, Integer)) ~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleImplicitConversionFail02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class C Shared Sub Main() Dim x As System.ValueTuple(Of Integer, Integer) x = (Nothing, Nothing, Nothing) x = (1, 2, 3) x = (1, "string") x = (1, 1, garbage) x = (1, 1, ) x = (Nothing, Nothing) ' ok x = (1, Nothing) ' ok x = (1, Function(t) t) x = Nothing ' ok End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30311: Value of type '(Object, Object, Object)' cannot be converted to '(Integer, Integer)'. x = (Nothing, Nothing, Nothing) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30311: Value of type '(Integer, Integer, Integer)' cannot be converted to '(Integer, Integer)'. x = (1, 2, 3) ~~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Integer'. x = (1, "string") ~~~~~~~~ BC30451: 'garbage' is not declared. It may be inaccessible due to its protection level. x = (1, 1, garbage) ~~~~~~~ BC30201: Expression expected. x = (1, 1, ) ~ BC36625: Lambda expression cannot be converted to 'Integer' because 'Integer' is not a delegate type. x = (1, Function(t) t) ~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleInferredLambdaStrictOn() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class C Shared Sub Main() Dim valid = (1, Function() Nothing) Dim x = (Nothing, Function(t) t) Dim y = (1, Function(t) t) Dim z = (Function(t) t, Function(t) t) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred. Dim x = (Nothing, Function(t) t) ~ BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred. Dim y = (1, Function(t) t) ~ BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred. Dim z = (Function(t) t, Function(t) t) ~ BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred. Dim z = (Function(t) t, Function(t) t) ~ </errors>) End Sub <Fact()> Public Sub TupleInferredLambdaStrictOff() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict Off Class C Shared Sub Main() Dim valid = (1, Function() Nothing) Test(valid) Dim x = (Nothing, Function(t) t) Test(x) Dim y = (1, Function(t) t) Test(y) End Sub shared function Test(of T)(x as T) as T System.Console.WriteLine(GetType(T)) return x End Function End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.ValueTuple`2[System.Int32,VB$AnonymousDelegate_0`1[System.Object]] System.ValueTuple`2[System.Object,VB$AnonymousDelegate_1`2[System.Object,System.Object]] System.ValueTuple`2[System.Int32,VB$AnonymousDelegate_1`2[System.Object,System.Object]] ]]>) End Sub <Fact> Public Sub TupleImplicitConversionFail03() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class C Shared Sub Main() Dim x As (String, String) x = (Nothing, Nothing, Nothing) x = (1, 2, 3) x = (1, "string") x = (1, 1, garbage) x = (1, 1, ) x = (Nothing, Nothing) ' ok x = (1, Nothing) ' ok x = (1, Function(t) t) x = Nothing ' ok End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30311: Value of type '(Object, Object, Object)' cannot be converted to '(String, String)'. x = (Nothing, Nothing, Nothing) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30311: Value of type '(Integer, Integer, Integer)' cannot be converted to '(String, String)'. x = (1, 2, 3) ~~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'. x = (1, "string") ~ BC30451: 'garbage' is not declared. It may be inaccessible due to its protection level. x = (1, 1, garbage) ~~~~~~~ BC30201: Expression expected. x = (1, 1, ) ~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'. x = (1, Nothing) ' ok ~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'. x = (1, Function(t) t) ~ BC36625: Lambda expression cannot be converted to 'String' because 'String' is not a delegate type. x = (1, Function(t) t) ~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleImplicitConversionFail04() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class C Shared Sub Main() Dim x As ((Integer, Integer), Integer) x = ((Nothing, Nothing, Nothing), 1) x = ((1, 2, 3), 1) x = ((1, "string"), 1) x = ((1, 1, garbage), 1) x = ((1, 1, ), 1) x = ((Nothing, Nothing), 1) ' ok x = ((1, Nothing), 1) ' ok x = ((1, Function(t) t), 1) x = (Nothing, 1) ' ok End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30311: Value of type '(Object, Object, Object)' cannot be converted to '(Integer, Integer)'. x = ((Nothing, Nothing, Nothing), 1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30311: Value of type '(Integer, Integer, Integer)' cannot be converted to '(Integer, Integer)'. x = ((1, 2, 3), 1) ~~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Integer'. x = ((1, "string"), 1) ~~~~~~~~ BC30451: 'garbage' is not declared. It may be inaccessible due to its protection level. x = ((1, 1, garbage), 1) ~~~~~~~ BC30201: Expression expected. x = ((1, 1, ), 1) ~ BC36625: Lambda expression cannot be converted to 'Integer' because 'Integer' is not a delegate type. x = ((1, Function(t) t), 1) ~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleImplicitConversionFail05() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub Main() Dim x As (x0 As System.ValueTuple(Of Integer, Integer), x1 As Integer, x2 As Integer, x3 As Integer, x4 As Integer, x5 As Integer, x6 As Integer, x7 As Integer, x8 As Integer, x9 As Integer, x10 As Integer) x = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) x = ((0, 0.0), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8 ) x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9.1, 10) x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9 x = ((0, 0), 1, 2, 3, 4, oops, 6, 7, oopsss, 9, 10) x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9) x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, (1, 1, 1), 10) End Sub End Class ]]><%= s_trivial2uple %><%= s_trivialRemainingTuples %></file> </compilation>) ' Intentionally not including 3-tuple for use-site errors comp.AssertTheseDiagnostics( <errors> BC30311: Value of type 'Integer' cannot be converted to '(Integer, Integer)'. x = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) ~ BC30311: Value of type '((Integer, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)' cannot be converted to '(x0 As (Integer, Integer), x1 As Integer, x2 As Integer, x3 As Integer, x4 As Integer, x5 As Integer, x6 As Integer, x7 As Integer, x8 As Integer, x9 As Integer, x10 As Integer)'. x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30311: Value of type '((Integer, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)' cannot be converted to '(x0 As (Integer, Integer), x1 As Integer, x2 As Integer, x3 As Integer, x4 As Integer, x5 As Integer, x6 As Integer, x7 As Integer, x8 As Integer, x9 As Integer, x10 As Integer)'. x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8 ) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of ,,)' is not defined or imported. x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30452: Operator '=' is not defined for types '(x0 As (Integer, Integer), x1 As Integer, x2 As Integer, x3 As Integer, x4 As Integer, x5 As Integer, x6 As Integer, x7 As Integer, x8 As Integer, x9 As Integer, x10 As Integer)' and '((Integer, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'. x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of ,,)' is not defined or imported. x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30198: ')' expected. x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9 ~ BC30198: ')' expected. x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9 ~ BC30451: 'oops' is not declared. It may be inaccessible due to its protection level. x = ((0, 0), 1, 2, 3, 4, oops, 6, 7, oopsss, 9, 10) ~~~~ BC30451: 'oopsss' is not declared. It may be inaccessible due to its protection level. x = ((0, 0), 1, 2, 3, 4, oops, 6, 7, oopsss, 9, 10) ~~~~~~ BC30311: Value of type '((Integer, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)' cannot be converted to '(x0 As (Integer, Integer), x1 As Integer, x2 As Integer, x3 As Integer, x4 As Integer, x5 As Integer, x6 As Integer, x7 As Integer, x8 As Integer, x9 As Integer, x10 As Integer)'. x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of ,,)' is not defined or imported. x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30311: Value of type '(Integer, Integer, Integer)' cannot be converted to 'Integer'. x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, (1, 1, 1), 10) ~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of ,,)' is not defined or imported. x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, (1, 1, 1), 10) ~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleImplicitConversionFail06() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Class C Shared Sub Main() Dim l As Func(Of String) = Function() 1 Dim x As (String, Func(Of String)) = (Nothing, Function() 1) Dim l1 As Func(Of (String, String)) = Function() (Nothing, 1.1) Dim x1 As (String, Func(Of (String, String))) = (Nothing, Function() (Nothing, 1.1)) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'. Dim l As Func(Of String) = Function() 1 ~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'. Dim x As (String, Func(Of String)) = (Nothing, Function() 1) ~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'String'. Dim l1 As Func(Of (String, String)) = Function() (Nothing, 1.1) ~~~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'String'. Dim x1 As (String, Func(Of (String, String))) = (Nothing, Function() (Nothing, 1.1)) ~~~ </errors>) End Sub <Fact> Public Sub TupleExplicitConversionFail06() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Class C Shared Sub Main() Dim l As Func(Of String) = Function() 1 Dim x As (String, Func(Of String)) = DirectCast((Nothing, Function() 1), (String, Func(Of String))) Dim l1 As Func(Of (String, String)) = DirectCast(Function() (Nothing, 1.1), Func(Of (String, String))) Dim x1 As (String, Func(Of (String, String))) = DirectCast((Nothing, Function() (Nothing, 1.1)), (String, Func(Of (String, String)))) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'. Dim l As Func(Of String) = Function() 1 ~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'. Dim x As (String, Func(Of String)) = DirectCast((Nothing, Function() 1), (String, Func(Of String))) ~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'String'. Dim l1 As Func(Of (String, String)) = DirectCast(Function() (Nothing, 1.1), Func(Of (String, String))) ~~~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'String'. Dim x1 As (String, Func(Of (String, String))) = DirectCast((Nothing, Function() (Nothing, 1.1)), (String, Func(Of (String, String)))) ~~~ </errors>) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub TupleCTypeNullableConversionWithTypelessTuple() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Class C Shared Sub Main() Dim x As (Integer, String)? = CType((1, Nothing), (Integer, String)?) Console.Write(x) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertNoDiagnostics() CompileAndVerify(comp, expectedOutput:="(1, )") Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(1, Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(node).Kind) Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) Dim [ctype] = tree.GetRoot().DescendantNodes().OfType(Of CTypeExpressionSyntax)().Single() Assert.Equal("CType((1, Nothing), (Integer, String)?)", [ctype].ToString()) comp.VerifyOperationTree([ctype], expectedOperationTree:= <![CDATA[ IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of (System.Int32, System.String))) (Syntax: 'CType((1, N ... , String)?)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.String)) (Syntax: '(1, Nothing)') NaturalType: null Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') ]]>.Value) End Sub <Fact> Public Sub TupleDirectCastNullableConversionWithTypelessTuple() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Class C Shared Sub Main() Dim x As (Integer, String)? = DirectCast((1, Nothing), (Integer, String)?) Console.Write(x) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertNoDiagnostics() CompileAndVerify(comp, expectedOutput:="(1, )") Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(1, Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(node).Kind) Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) End Sub <Fact> Public Sub TupleTryCastNullableConversionWithTypelessTuple() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Class C Shared Sub Main() Dim x As (Integer, String)? = TryCast((1, Nothing), (Integer, String)?) Console.Write(x) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics(<errors> BC30792: 'TryCast' operand must be reference type, but '(Integer, String)?' is a value type. Dim x As (Integer, String)? = TryCast((1, Nothing), (Integer, String)?) ~~~~~~~~~~~~~~~~~~ </errors>) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(1, Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(node).Kind) Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) End Sub <Fact> Public Sub TupleTryCastNullableConversionWithTypelessTuple2() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Class C Shared Sub M(Of T)() Dim x = TryCast((0, Nothing), C(Of Integer, T)) Console.Write(x) End Sub End Class Class C(Of T, U) End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics(<errors> BC30311: Value of type '(Integer, Object)' cannot be converted to 'C(Of Integer, T)'. Dim x = TryCast((0, Nothing), C(Of Integer, T)) ~~~~~~~~~~~~ </errors>) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(0, Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(node).Kind) Assert.Equal("C(Of System.Int32, T)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("C(Of System.Int32, T)", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) End Sub <Fact> Public Sub TupleImplicitNullableConversionWithTypelessTuple() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class C Shared Sub Main() Dim x As (Integer, String)? = (1, Nothing) System.Console.Write(x) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertNoDiagnostics() CompileAndVerify(comp, expectedOutput:="(1, )") Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(1, Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(node).Kind) End Sub <Fact> Public Sub ImplicitConversionOnTypelessTupleWithUserConversion() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Structure C Shared Sub Main() Dim x As C = (1, Nothing) Dim y As C? = (2, Nothing) End Sub Public Shared Widening Operator CType(ByVal d As (Integer, String)) As C Return New C() End Operator End Structure ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics(<errors> BC30311: Value of type '(Integer, Object)' cannot be converted to 'C?'. Dim y As C? = (2, Nothing) ~~~~~~~~~~~~ </errors>) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim firstTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(0) Assert.Equal("(1, Nothing)", firstTuple.ToString()) Assert.Null(model.GetTypeInfo(firstTuple).Type) Assert.Equal("C", model.GetTypeInfo(firstTuple).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Narrowing Or ConversionKind.UserDefined, model.GetConversion(firstTuple).Kind) Dim secondTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(1) Assert.Equal("(2, Nothing)", secondTuple.ToString()) Assert.Null(model.GetTypeInfo(secondTuple).Type) Assert.Equal("System.Nullable(Of C)", model.GetTypeInfo(secondTuple).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.DelegateRelaxationLevelNone, model.GetConversion(secondTuple).Kind) End Sub <Fact> Public Sub DirectCastOnTypelessTupleWithUserConversion() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Structure C Shared Sub Main() Dim x = DirectCast((1, Nothing), C) Dim y = DirectCast((2, Nothing), C?) End Sub Public Shared Widening Operator CType(ByVal d As (Integer, String)) As C Return New C() End Operator End Structure ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics(<errors> BC30311: Value of type '(Integer, Object)' cannot be converted to 'C'. Dim x = DirectCast((1, Nothing), C) ~~~~~~~~~~~~ BC30311: Value of type '(Integer, Object)' cannot be converted to 'C?'. Dim y = DirectCast((2, Nothing), C?) ~~~~~~~~~~~~ </errors>) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim firstTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(0) Assert.Equal("(1, Nothing)", firstTuple.ToString()) Assert.Null(model.GetTypeInfo(firstTuple).Type) Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(firstTuple).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(firstTuple).Kind) Dim secondTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(1) Assert.Equal("(2, Nothing)", secondTuple.ToString()) Assert.Null(model.GetTypeInfo(secondTuple).Type) Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(secondTuple).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(secondTuple).Kind) End Sub <Fact> Public Sub TryCastOnTypelessTupleWithUserConversion() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Structure C Shared Sub Main() Dim x = TryCast((1, Nothing), C) Dim y = TryCast((2, Nothing), C?) End Sub Public Shared Widening Operator CType(ByVal d As (Integer, String)) As C Return New C() End Operator End Structure ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics(<errors> BC30792: 'TryCast' operand must be reference type, but 'C' is a value type. Dim x = TryCast((1, Nothing), C) ~ BC30792: 'TryCast' operand must be reference type, but 'C?' is a value type. Dim y = TryCast((2, Nothing), C?) ~~ </errors>) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim firstTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(0) Assert.Equal("(1, Nothing)", firstTuple.ToString()) Assert.Null(model.GetTypeInfo(firstTuple).Type) Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(firstTuple).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(firstTuple).Kind) Dim secondTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(1) Assert.Equal("(2, Nothing)", secondTuple.ToString()) Assert.Null(model.GetTypeInfo(secondTuple).Type) Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(secondTuple).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(secondTuple).Kind) End Sub <Fact> Public Sub CTypeOnTypelessTupleWithUserConversion() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Structure C Shared Sub Main() Dim x = CType((1, Nothing), C) Dim y = CType((2, Nothing), C?) End Sub Public Shared Widening Operator CType(ByVal d As (Integer, String)) As C Return New C() End Operator End Structure ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics(<errors> BC30311: Value of type '(Integer, Object)' cannot be converted to 'C?'. Dim y = CType((2, Nothing), C?) ~~~~~~~~~~~~ </errors>) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim firstTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(0) Assert.Equal("(1, Nothing)", firstTuple.ToString()) Assert.Null(model.GetTypeInfo(firstTuple).Type) Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(firstTuple).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(firstTuple).Kind) Dim secondTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(1) Assert.Equal("(2, Nothing)", secondTuple.ToString()) Assert.Null(model.GetTypeInfo(secondTuple).Type) Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(secondTuple).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(secondTuple).Kind) End Sub <Fact> Public Sub TupleTargetTypeLambda() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Imports System Class C Shared Sub Test(d As Func(Of Func(Of (Short, Short)))) Console.WriteLine("short") End Sub Shared Sub Test(d As Func(Of Func(Of (Byte, Byte)))) Console.WriteLine("byte") End Sub Shared Sub Main() Test(Function() Function() DirectCast((1, 1), (Byte, Byte))) Test(Function() Function() (1, 1)) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30521: Overload resolution failed because no accessible 'Test' is most specific for these arguments: 'Public Shared Sub Test(d As Func(Of Func(Of (Short, Short))))': Not most specific. 'Public Shared Sub Test(d As Func(Of Func(Of (Byte, Byte))))': Not most specific. Test(Function() Function() DirectCast((1, 1), (Byte, Byte))) ~~~~ BC30521: Overload resolution failed because no accessible 'Test' is most specific for these arguments: 'Public Shared Sub Test(d As Func(Of Func(Of (Short, Short))))': Not most specific. 'Public Shared Sub Test(d As Func(Of Func(Of (Byte, Byte))))': Not most specific. Test(Function() Function() (1, 1)) ~~~~ </errors>) End Sub <Fact> Public Sub TupleTargetTypeLambda1() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Imports System Class C Shared Sub Test(d As Func(Of (Func(Of Short), Integer))) Console.WriteLine("short") End Sub Shared Sub Test(d As Func(Of (Func(Of Byte), Integer))) Console.WriteLine("byte") End Sub Shared Sub Main() Test(Function() (Function() CType(1, Byte), 1)) Test(Function() (Function() 1, 1)) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30521: Overload resolution failed because no accessible 'Test' is most specific for these arguments: 'Public Shared Sub Test(d As Func(Of (Func(Of Short), Integer)))': Not most specific. 'Public Shared Sub Test(d As Func(Of (Func(Of Byte), Integer)))': Not most specific. Test(Function() (Function() CType(1, Byte), 1)) ~~~~ BC30521: Overload resolution failed because no accessible 'Test' is most specific for these arguments: 'Public Shared Sub Test(d As Func(Of (Func(Of Short), Integer)))': Not most specific. 'Public Shared Sub Test(d As Func(Of (Func(Of Byte), Integer)))': Not most specific. Test(Function() (Function() 1, 1)) ~~~~ </errors>) End Sub <Fact> Public Sub TargetTypingOverload01() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C Shared Sub Main() Test((Nothing, Nothing)) Test((1, 1)) Test((Function() 7, Function() 8), 2) End Sub Shared Sub Test(Of T)(x As (T, T)) Console.WriteLine("first") End Sub Shared Sub Test(x As (Object, Object)) Console.WriteLine("second") End Sub Shared Sub Test(Of T)(x As (Func(Of T), Func(Of T)), y As T) Console.WriteLine("third") Console.WriteLine(x.Item1().ToString()) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[second first third 7]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TargetTypingOverload02() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Class C Shared Sub Main() Test1((Function() 7, Function() 8)) Test2(Function() 7, Function() 8) End Sub Shared Sub Test1(Of T)(x As (T, T)) Console.WriteLine("first") End Sub Shared Sub Test1(x As (Object, Object)) Console.WriteLine("second") End Sub Shared Sub Test1(Of T)(x As (Func(Of T), Func(Of T))) Console.WriteLine("third") Console.WriteLine(x.Item1().ToString()) End Sub Shared Sub Test2(Of T)(x As T, y as T) Console.WriteLine("first") End Sub Shared Sub Test2(x As Object, y as Object) Console.WriteLine("second") End Sub Shared Sub Test2(Of T)(x As Func(Of T), y as Func(Of T)) Console.WriteLine("third") End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:= "first first") verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TargetTypingNullable01() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C Shared Sub Main() Dim x = M1() Test(x) End Sub Shared Function M1() As (a As Integer, b As Double)? Return (1, 2) End Function Shared Sub Test(Of T)(arg As T) Console.WriteLine(GetType(T)) Console.WriteLine(arg) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[System.Nullable`1[System.ValueTuple`2[System.Int32,System.Double]] (1, 2)]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TargetTypingOverload01Long() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C Shared Sub Main() Test((Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing)) Test((1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) Test((Function() 11, Function() 12, Function() 13, Function() 14, Function() 15, Function() 16, Function() 17, Function() 18, Function() 19, Function() 20)) End Sub Shared Sub Test(Of T)(x As (T, T, T, T, T, T, T, T, T, T)) Console.WriteLine("first") End Sub Shared Sub Test(x As (Object, Object, Object, Object, Object, Object, Object, Object, Object, Object)) Console.WriteLine("second") End Sub Shared Sub Test(Of T)(x As (Func(Of T), Func(Of T), Func(Of T), Func(Of T), Func(Of T), Func(Of T), Func(Of T), Func(Of T), Func(Of T), Func(Of T)), y As T) Console.WriteLine("third") Console.WriteLine(x.Item1().ToString()) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[second first first]]>) verifier.VerifyDiagnostics() End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/12961")> Public Sub TargetTypingNullable02() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C Shared Sub Main() Dim x = M1() Test(x) End Sub Shared Function M1() As (a As Integer, b As String)? Return (1, Nothing) End Function Shared Sub Test(Of T)(arg As T) Console.WriteLine(GetType(T)) Console.WriteLine(arg) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[System.Nullable`1[System.ValueTuple`2[System.Int32,System.String]] (1, )]]>) verifier.VerifyDiagnostics() End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/12961")> Public Sub TargetTypingNullable02Long() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C Shared Sub Main() Dim x = M1() Console.WriteLine(x?.a) Console.WriteLine(x?.a8) Test(x) End Sub Shared Function M1() As (a As Integer, b As String, a1 As Integer, a2 As Integer, a3 As Integer, a4 As Integer, a5 As Integer, a6 As Integer, a7 As Integer, a8 As Integer)? Return (1, Nothing, 1, 2, 3, 4, 5, 6, 7, 8) End Function Shared Sub Test(Of T)(arg As T) Console.WriteLine(arg) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[System.Nullable`1[System.ValueTuple`2[System.Int32,System.String]] (1, )]]>) verifier.VerifyDiagnostics() End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/12961")> Public Sub TargetTypingNullableOverload() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C Shared Sub Main() Test((Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing)) ' Overload resolution fails Test(("a", "a", "a", "a", "a", "a", "a", "a", "a", "a")) Test((1, 1, 1, 1, 1, 1, 1, 1, 1, 1)) End Sub Shared Sub Test(x As (String, String, String, String, String, String, String, String, String, String)) Console.WriteLine("first") End Sub Shared Sub Test(x As (String, String, String, String, String, String, String, String, String, String)?) Console.WriteLine("second") End Sub Shared Sub Test(x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)?) Console.WriteLine("third") End Sub Shared Sub Test(x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)) Console.WriteLine("fourth") End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[first fourth]]>) verifier.VerifyDiagnostics() End Sub <Fact()> <WorkItem(13277, "https://github.com/dotnet/roslyn/issues/13277")> <WorkItem(14365, "https://github.com/dotnet/roslyn/issues/14365")> Public Sub CreateTupleTypeSymbol_UnderlyingTypeIsError() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef, TestReferences.SymbolsTests.netModule.netModule1}) Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim vt2 = comp.CreateErrorTypeSymbol(Nothing, "ValueTuple", 2).Construct(intType, intType) Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(underlyingType:=vt2)) Dim csComp = CreateCSharpCompilation("") Assert.Throws(Of ArgumentNullException)(Sub() comp.CreateErrorTypeSymbol(Nothing, Nothing, 2)) Assert.Throws(Of ArgumentException)(Sub() comp.CreateErrorTypeSymbol(Nothing, "a", -1)) Assert.Throws(Of ArgumentException)(Sub() comp.CreateErrorTypeSymbol(csComp.GlobalNamespace, "a", 1)) Assert.Throws(Of ArgumentNullException)(Sub() comp.CreateErrorNamespaceSymbol(Nothing, "a")) Assert.Throws(Of ArgumentNullException)(Sub() comp.CreateErrorNamespaceSymbol(csComp.GlobalNamespace, Nothing)) Assert.Throws(Of ArgumentException)(Sub() comp.CreateErrorNamespaceSymbol(csComp.GlobalNamespace, "a")) Dim ns = comp.CreateErrorNamespaceSymbol(comp.GlobalNamespace, "a") Assert.Equal("a", ns.ToTestDisplayString()) Assert.False(ns.IsGlobalNamespace) Assert.Equal(NamespaceKind.Compilation, ns.NamespaceKind) Assert.Same(comp.GlobalNamespace, ns.ContainingSymbol) Assert.Same(comp.GlobalNamespace.ContainingAssembly, ns.ContainingAssembly) Assert.Same(comp.GlobalNamespace.ContainingModule, ns.ContainingModule) ns = comp.CreateErrorNamespaceSymbol(comp.Assembly.GlobalNamespace, "a") Assert.Equal("a", ns.ToTestDisplayString()) Assert.False(ns.IsGlobalNamespace) Assert.Equal(NamespaceKind.Assembly, ns.NamespaceKind) Assert.Same(comp.Assembly.GlobalNamespace, ns.ContainingSymbol) Assert.Same(comp.Assembly.GlobalNamespace.ContainingAssembly, ns.ContainingAssembly) Assert.Same(comp.Assembly.GlobalNamespace.ContainingModule, ns.ContainingModule) ns = comp.CreateErrorNamespaceSymbol(comp.SourceModule.GlobalNamespace, "a") Assert.Equal("a", ns.ToTestDisplayString()) Assert.False(ns.IsGlobalNamespace) Assert.Equal(NamespaceKind.Module, ns.NamespaceKind) Assert.Same(comp.SourceModule.GlobalNamespace, ns.ContainingSymbol) Assert.Same(comp.SourceModule.GlobalNamespace.ContainingAssembly, ns.ContainingAssembly) Assert.Same(comp.SourceModule.GlobalNamespace.ContainingModule, ns.ContainingModule) ns = comp.CreateErrorNamespaceSymbol(comp.CreateErrorNamespaceSymbol(comp.GlobalNamespace, "a"), "b") Assert.Equal("a.b", ns.ToTestDisplayString()) ns = comp.CreateErrorNamespaceSymbol(comp.GlobalNamespace, "") Assert.Equal("", ns.ToTestDisplayString()) Assert.False(ns.IsGlobalNamespace) vt2 = comp.CreateErrorTypeSymbol(comp.CreateErrorNamespaceSymbol(comp.GlobalNamespace, "System"), "ValueTuple", 2).Construct(intType, intType) Assert.Equal("(System.Int32, System.Int32)", comp.CreateTupleTypeSymbol(underlyingType:=vt2).ToTestDisplayString()) vt2 = comp.CreateErrorTypeSymbol(comp.CreateErrorNamespaceSymbol(comp.Assembly.GlobalNamespace, "System"), "ValueTuple", 2).Construct(intType, intType) Assert.Equal("(System.Int32, System.Int32)", comp.CreateTupleTypeSymbol(underlyingType:=vt2).ToTestDisplayString()) vt2 = comp.CreateErrorTypeSymbol(comp.CreateErrorNamespaceSymbol(comp.SourceModule.GlobalNamespace, "System"), "ValueTuple", 2).Construct(intType, intType) Assert.Equal("(System.Int32, System.Int32)", comp.CreateTupleTypeSymbol(underlyingType:=vt2).ToTestDisplayString()) End Sub <Fact> <WorkItem(13042, "https://github.com/dotnet/roslyn/issues/13042")> Public Sub GetSymbolInfoOnTupleType() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module C Function M() As (System.Int32, String) throw new System.Exception() End Function End Module </file> </compilation>, references:=s_valueTupleRefs) Dim comp = verifier.Compilation Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim type = nodes.OfType(Of QualifiedNameSyntax)().First() Assert.Equal("System.Int32", type.ToString()) Assert.NotNull(model.GetSymbolInfo(type).Symbol) Assert.Equal("System.Int32", model.GetSymbolInfo(type).Symbol.ToTestDisplayString()) End Sub <Fact(Skip:="See bug 16697")> <WorkItem(16697, "https://github.com/dotnet/roslyn/issues/16697")> Public Sub GetSymbolInfo_01() Dim source = " Class C Shared Sub Main() Dim x1 = (Alice:=1, ""hello"") Dim Alice = x1.Alice End Sub End Class " Dim tree = Parse(source, options:=TestOptions.Regular) Dim comp = CreateCompilationWithMscorlib40(tree) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim nc = nodes.OfType(Of NameColonEqualsSyntax)().ElementAt(0) Dim sym = model.GetSymbolInfo(nc.Name) Assert.Equal("Alice", sym.Symbol.Name) Assert.Equal(SymbolKind.Field, sym.Symbol.Kind) ' Incorrectly returns Local Assert.Equal(nc.Name.GetLocation(), sym.Symbol.Locations(0)) ' Incorrect location End Sub <Fact> <WorkItem(23651, "https://github.com/dotnet/roslyn/issues/23651")> Public Sub GetSymbolInfo_WithDuplicateInferredNames() Dim source = " Class C Shared Sub M(Bob As String) Dim x1 = (Bob, Bob) End Sub End Class " Dim tree = Parse(source, options:=TestOptions.Regular) Dim comp = CreateCompilationWithMscorlib40(tree) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim tuple = nodes.OfType(Of TupleExpressionSyntax)().Single() Dim type = DirectCast(model.GetTypeInfo(tuple).Type, TypeSymbol) Assert.True(type.TupleElementNames.IsDefault) End Sub <Fact> Public Sub RetargetTupleErrorType() Dim libComp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class A Public Shared Function M() As (Integer, Integer) Return (1, 2) End Function End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) libComp.AssertNoDiagnostics() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class B Public Sub M2() A.M() End Sub End Class </file> </compilation>, additionalRefs:={libComp.ToMetadataReference()}) comp.AssertTheseDiagnostics( <errors> BC30652: Reference required to assembly 'System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' containing the type 'ValueTuple(Of ,)'. Add one to your project. A.M() ~~~~~ </errors>) Dim methodM = comp.GetMember(Of MethodSymbol)("A.M") Assert.Equal("(System.Int32, System.Int32)", methodM.ReturnType.ToTestDisplayString()) Assert.True(methodM.ReturnType.IsTupleType) Assert.False(methodM.ReturnType.IsErrorType()) Assert.True(methodM.ReturnType.TupleUnderlyingType.IsErrorType()) End Sub <Fact> Public Sub CaseSensitivity001() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x2 = (A:=10, B:=20) System.Console.Write(x2.a) System.Console.Write(x2.item2) Dim x3 = (item1 := 1, item2 := 2) System.Console.Write(x3.Item1) System.Console.WriteLine(x3.Item2) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[102012]]>) End Sub <Fact> Public Sub CaseSensitivity002() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Module Module1 Sub Main() Dim x1 = (A:=10, a:=20) System.Console.Write(x1.a) System.Console.Write(x1.A) Dim x2 as (A as Integer, a As Integer) = (10, 20) System.Console.Write(x1.a) System.Console.Write(x1.A) Dim x3 = (I1:=10, item1:=20) Dim x4 = (Item1:=10, item1:=20) Dim x5 = (item1:=10, item1:=20) Dim x6 = (tostring:=10, item1:=20) End Sub End Module ]]> </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37262: Tuple element names must be unique. Dim x1 = (A:=10, a:=20) ~ BC31429: 'A' is ambiguous because multiple kinds of members with this name exist in structure '(A As Integer, a As Integer)'. System.Console.Write(x1.a) ~~~~ BC31429: 'A' is ambiguous because multiple kinds of members with this name exist in structure '(A As Integer, a As Integer)'. System.Console.Write(x1.A) ~~~~ BC37262: Tuple element names must be unique. Dim x2 as (A as Integer, a As Integer) = (10, 20) ~ BC31429: 'A' is ambiguous because multiple kinds of members with this name exist in structure '(A As Integer, a As Integer)'. System.Console.Write(x1.a) ~~~~ BC31429: 'A' is ambiguous because multiple kinds of members with this name exist in structure '(A As Integer, a As Integer)'. System.Console.Write(x1.A) ~~~~ BC37261: Tuple element name 'item1' is only allowed at position 1. Dim x3 = (I1:=10, item1:=20) ~~~~~ BC37261: Tuple element name 'item1' is only allowed at position 1. Dim x4 = (Item1:=10, item1:=20) ~~~~~ BC37261: Tuple element name 'item1' is only allowed at position 1. Dim x5 = (item1:=10, item1:=20) ~~~~~ BC37260: Tuple element name 'tostring' is disallowed at any position. Dim x6 = (tostring:=10, item1:=20) ~~~~~~~~ BC37261: Tuple element name 'item1' is only allowed at position 1. Dim x6 = (tostring:=10, item1:=20) ~~~~~ </errors>) End Sub <Fact> Public Sub CaseSensitivity003() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x as (Item1 as String, itEm2 as String, Bob as string) = (Nothing, Nothing, Nothing) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (, , ) ]]>) Dim comp = verifier.Compilation Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(Nothing, Nothing, Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Dim fields = From m In model.GetTypeInfo(node).ConvertedType.GetMembers() Where m.Kind = SymbolKind.Field Order By m.Name Select m.Name ' check no duplication of original/default ItemX fields Assert.Equal("Bob#Item1#Item2#Item3", fields.Join("#")) End Sub <Fact> Public Sub CaseSensitivity004() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x = ( I1 := 1, I2 := 2, I3 := 3, ITeM4 := 4, I5 := 5, I6 := 6, I7 := 7, ITeM8 := 8, ItEM9 := 9 ) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (1, 2, 3, 4, 5, 6, 7, 8, 9) ]]>) Dim comp = verifier.Compilation Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Dim fields = From m In model.GetTypeInfo(node).Type.GetMembers() Where m.Kind = SymbolKind.Field Order By m.Name Select m.Name ' check no duplication of original/default ItemX fields Assert.Equal("I1#I2#I3#I5#I6#I7#Item1#Item2#Item3#Item4#Item5#Item6#Item7#Item8#Item9#Rest", fields.Join("#")) End Sub ' The NonNullTypes context for nested tuple types is using a dummy rather than actual context from surrounding code. ' This does not affect `IsNullable`, but it affects `IsAnnotatedWithNonNullTypesContext`, which is used in comparisons. ' So when we copy modifiers (re-applying nullability information, including actual NonNullTypes context), we make the comparison fail. ' I think the solution is to never use a dummy context, even for value types. <Fact> Public Sub TupleNamesFromCS001() Dim csCompilation = CreateCSharpCompilation("CSDll", <![CDATA[ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary1 { public class Class1 { public (int Alice, int Bob) goo = (2, 3); public (int Alice, int Bob) Bar() => (4, 5); public (int Alice, int Bob) Baz => (6, 7); } public class Class2 { public (int Alice, int q, int w, int e, int f, int g, int h, int j, int Bob) goo = SetBob(11); public (int Alice, int q, int w, int e, int f, int g, int h, int j, int Bob) Bar() => SetBob(12); public (int Alice, int q, int w, int e, int f, int g, int h, int j, int Bob) Baz => SetBob(13); private static (int Alice, int q, int w, int e, int f, int g, int h, int j, int Bob) SetBob(int x) { var result = default((int Alice, int q, int w, int e, int f, int g, int h, int j, int Bob)); result.Bob = x; return result; } } public class class3: IEnumerable<(int Alice, int Bob)> { IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } IEnumerator<(Int32 Alice, Int32 Bob)> IEnumerable<(Int32 Alice, Int32 Bob)>.GetEnumerator() { yield return (1, 2); yield return (3, 4); } } } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbCompilation = CreateVisualBasicCompilation("VBDll", <![CDATA[ Module Module1 Sub Main() Dim x As New ClassLibrary1.Class1 System.Console.WriteLine(x.goo.Alice) System.Console.WriteLine(x.goo.Bob) System.Console.WriteLine(x.Bar.Alice) System.Console.WriteLine(x.Bar.Bob) System.Console.WriteLine(x.Baz.Alice) System.Console.WriteLine(x.Baz.Bob) Dim y As New ClassLibrary1.Class2 System.Console.WriteLine(y.goo.Alice) System.Console.WriteLine(y.goo.Bob) System.Console.WriteLine(y.Bar.Alice) System.Console.WriteLine(y.Bar.Bob) System.Console.WriteLine(y.Baz.Alice) System.Console.WriteLine(y.Baz.Bob) Dim z As New ClassLibrary1.class3 For Each item In z System.Console.WriteLine(item.Alice) System.Console.WriteLine(item.Bob) Next End Sub End Module ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}, referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbexeVerifier = CompileAndVerify(vbCompilation, expectedOutput:=" 2 3 4 5 6 7 0 11 0 12 0 13 1 2 3 4") vbexeVerifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleNamesFromVB001() Dim classLib = CreateVisualBasicCompilation("VBClass", <![CDATA[ Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Linq Imports System.Text Imports System.Threading.Tasks Namespace ClassLibrary1 Public Class Class1 Public goo As (Alice As Integer, Bob As Integer) = (2, 3) Public Function Bar() As (Alice As Integer, Bob As Integer) Return (4, 5) End Function Public ReadOnly Property Baz As (Alice As Integer, Bob As Integer) Get Return (6, 7) End Get End Property End Class Public Class Class2 Public goo As (Alice As Integer, q As Integer, w As Integer, e As Integer, f As Integer, g As Integer, h As Integer, j As Integer, Bob As Integer) = SetBob(11) Public Function Bar() As (Alice As Integer, q As Integer, w As Integer, e As Integer, f As Integer, g As Integer, h As Integer, j As Integer, Bob As Integer) Return SetBob(12) End Function Public ReadOnly Property Baz As (Alice As Integer, q As Integer, w As Integer, e As Integer, f As Integer, g As Integer, h As Integer, j As Integer, Bob As Integer) Get Return SetBob(13) End Get End Property Private Shared Function SetBob(x As Integer) As (Alice As Integer, q As Integer, w As Integer, e As Integer, f As Integer, g As Integer, h As Integer, j As Integer, Bob As Integer) Dim result As (Alice As Integer, q As Integer, w As Integer, e As Integer, f As Integer, g As Integer, h As Integer, j As Integer, Bob As Integer) = Nothing result.Bob = x Return result End Function End Class Public Class class3 Implements IEnumerable(Of (Alice As Integer, Bob As Integer)) Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function Public Iterator Function GetEnumerator() As IEnumerator(Of (Alice As Integer, Bob As Integer)) Implements IEnumerable(Of (Alice As Integer, Bob As Integer)).GetEnumerator Yield (1, 2) Yield (3, 4) End Function End Class End Namespace ]]>, compilationOptions:=New Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbCompilation = CreateVisualBasicCompilation("VBDll", <![CDATA[ Module Module1 Sub Main() Dim x As New ClassLibrary1.Class1 System.Console.WriteLine(x.goo.Alice) System.Console.WriteLine(x.goo.Bob) System.Console.WriteLine(x.Bar.Alice) System.Console.WriteLine(x.Bar.Bob) System.Console.WriteLine(x.Baz.Alice) System.Console.WriteLine(x.Baz.Bob) Dim y As New ClassLibrary1.Class2 System.Console.WriteLine(y.goo.Alice) System.Console.WriteLine(y.goo.Bob) System.Console.WriteLine(y.Bar.Alice) System.Console.WriteLine(y.Bar.Bob) System.Console.WriteLine(y.Baz.Alice) System.Console.WriteLine(y.Baz.Bob) Dim z As New ClassLibrary1.class3 For Each item In z System.Console.WriteLine(item.Alice) System.Console.WriteLine(item.Bob) Next End Sub End Module ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={classLib}, referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbexeVerifier = CompileAndVerify(vbCompilation, expectedOutput:=" 2 3 4 5 6 7 0 11 0 12 0 13 1 2 3 4") vbexeVerifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleNamesFromVB001_InterfaceImpl() Dim classLib = CreateVisualBasicCompilation("VBClass", <![CDATA[ Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Linq Imports System.Text Imports System.Threading.Tasks Namespace ClassLibrary1 Public Class class3 Implements IEnumerable(Of (Alice As Integer, Bob As Integer)) Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function Private Iterator Function GetEnumerator() As IEnumerator(Of (Alice As Integer, Bob As Integer)) Implements IEnumerable(Of (Alice As Integer, Bob As Integer)).GetEnumerator Yield (1, 2) Yield (3, 4) End Function End Class End Namespace ]]>, compilationOptions:=New Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbCompilation = CreateVisualBasicCompilation("VBDll", <![CDATA[ Module Module1 Sub Main() Dim z As New ClassLibrary1.class3 For Each item In z System.Console.WriteLine(item.Alice) System.Console.WriteLine(item.Bob) Next End Sub End Module ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={classLib}, referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbexeVerifier = CompileAndVerify(vbCompilation, expectedOutput:=" 1 2 3 4") vbexeVerifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleNamesFromCS002() Dim csCompilation = CreateCSharpCompilation("CSDll", <![CDATA[ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary1 { public class Class1 { public (int Alice, (int Alice, int Bob) Bob) goo = (2, (2, 3)); public ((int Alice, int Bob)[] Alice, int Bob) Bar() => (new(int, int)[] { (4, 5) }, 5); public (int Alice, List<(int Alice, int Bob)?> Bob) Baz => (6, new List<(int Alice, int Bob)?>() { (8, 9) }); public static event Action<(int i0, int i1, int i2, int i3, int i4, int i5, int i6, int i7, (int Alice, int Bob) Bob)> goo1; public static void raise() { goo1((0, 1, 2, 3, 4, 5, 6, 7, (8, 42))); } } } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbCompilation = CreateVisualBasicCompilation("VBDll", <![CDATA[ Module Module1 Sub Main() Dim x As New ClassLibrary1.Class1 System.Console.WriteLine(x.goo.Bob.Bob) System.Console.WriteLine(x.goo.Item2.Item2) System.Console.WriteLine(x.Bar.Alice(0).Bob) System.Console.WriteLine(x.Bar.Item1(0).Item2) System.Console.WriteLine(x.Baz.Bob(0).Value) System.Console.WriteLine(x.Baz.Item2(0).Value) AddHandler ClassLibrary1.Class1.goo1, Sub(p) System.Console.WriteLine(p.Bob.Bob) System.Console.WriteLine(p.Rest.Item2.Bob) End Sub ClassLibrary1.Class1.raise() End Sub End Module ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}, referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbexeVerifier = CompileAndVerify(vbCompilation, expectedOutput:=" 3 3 5 5 (8, 9) (8, 9) 42 42") vbexeVerifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleNamesFromVB002() Dim classLib = CreateVisualBasicCompilation("VBClass", <![CDATA[ Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Linq Imports System.Text Imports System.Threading.Tasks Namespace ClassLibrary1 Public Class Class1 Public goo As (Alice As Integer, Bob As (Alice As Integer, Bob As Integer)) = (2, (2, 3)) Public Function Bar() As (Alice As (Alice As Integer, Bob As Integer)(), Bob As Integer) Return (New(Integer, Integer)() {(4, 5)}, 5) End Function Public ReadOnly Property Baz As (Alice As Integer, Bob As List(Of (Alice As Integer, Bob As Integer) ?)) Get Return (6, New List(Of (Alice As Integer, Bob As Integer) ?)() From {(8, 9)}) End Get End Property Public Shared Event goo1 As Action(Of (i0 As Integer, i1 As Integer, i2 As Integer, i3 As Integer, i4 As Integer, i5 As Integer, i6 As Integer, i7 As Integer, Bob As (Alice As Integer, Bob As Integer))) Public Shared Sub raise() RaiseEvent goo1((0, 1, 2, 3, 4, 5, 6, 7, (8, 42))) End Sub End Class End Namespace ]]>, compilationOptions:=New Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbCompilation = CreateVisualBasicCompilation("VBDll", <![CDATA[ Module Module1 Sub Main() Dim x As New ClassLibrary1.Class1 System.Console.WriteLine(x.goo.Bob.Bob) System.Console.WriteLine(x.goo.Item2.Item2) System.Console.WriteLine(x.Bar.Alice(0).Bob) System.Console.WriteLine(x.Bar.Item1(0).Item2) System.Console.WriteLine(x.Baz.Bob(0).Value) System.Console.WriteLine(x.Baz.Item2(0).Value) AddHandler ClassLibrary1.Class1.goo1, Sub(p) System.Console.WriteLine(p.Bob.Bob) System.Console.WriteLine(p.Rest.Item2.Bob) End Sub ClassLibrary1.Class1.raise() End Sub End Module ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={classLib}, referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbexeVerifier = CompileAndVerify(vbCompilation, expectedOutput:=" 3 3 5 5 (8, 9) (8, 9) 42 42") vbexeVerifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleNamesFromCS003() Dim csCompilation = CreateCSharpCompilation("CSDll", <![CDATA[ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary1 { public class Class1 { public (int Alice, int alice) goo = (2, 3); } } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbCompilation = CreateVisualBasicCompilation("VBDll", <![CDATA[ Module Module1 Sub Main() Dim x As New ClassLibrary1.Class1 System.Console.WriteLine(x.goo.Item1) System.Console.WriteLine(x.goo.Item2) System.Console.WriteLine(x.goo.Alice) System.Console.WriteLine(x.goo.alice) Dim f = x.goo System.Console.WriteLine(f.Item1) System.Console.WriteLine(f.Item2) System.Console.WriteLine(f.Alice) System.Console.WriteLine(f.alice) End Sub End Module ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}, referencedAssemblies:=s_valueTupleRefsAndDefault) vbCompilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "x.goo.Alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer)").WithLocation(8, 34), Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "x.goo.alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer)").WithLocation(9, 34), Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "f.Alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer)").WithLocation(14, 34), Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "f.alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer)").WithLocation(15, 34) ) End Sub <Fact> Public Sub TupleNamesFromCS004() Dim csCompilation = CreateCSharpCompilation("CSDll", <![CDATA[ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary1 { public class Class1 { public (int Alice, int alice, int) goo = (2, 3, 4); } } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbCompilation = CreateVisualBasicCompilation("VBDll", <![CDATA[ Module Module1 Sub Main() Dim x As New ClassLibrary1.Class1 System.Console.WriteLine(x.goo.Item1) System.Console.WriteLine(x.goo.Item2) System.Console.WriteLine(x.goo.Item3) System.Console.WriteLine(x.goo.Alice) System.Console.WriteLine(x.goo.alice) Dim f = x.goo System.Console.WriteLine(f.Item1) System.Console.WriteLine(f.Item2) System.Console.WriteLine(f.Item3) System.Console.WriteLine(f.Alice) System.Console.WriteLine(f.alice) End Sub End Module ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}, referencedAssemblies:=s_valueTupleRefsAndDefault) vbCompilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "x.goo.Alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer, Integer)").WithLocation(9, 34), Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "x.goo.alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer, Integer)").WithLocation(10, 34), Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "f.Alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer, Integer)").WithLocation(16, 34), Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "f.alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer, Integer)").WithLocation(17, 34) ) End Sub <Fact> Public Sub BadTupleNameMetadata() Dim comp = CreateCompilationWithCustomILSource(<compilation> <file name="a.vb"> </file> </compilation>, " .assembly extern mscorlib { } .assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 } .class public auto ansi C extends [mscorlib]System.Object { .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> ValidField .field public int32 ValidFieldWithAttribute .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[1](""name1"")} = ( 01 00 01 00 00 00 05 6E 61 6D 65 31 ) .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> TooFewNames .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[1](""name1"")} = ( 01 00 01 00 00 00 05 6E 61 6D 65 31 ) .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> TooManyNames .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[3](""e1"", ""e2"", ""e3"")} = ( 01 00 03 00 00 00 02 65 31 02 65 32 02 65 33 ) .method public hidebysig instance class [System.ValueTuple]System.ValueTuple`2<int32,int32> TooFewNamesMethod() cil managed { .param [0] .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[1](""name1"")} = ( 01 00 01 00 00 00 05 6E 61 6D 65 31 ) // Code size 8 (0x8) .maxstack 8 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: newobj instance void class [System.ValueTuple]System.ValueTuple`2<int32,int32>::.ctor(!0, !1) IL_0007: ret } // end of method C::TooFewNamesMethod .method public hidebysig instance class [System.ValueTuple]System.ValueTuple`2<int32,int32> TooManyNamesMethod() cil managed { .param [0] .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[3](""e1"", ""e2"", ""e3"")} = ( 01 00 03 00 00 00 02 65 31 02 65 32 02 65 33 ) // Code size 8 (0x8) .maxstack 8 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: newobj instance void class [System.ValueTuple]System.ValueTuple`2<int32,int32>::.ctor(!0, !1) IL_0007: ret } // end of method C::TooManyNamesMethod } // end of class C ", additionalReferences:=s_valueTupleRefs) Dim c = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim validField = c.GetMember(Of FieldSymbol)("ValidField") Assert.False(validField.Type.IsErrorType()) Assert.True(validField.Type.IsTupleType) Assert.True(validField.Type.TupleElementNames.IsDefault) Dim validFieldWithAttribute = c.GetMember(Of FieldSymbol)("ValidFieldWithAttribute") Assert.True(validFieldWithAttribute.Type.IsErrorType()) Assert.False(validFieldWithAttribute.Type.IsTupleType) Assert.IsType(Of UnsupportedMetadataTypeSymbol)(validFieldWithAttribute.Type) Assert.False(DirectCast(validFieldWithAttribute.Type, INamedTypeSymbol).IsSerializable) Dim tooFewNames = c.GetMember(Of FieldSymbol)("TooFewNames") Assert.True(tooFewNames.Type.IsErrorType()) Assert.IsType(Of UnsupportedMetadataTypeSymbol)(tooFewNames.Type) Assert.False(DirectCast(tooFewNames.Type, INamedTypeSymbol).IsSerializable) Dim tooManyNames = c.GetMember(Of FieldSymbol)("TooManyNames") Assert.True(tooManyNames.Type.IsErrorType()) Assert.IsType(Of UnsupportedMetadataTypeSymbol)(tooManyNames.Type) Dim tooFewNamesMethod = c.GetMember(Of MethodSymbol)("TooFewNamesMethod") Assert.True(tooFewNamesMethod.ReturnType.IsErrorType()) Assert.IsType(Of UnsupportedMetadataTypeSymbol)(tooFewNamesMethod.ReturnType) Dim tooManyNamesMethod = c.GetMember(Of MethodSymbol)("TooManyNamesMethod") Assert.True(tooManyNamesMethod.ReturnType.IsErrorType()) Assert.IsType(Of UnsupportedMetadataTypeSymbol)(tooManyNamesMethod.ReturnType) End Sub <Fact> Public Sub MetadataForPartiallyNamedTuples() Dim comp = CreateCompilationWithCustomILSource(<compilation> <file name="a.vb"> </file> </compilation>, " .assembly extern mscorlib { } .assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 } .class public auto ansi C extends [mscorlib]System.Object { .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> ValidField .field public int32 ValidFieldWithAttribute .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[1](""name1"")} = ( 01 00 01 00 00 00 05 6E 61 6D 65 31 ) // In source, all or no names must be specified for a tuple .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> PartialNames .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[2](""e1"", null)} = ( 01 00 02 00 00 00 02 65 31 FF ) .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> AllNullNames .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[2](null, null)} = ( 01 00 02 00 00 00 ff ff 00 00 ) .method public hidebysig instance void PartialNamesMethod( class [System.ValueTuple]System.ValueTuple`1<class [System.ValueTuple]System.ValueTuple`2<int32,int32>> c) cil managed { .param [1] .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // First null is fine (unnamed tuple) but the second is half-named // = {string[3](null, ""e1"", null)} = ( 01 00 03 00 00 00 FF 02 65 31 FF ) // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method C::PartialNamesMethod .method public hidebysig instance void AllNullNamesMethod( class [System.ValueTuple]System.ValueTuple`1<class [System.ValueTuple]System.ValueTuple`2<int32,int32>> c) cil managed { .param [1] .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // First null is fine (unnamed tuple) but the second is half-named // = {string[3](null, null, null)} = ( 01 00 03 00 00 00 ff ff ff 00 00 ) // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method C::AllNullNamesMethod } // end of class C ", additionalReferences:=s_valueTupleRefs) Dim c = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim validField = c.GetMember(Of FieldSymbol)("ValidField") Assert.False(validField.Type.IsErrorType()) Assert.True(validField.Type.IsTupleType) Assert.True(validField.Type.TupleElementNames.IsDefault) Dim validFieldWithAttribute = c.GetMember(Of FieldSymbol)("ValidFieldWithAttribute") Assert.True(validFieldWithAttribute.Type.IsErrorType()) Assert.False(validFieldWithAttribute.Type.IsTupleType) Assert.IsType(Of UnsupportedMetadataTypeSymbol)(validFieldWithAttribute.Type) Dim partialNames = c.GetMember(Of FieldSymbol)("PartialNames") Assert.False(partialNames.Type.IsErrorType()) Assert.True(partialNames.Type.IsTupleType) Assert.Equal("(e1 As System.Int32, System.Int32)", partialNames.Type.ToTestDisplayString()) Dim allNullNames = c.GetMember(Of FieldSymbol)("AllNullNames") Assert.False(allNullNames.Type.IsErrorType()) Assert.True(allNullNames.Type.IsTupleType) Assert.Equal("(System.Int32, System.Int32)", allNullNames.Type.ToTestDisplayString()) Dim partialNamesMethod = c.GetMember(Of MethodSymbol)("PartialNamesMethod") Dim partialParamType = partialNamesMethod.Parameters.Single().Type Assert.False(partialParamType.IsErrorType()) Assert.True(partialParamType.IsTupleType) Assert.Equal("ValueTuple(Of (e1 As System.Int32, System.Int32))", partialParamType.ToTestDisplayString()) Dim allNullNamesMethod = c.GetMember(Of MethodSymbol)("AllNullNamesMethod") Dim allNullParamType = allNullNamesMethod.Parameters.Single().Type Assert.False(allNullParamType.IsErrorType()) Assert.True(allNullParamType.IsTupleType) Assert.Equal("ValueTuple(Of (System.Int32, System.Int32))", allNullParamType.ToTestDisplayString()) End Sub <Fact> Public Sub NestedTuplesNoAttribute() Dim comp = CreateCompilationWithCustomILSource(<compilation> <file name="a.vb"> </file> </compilation>, " .assembly extern mscorlib { } .assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 } .class public auto ansi beforefieldinit Base`1<T> extends [mscorlib]System.Object { } .class public auto ansi C extends [mscorlib]System.Object { .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> Field1 .field public class Base`1<class [System.ValueTuple]System.ValueTuple`1< class [System.ValueTuple]System.ValueTuple`2<int32, int32>>> Field2; } // end of class C ", additionalReferences:=s_valueTupleRefs) Dim c = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim base1 = comp.GlobalNamespace.GetTypeMember("Base") Assert.NotNull(base1) Dim field1 = c.GetMember(Of FieldSymbol)("Field1") Assert.False(field1.Type.IsErrorType()) Assert.True(field1.Type.IsTupleType) Assert.True(field1.Type.TupleElementNames.IsDefault) Dim field2Type = DirectCast(c.GetMember(Of FieldSymbol)("Field2").Type, NamedTypeSymbol) Assert.Equal(base1, field2Type.OriginalDefinition) Assert.True(field2Type.IsGenericType) Dim first = field2Type.TypeArguments(0) Assert.True(first.IsTupleType) Assert.Equal(1, first.TupleElementTypes.Length) Assert.True(first.TupleElementNames.IsDefault) Dim second = first.TupleElementTypes(0) Assert.True(second.IsTupleType) Assert.True(second.TupleElementNames.IsDefault) Assert.Equal(2, second.TupleElementTypes.Length) Assert.All(second.TupleElementTypes, Sub(t) Assert.Equal(SpecialType.System_Int32, t.SpecialType)) End Sub <Fact> <WorkItem(258853, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/258853")> Public Sub BadOverloadWithTupleLiteralWithNaturalType() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub M(x As Integer) End Sub Sub M(x As String) End Sub Sub Main() M((1, 2)) End Sub End Module </file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics( <errors> BC30518: Overload resolution failed because no accessible 'M' can be called with these arguments: 'Public Sub M(x As Integer)': Value of type '(Integer, Integer)' cannot be converted to 'Integer'. 'Public Sub M(x As String)': Value of type '(Integer, Integer)' cannot be converted to 'String'. M((1, 2)) ~ </errors>) End Sub <Fact> <WorkItem(258853, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/258853")> Public Sub BadOverloadWithTupleLiteralWithNothing() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub M(x As Integer) End Sub Sub M(x As String) End Sub Sub Main() M((1, Nothing)) End Sub End Module </file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics( <errors> BC30518: Overload resolution failed because no accessible 'M' can be called with these arguments: 'Public Sub M(x As Integer)': Value of type '(Integer, Object)' cannot be converted to 'Integer'. 'Public Sub M(x As String)': Value of type '(Integer, Object)' cannot be converted to 'String'. M((1, Nothing)) ~ </errors>) End Sub <Fact> <WorkItem(258853, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/258853")> Public Sub BadOverloadWithTupleLiteralWithAddressOf() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub M(x As Integer) End Sub Sub M(x As String) End Sub Sub Main() M((1, AddressOf Main)) End Sub End Module </file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics( <errors> BC30518: Overload resolution failed because no accessible 'M' can be called with these arguments: 'Public Sub M(x As Integer)': Expression does not produce a value. 'Public Sub M(x As String)': Expression does not produce a value. M((1, AddressOf Main)) ~ </errors>) End Sub <Fact> Public Sub TupleLiteralWithOnlySomeNames() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim t As (Integer, String, Integer) = (1, b:="hello", Item3:=3) console.write($"{t.Item1} {t.Item2} {t.Item3}") End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:="1 hello 3") End Sub <Fact()> <WorkItem(13705, "https://github.com/dotnet/roslyn/issues/13705")> Public Sub TupleCoVariance() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Interface I(Of Out T) Function M() As System.ValueTuple(Of Integer, T) End Interface ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC36726: Type 'T' cannot be used for the 'T2' in 'System.ValueTuple(Of T1, T2)' in this context because 'T' is an 'Out' type parameter. Function M() As System.ValueTuple(Of Integer, T) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> <WorkItem(13705, "https://github.com/dotnet/roslyn/issues/13705")> Public Sub TupleCoVariance2() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Interface I(Of Out T) Function M() As (Integer, T) End Interface ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC36726: Type 'T' cannot be used for the 'T2' in 'System.ValueTuple(Of T1, T2)' in this context because 'T' is an 'Out' type parameter. Function M() As (Integer, T) ~~~~~~~~~~~~ </errors>) End Sub <Fact()> <WorkItem(13705, "https://github.com/dotnet/roslyn/issues/13705")> Public Sub TupleContraVariance() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Interface I(Of In T) Sub M(x As (Boolean, T)) End Interface ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC36727: Type 'T' cannot be used for the 'T2' in 'System.ValueTuple(Of T1, T2)' in this context because 'T' is an 'In' type parameter. Sub M(x As (Boolean, T)) ~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub DefiniteAssignment001() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (A as string, B as string) ss.A = "q" ss.Item2 = "w" System.Console.WriteLine(ss) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, w)]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DefiniteAssignment001Err() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (A as string, B as string) ss.A = "q" 'ss.Item2 = "w" System.Console.WriteLine(ss) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, )]]>) verifier.VerifyDiagnostics( Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss").WithArguments("ss").WithLocation(8, 34) ) End Sub <Fact> Public Sub DefiniteAssignment002() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (A as string, B as string) ss.A = "q" ss.B = "q" ss.Item1 = "w" ss.Item2 = "w" System.Console.WriteLine(ss) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(w, w)]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DefiniteAssignment003() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (A as string, D as (B as string, C as string )) ss.A = "q" ss.D.B = "w" ss.D.C = "e" System.Console.WriteLine(ss) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, (w, e))]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DefiniteAssignment004() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (I1 as string , I2 As string, I3 As string, I4 As string, I5 As string, I6 As string, I7 As string, I8 As string, I9 As string, I10 As string) ss.I1 = "q" ss.I2 = "q" ss.I3 = "q" ss.I4 = "q" ss.I5 = "q" ss.I6 = "q" ss.I7 = "q" ss.I8 = "q" ss.I9 = "q" ss.I10 = "q" System.Console.WriteLine(ss) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q, q, q, q, q, q, q, q)]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DefiniteAssignment005() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String, I9 As String, I10 As String) ss.Item1 = "q" ss.Item2 = "q" ss.Item3 = "q" ss.Item4 = "q" ss.Item5 = "q" ss.Item6 = "q" ss.Item7 = "q" ss.Item8 = "q" ss.Item9 = "q" ss.Item10 = "q" System.Console.WriteLine(ss) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q, q, q, q, q, q, q, q)]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DefiniteAssignment006() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String, I9 As String, I10 As String) ss.Item1 = "q" ss.I2 = "q" ss.Item3 = "q" ss.I4 = "q" ss.Item5 = "q" ss.I6 = "q" ss.Item7 = "q" ss.I8 = "q" ss.Item9 = "q" ss.I10 = "q" System.Console.WriteLine(ss) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q, q, q, q, q, q, q, q)]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DefiniteAssignment007() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String, I9 As String, I10 As String) ss.Item1 = "q" ss.I2 = "q" ss.Item3 = "q" ss.I4 = "q" ss.Item5 = "q" ss.I6 = "q" ss.Item7 = "q" ss.I8 = "q" ss.Item9 = "q" ss.I10 = "q" System.Console.WriteLine(ss.Rest) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q)]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DefiniteAssignment008() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String, I9 As String, I10 As String) ss.I8 = "q" ss.Item9 = "q" ss.I10 = "q" System.Console.WriteLine(ss.Rest) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q)]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DefiniteAssignment008long() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String, I9 As String, I10 As String, I11 as string, I12 As String, I13 As String, I14 As String, I15 As String, I16 As String, I17 As String, I18 As String, I19 As String, I20 As String, I21 as string, I22 As String, I23 As String, I24 As String, I25 As String, I26 As String, I27 As String, I28 As String, I29 As String, I30 As String, I31 As String) 'warn System.Console.WriteLine(ss.Rest.Rest.Rest) 'warn System.Console.WriteLine(ss.I31) ss.I29 = "q" ss.Item30 = "q" ss.I31 = "q" System.Console.WriteLine(ss.I29) System.Console.WriteLine(ss.Rest.Rest.Rest) System.Console.WriteLine(ss.I31) ' warn System.Console.WriteLine(ss.Rest.Rest) ' warn System.Console.WriteLine(ss.Rest) ' warn System.Console.WriteLine(ss) ' warn System.Console.WriteLine(ss.I2) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (, , , , , , , , , ) q (, , , , , , , q, q, q) q (, , , , , , , , , , , , , , q, q, q) (, , , , , , , , , , , , , , , , , , , , , q, q, q) (, , , , , , , , , , , , , , , , , , , , , , , , , , , , q, q, q)]]>) verifier.VerifyDiagnostics( Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss.Rest.Rest.Rest").WithArguments("Rest").WithLocation(36, 34), Diagnostic(ERRID.WRN_DefAsgUseNullRef, "ss.I31").WithArguments("I31").WithLocation(38, 34), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss.Rest.Rest").WithArguments("Rest").WithLocation(49, 34), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss.Rest").WithArguments("Rest").WithLocation(52, 34), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss").WithArguments("ss").WithLocation(55, 34), Diagnostic(ERRID.WRN_DefAsgUseNullRef, "ss.I2").WithArguments("I2").WithLocation(58, 34)) End Sub <Fact> Public Sub DefiniteAssignment009() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String, I9 As String, I10 As String) ss.I1 = "q" ss.I2 = "q" ss.I3 = "q" ss.I4 = "q" ss.I5 = "q" ss.I6 = "q" ss.I7 = "q" ss.Rest = Nothing System.Console.WriteLine(ss) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q, q, q, q, q, , , )]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DefiniteAssignment010() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String, I9 As String, I10 As String) ss.Rest = ("q", "w", "e") System.Console.WriteLine(ss.I9) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[w]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DefiniteAssignment011() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() if (1.ToString() = 2.ToString()) Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String) ss.I1 = "q" ss.I2 = "q" ss.I3 = "q" ss.I4 = "q" ss.I5 = "q" ss.I6 = "q" ss.I7 = "q" ss.I8 = "q" System.Console.WriteLine(ss) elseif (1.ToString() = 3.ToString()) Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String) ss.I1 = "q" ss.I2 = "q" ss.I3 = "q" ss.I4 = "q" ss.I5 = "q" ss.I6 = "q" ss.I7 = "q" ' ss.I8 = "q" System.Console.WriteLine(ss) else Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String) ss.I1 = "q" ss.I2 = "q" ss.I3 = "q" ss.I4 = "q" ss.I5 = "q" ss.I6 = "q" ' ss.I7 = "q" ss.I8 = "q" System.Console.WriteLine(ss) ' should fail end if End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q, q, q, q, , q)]]>) verifier.VerifyDiagnostics( Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss").WithArguments("ss").WithLocation(44, 38), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss").WithArguments("ss").WithLocation(65, 38) ) End Sub <Fact> Public Sub DefiniteAssignment012() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() if (1.ToString() = 2.ToString()) Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String) ss.I1 = "q" ss.I2 = "q" ss.I3 = "q" ss.I4 = "q" ss.I5 = "q" ss.I6 = "q" ss.I7 = "q" ss.I8 = "q" System.Console.WriteLine(ss) else if (1.ToString() = 3.ToString()) Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String) ss.I1 = "q" ss.I2 = "q" ss.I3 = "q" ss.I4 = "q" ss.I5 = "q" ss.I6 = "q" ss.I7 = "q" ' ss.I8 = "q" System.Console.WriteLine(ss) ' should fail1 else Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String) ss.I1 = "q" ss.I2 = "q" ss.I3 = "q" ss.I4 = "q" ss.I5 = "q" ss.I6 = "q" ' ss.I7 = "q" ss.I8 = "q" System.Console.WriteLine(ss) ' should fail2 end if End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q, q, q, q, , q)]]>) verifier.VerifyDiagnostics( Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss").WithArguments("ss").WithLocation(43, 38), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss").WithArguments("ss").WithLocation(64, 38) ) End Sub <Fact> Public Sub DefiniteAssignment013() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String) ss.I1 = "q" ss.I2 = "q" ss.I3 = "q" ss.I4 = "q" ss.I5 = "q" ss.I6 = "q" ss.I7 = "q" ss.Item1 = "q" ss.Item2 = "q" ss.Item3 = "q" ss.Item4 = "q" ss.Item5 = "q" ss.Item6 = "q" ss.Item7 = "q" System.Console.WriteLine(ss.Rest) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[()]]>) verifier.VerifyDiagnostics( Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss.Rest").WithArguments("Rest").WithLocation(28, 38) ) End Sub <Fact> Public Sub DefiniteAssignment014() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String) ss.I1 = "q" ss.Item2 = "aa" System.Console.WriteLine(ss.Item1) System.Console.WriteLine(ss.I2) System.Console.WriteLine(ss.I3) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[q aa]]>) verifier.VerifyDiagnostics( Diagnostic(ERRID.WRN_DefAsgUseNullRef, "ss.I3").WithArguments("I3").WithLocation(18, 38) ) End Sub <Fact> Public Sub DefiniteAssignment015() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Threading.Tasks Module Module1 Sub Main() Dim v = Test().Result end sub async Function Test() as Task(of long) Dim v1 as (a as Integer, b as Integer) Dim v2 as (x as Byte, y as Integer) v1.a = 5 v2.x = 5 ' no need to persist across await since it is unused after it. System.Console.WriteLine(v2.Item1) await Task.Yield() ' this is assigned and persisted across await return v1.Item1 end Function End Module </file> </compilation>, useLatestFramework:=True, references:=s_valueTupleRefs, expectedOutput:="5") ' NOTE: !!! There should be NO IL local for " v1 as (Long, Integer)" , it should be captured instead ' NOTE: !!! There should be an IL local for " v2 as (Byte, Integer)" , it should not be captured verifier.VerifyIL("Module1.VB$StateMachine_1_Test.MoveNext()", <![CDATA[ { // Code size 214 (0xd6) .maxstack 3 .locals init (Long V_0, Integer V_1, System.ValueTuple(Of Byte, Integer) V_2, //v2 System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_3, System.Runtime.CompilerServices.YieldAwaitable V_4, System.Exception V_5) IL_0000: ldarg.0 IL_0001: ldfld "Module1.VB$StateMachine_1_Test.$State As Integer" IL_0006: stloc.1 .try { IL_0007: ldloc.1 IL_0008: brfalse.s IL_0061 IL_000a: ldarg.0 IL_000b: ldflda "Module1.VB$StateMachine_1_Test.$VB$ResumableLocal_v1$0 As (a As Integer, b As Integer)" IL_0010: ldc.i4.5 IL_0011: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0016: ldloca.s V_2 IL_0018: ldc.i4.5 IL_0019: stfld "System.ValueTuple(Of Byte, Integer).Item1 As Byte" IL_001e: ldloc.2 IL_001f: ldfld "System.ValueTuple(Of Byte, Integer).Item1 As Byte" IL_0024: call "Sub System.Console.WriteLine(Integer)" IL_0029: call "Function System.Threading.Tasks.Task.Yield() As System.Runtime.CompilerServices.YieldAwaitable" IL_002e: stloc.s V_4 IL_0030: ldloca.s V_4 IL_0032: call "Function System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter() As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0037: stloc.3 IL_0038: ldloca.s V_3 IL_003a: call "Function System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.get_IsCompleted() As Boolean" IL_003f: brtrue.s IL_007d IL_0041: ldarg.0 IL_0042: ldc.i4.0 IL_0043: dup IL_0044: stloc.1 IL_0045: stfld "Module1.VB$StateMachine_1_Test.$State As Integer" IL_004a: ldarg.0 IL_004b: ldloc.3 IL_004c: stfld "Module1.VB$StateMachine_1_Test.$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0051: ldarg.0 IL_0052: ldflda "Module1.VB$StateMachine_1_Test.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Long)" IL_0057: ldloca.s V_3 IL_0059: ldarg.0 IL_005a: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Long).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Module1.VB$StateMachine_1_Test)(ByRef System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ByRef Module1.VB$StateMachine_1_Test)" IL_005f: leave.s IL_00d5 IL_0061: ldarg.0 IL_0062: ldc.i4.m1 IL_0063: dup IL_0064: stloc.1 IL_0065: stfld "Module1.VB$StateMachine_1_Test.$State As Integer" IL_006a: ldarg.0 IL_006b: ldfld "Module1.VB$StateMachine_1_Test.$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0070: stloc.3 IL_0071: ldarg.0 IL_0072: ldflda "Module1.VB$StateMachine_1_Test.$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0077: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_007d: ldloca.s V_3 IL_007f: call "Sub System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()" IL_0084: ldloca.s V_3 IL_0086: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_008c: ldarg.0 IL_008d: ldflda "Module1.VB$StateMachine_1_Test.$VB$ResumableLocal_v1$0 As (a As Integer, b As Integer)" IL_0092: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0097: conv.i8 IL_0098: stloc.0 IL_0099: leave.s IL_00bf } catch System.Exception { IL_009b: dup IL_009c: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)" IL_00a1: stloc.s V_5 IL_00a3: ldarg.0 IL_00a4: ldc.i4.s -2 IL_00a6: stfld "Module1.VB$StateMachine_1_Test.$State As Integer" IL_00ab: ldarg.0 IL_00ac: ldflda "Module1.VB$StateMachine_1_Test.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Long)" IL_00b1: ldloc.s V_5 IL_00b3: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Long).SetException(System.Exception)" IL_00b8: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_00bd: leave.s IL_00d5 } IL_00bf: ldarg.0 IL_00c0: ldc.i4.s -2 IL_00c2: dup IL_00c3: stloc.1 IL_00c4: stfld "Module1.VB$StateMachine_1_Test.$State As Integer" IL_00c9: ldarg.0 IL_00ca: ldflda "Module1.VB$StateMachine_1_Test.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Long)" IL_00cf: ldloc.0 IL_00d0: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Long).SetResult(Long)" IL_00d5: ret } ]]>) End Sub <Fact> <WorkItem(13661, "https://github.com/dotnet/roslyn/issues/13661")> Public Sub LongTupleWithPartialNames_Bug13661() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module C Sub Main() Dim t = (A:=1, 2, C:=3, D:=4, E:=5, F:=6, G:=7, 8, I:=9) System.Console.Write($"{t.I}") End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, options:=TestOptions.DebugExe, expectedOutput:="9", sourceSymbolValidator:= Sub(m As ModuleSymbol) Dim compilation = m.DeclaringCompilation Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim t = nodes.OfType(Of VariableDeclaratorSyntax)().Single().Names(0) Dim xSymbol = DirectCast(model.GetDeclaredSymbol(t), LocalSymbol).Type AssertEx.SetEqual(xSymbol.GetMembers().OfType(Of FieldSymbol)().Select(Function(f) f.Name), "A", "C", "D", "E", "F", "G", "I", "Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9", "Rest") End Sub) ' No assert hit End Sub <Fact> Public Sub UnifyUnderlyingWithTuple_08() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Module Module1 Sub Main() Dim x = (1, 3) Dim s As String = x System.Console.WriteLine(s) System.Console.WriteLine(CType(x, Long)) Dim y As (Integer, String) = New KeyValuePair(Of Integer, String)(2, "4") System.Console.WriteLine(y) System.Console.WriteLine(CType("5", ValueTuple(Of String, String))) System.Console.WriteLine(+x) System.Console.WriteLine(-x) System.Console.WriteLine(Not x) System.Console.WriteLine(If(x, True, False)) System.Console.WriteLine(If(Not x, True, False)) System.Console.WriteLine(x + 1) System.Console.WriteLine(x - 1) System.Console.WriteLine(x * 3) System.Console.WriteLine(x / 2) System.Console.WriteLine(x \ 2) System.Console.WriteLine(x Mod 3) System.Console.WriteLine(x & 3) System.Console.WriteLine(x And 3) System.Console.WriteLine(x Or 15) System.Console.WriteLine(x Xor 3) System.Console.WriteLine(x Like 15) System.Console.WriteLine(x ^ 4) System.Console.WriteLine(x << 1) System.Console.WriteLine(x >> 1) System.Console.WriteLine(x = 1) System.Console.WriteLine(x <> 1) System.Console.WriteLine(x > 1) System.Console.WriteLine(x < 1) System.Console.WriteLine(x >= 1) System.Console.WriteLine(x <= 1) End Sub End Module ]]></file> </compilation> Dim tuple = <compilation> <file name="a.vb"><![CDATA[ Namespace System Public Structure ValueTuple(Of T1, T2) Public Item1 As T1 Public Item2 As T2 Public Sub New(item1 As T1, item2 As T2) Me.Item1 = item1 Me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}" End Function Public Shared Widening Operator CType(arg As ValueTuple(Of T1, T2)) As String Return arg.ToString() End Operator Public Shared Narrowing Operator CType(arg As ValueTuple(Of T1, T2)) As Long Return CLng(CObj(arg.Item1) + CObj(arg.Item2)) End Operator Public Shared Widening Operator CType(arg As System.Collections.Generic.KeyValuePair(Of T1, T2)) As ValueTuple(Of T1, T2) Return New ValueTuple(Of T1, T2)(arg.Key, arg.Value) End Operator Public Shared Narrowing Operator CType(arg As String) As ValueTuple(Of T1, T2) Return New ValueTuple(Of T1, T2)(CType(CObj(arg), T1), CType(CObj(arg), T2)) End Operator Public Shared Operator +(arg As ValueTuple(Of T1, T2)) As ValueTuple(Of T1, T2) Return arg End Operator Public Shared Operator -(arg As ValueTuple(Of T1, T2)) As Long Return -CType(arg, Long) End Operator Public Shared Operator Not(arg As ValueTuple(Of T1, T2)) As Boolean Return CType(arg, Long) = 0 End Operator Public Shared Operator IsTrue(arg As ValueTuple(Of T1, T2)) As Boolean Return CType(arg, Long) <> 0 End Operator Public Shared Operator IsFalse(arg As ValueTuple(Of T1, T2)) As Boolean Return CType(arg, Long) = 0 End Operator Public Shared Operator +(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long Return CType(arg1, Long) + arg2 End Operator Public Shared Operator -(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long Return CType(arg1, Long) - arg2 End Operator Public Shared Operator *(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long Return CType(arg1, Long) * arg2 End Operator Public Shared Operator /(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long Return CType(arg1, Long) / arg2 End Operator Public Shared Operator \(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long Return CType(arg1, Long) \ arg2 End Operator Public Shared Operator Mod(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long Return CType(arg1, Long) Mod arg2 End Operator Public Shared Operator &(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long Return CType(arg1, Long) & arg2 End Operator Public Shared Operator And(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long Return CType(arg1, Long) And arg2 End Operator Public Shared Operator Or(arg1 As ValueTuple(Of T1, T2), arg2 As Long) As Long Return CType(arg1, Long) Or arg2 End Operator Public Shared Operator Xor(arg1 As ValueTuple(Of T1, T2), arg2 As Long) As Long Return CType(arg1, Long) Xor arg2 End Operator Public Shared Operator Like(arg1 As ValueTuple(Of T1, T2), arg2 As Long) As Long Return CType(arg1, Long) Or arg2 End Operator Public Shared Operator ^(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long Return CType(arg1, Long) ^ arg2 End Operator Public Shared Operator <<(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long Return CType(arg1, Long) << arg2 End Operator Public Shared Operator >>(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long Return CType(arg1, Long) >> arg2 End Operator Public Shared Operator =(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Boolean Return CType(arg1, Long) = arg2 End Operator Public Shared Operator <>(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Boolean Return CType(arg1, Long) <> arg2 End Operator Public Shared Operator >(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Boolean Return CType(arg1, Long) > arg2 End Operator Public Shared Operator <(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Boolean Return CType(arg1, Long) < arg2 End Operator Public Shared Operator >=(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Boolean Return CType(arg1, Long) >= arg2 End Operator Public Shared Operator <=(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Boolean Return CType(arg1, Long) <= arg2 End Operator Public Overrides Function Equals(obj As Object) As Boolean Return False End Function Public Overrides Function GetHashCode() As Integer Return 0 End Function End Structure End Namespace ]]></file> </compilation> Dim expectedOutput = "{1, 3} 4 {2, 4} {5, 5} {1, 3} -4 False True False 5 3 12 2 2 1 43 0 15 7 15 256 8 2 False True True False True False " Dim [lib] = CreateCompilationWithMscorlib40AndVBRuntime(tuple, options:=TestOptions.ReleaseDll) [lib].VerifyEmitDiagnostics() Dim consumer1 = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.ReleaseExe, additionalRefs:={[lib].ToMetadataReference()}) CompileAndVerify(consumer1, expectedOutput:=expectedOutput).VerifyDiagnostics() Dim consumer2 = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.ReleaseExe, additionalRefs:={[lib].EmitToImageReference()}) CompileAndVerify(consumer2, expectedOutput:=expectedOutput).VerifyDiagnostics() End Sub <Fact> Public Sub UnifyUnderlyingWithTuple_12() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Module Module1 Sub Main() Dim x? = (1, 3) Dim s As String = x System.Console.WriteLine(s) System.Console.WriteLine(CType(x, Long)) Dim y As (Integer, String)? = New KeyValuePair(Of Integer, String)(2, "4") System.Console.WriteLine(y) System.Console.WriteLine(CType("5", ValueTuple(Of String, String))) System.Console.WriteLine(+x) System.Console.WriteLine(-x) System.Console.WriteLine(Not x) System.Console.WriteLine(If(x, True, False)) System.Console.WriteLine(If(Not x, True, False)) System.Console.WriteLine(x + 1) System.Console.WriteLine(x - 1) System.Console.WriteLine(x * 3) System.Console.WriteLine(x / 2) System.Console.WriteLine(x \ 2) System.Console.WriteLine(x Mod 3) System.Console.WriteLine(x & 3) System.Console.WriteLine(x And 3) System.Console.WriteLine(x Or 15) System.Console.WriteLine(x Xor 3) System.Console.WriteLine(x Like 15) System.Console.WriteLine(x ^ 4) System.Console.WriteLine(x << 1) System.Console.WriteLine(x >> 1) System.Console.WriteLine(x = 1) System.Console.WriteLine(x <> 1) System.Console.WriteLine(x > 1) System.Console.WriteLine(x < 1) System.Console.WriteLine(x >= 1) System.Console.WriteLine(x <= 1) End Sub End Module ]]></file> </compilation> Dim tuple = <compilation> <file name="a.vb"><![CDATA[ Namespace System Public Structure ValueTuple(Of T1, T2) Public Item1 As T1 Public Item2 As T2 Public Sub New(item1 As T1, item2 As T2) Me.Item1 = item1 Me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}" End Function Public Shared Widening Operator CType(arg As ValueTuple(Of T1, T2)?) As String Return arg.ToString() End Operator Public Shared Narrowing Operator CType(arg As ValueTuple(Of T1, T2)?) As Long Return CLng(CObj(arg.Value.Item1) + CObj(arg.Value.Item2)) End Operator Public Shared Widening Operator CType(arg As System.Collections.Generic.KeyValuePair(Of T1, T2)) As ValueTuple(Of T1, T2)? Return New ValueTuple(Of T1, T2)(arg.Key, arg.Value) End Operator Public Shared Narrowing Operator CType(arg As String) As ValueTuple(Of T1, T2)? Return New ValueTuple(Of T1, T2)(CType(CObj(arg), T1), CType(CObj(arg), T2)) End Operator Public Shared Operator +(arg As ValueTuple(Of T1, T2)?) As ValueTuple(Of T1, T2)? Return arg End Operator Public Shared Operator -(arg As ValueTuple(Of T1, T2)?) As Long Return -CType(arg, Long) End Operator Public Shared Operator Not(arg As ValueTuple(Of T1, T2)?) As Boolean Return CType(arg, Long) = 0 End Operator Public Shared Operator IsTrue(arg As ValueTuple(Of T1, T2)?) As Boolean Return CType(arg, Long) <> 0 End Operator Public Shared Operator IsFalse(arg As ValueTuple(Of T1, T2)?) As Boolean Return CType(arg, Long) = 0 End Operator Public Shared Operator +(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long Return CType(arg1, Long) + arg2 End Operator Public Shared Operator -(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long Return CType(arg1, Long) - arg2 End Operator Public Shared Operator *(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long Return CType(arg1, Long) * arg2 End Operator Public Shared Operator /(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long Return CType(arg1, Long) / arg2 End Operator Public Shared Operator \(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long Return CType(arg1, Long) \ arg2 End Operator Public Shared Operator Mod(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long Return CType(arg1, Long) Mod arg2 End Operator Public Shared Operator &(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long Return CType(arg1, Long) & arg2 End Operator Public Shared Operator And(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long Return CType(arg1, Long) And arg2 End Operator Public Shared Operator Or(arg1 As ValueTuple(Of T1, T2)?, arg2 As Long) As Long Return CType(arg1, Long) Or arg2 End Operator Public Shared Operator Xor(arg1 As ValueTuple(Of T1, T2)?, arg2 As Long) As Long Return CType(arg1, Long) Xor arg2 End Operator Public Shared Operator Like(arg1 As ValueTuple(Of T1, T2)?, arg2 As Long) As Long Return CType(arg1, Long) Or arg2 End Operator Public Shared Operator ^(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long Return CType(arg1, Long) ^ arg2 End Operator Public Shared Operator <<(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long Return CType(arg1, Long) << arg2 End Operator Public Shared Operator >>(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long Return CType(arg1, Long) >> arg2 End Operator Public Shared Operator =(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Boolean Return CType(arg1, Long) = arg2 End Operator Public Shared Operator <>(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Boolean Return CType(arg1, Long) <> arg2 End Operator Public Shared Operator >(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Boolean Return CType(arg1, Long) > arg2 End Operator Public Shared Operator <(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Boolean Return CType(arg1, Long) < arg2 End Operator Public Shared Operator >=(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Boolean Return CType(arg1, Long) >= arg2 End Operator Public Shared Operator <=(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Boolean Return CType(arg1, Long) <= arg2 End Operator Public Overrides Function Equals(obj As Object) As Boolean Return False End Function Public Overrides Function GetHashCode() As Integer Return 0 End Function End Structure End Namespace ]]></file> </compilation> Dim expectedOutput = "{1, 3} 4 {2, 4} {5, 5} {1, 3} -4 False True False 5 3 12 2 2 1 43 0 15 7 15 256 8 2 False True True False True False " Dim [lib] = CreateCompilationWithMscorlib40AndVBRuntime(tuple, options:=TestOptions.ReleaseDll) [lib].VerifyEmitDiagnostics() Dim consumer1 = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.ReleaseExe, additionalRefs:={[lib].ToMetadataReference()}) CompileAndVerify(consumer1, expectedOutput:=expectedOutput).VerifyDiagnostics() Dim consumer2 = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.ReleaseExe, additionalRefs:={[lib].EmitToImageReference()}) CompileAndVerify(consumer2, expectedOutput:=expectedOutput).VerifyDiagnostics() End Sub <Fact> Public Sub TupleConversion01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module C Sub Main() Dim x1 As (a As Integer, b As Integer) = DirectCast((e:=1, f:=2), (c As Long, d As Long)) Dim x2 As (a As Short, b As Short) = DirectCast((e:=1, f:=2), (c As Integer, d As Integer)) Dim x3 As (a As Integer, b As Integer) = DirectCast((e:=1, f:="qq"), (c As Long, d As Long)) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC41009: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'. Dim x1 As (a As Integer, b As Integer) = DirectCast((e:=1, f:=2), (c As Long, d As Long)) ~~~~ BC41009: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'. Dim x1 As (a As Integer, b As Integer) = DirectCast((e:=1, f:=2), (c As Long, d As Long)) ~~~~ BC41009: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(c As Integer, d As Integer)'. Dim x2 As (a As Short, b As Short) = DirectCast((e:=1, f:=2), (c As Integer, d As Integer)) ~~~~ BC41009: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(c As Integer, d As Integer)'. Dim x2 As (a As Short, b As Short) = DirectCast((e:=1, f:=2), (c As Integer, d As Integer)) ~~~~ BC41009: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'. Dim x3 As (a As Integer, b As Integer) = DirectCast((e:=1, f:="qq"), (c As Long, d As Long)) ~~~~ BC41009: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'. Dim x3 As (a As Integer, b As Integer) = DirectCast((e:=1, f:="qq"), (c As Long, d As Long)) ~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleConversion01_StrictOn() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Module C Sub Main() Dim x1 As (a As Integer, b As Integer) = DirectCast((e:=1, f:=2), (c As Long, d As Long)) Dim x2 As (a As Short, b As Short) = DirectCast((e:=1, f:=2), (c As Integer, d As Integer)) Dim x3 As (a As Integer, b As Integer) = DirectCast((e:=1, f:="qq"), (c As Long, d As Long)) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30512: Option Strict On disallows implicit conversions from '(c As Long, d As Long)' to '(a As Integer, b As Integer)'. Dim x1 As (a As Integer, b As Integer) = DirectCast((e:=1, f:=2), (c As Long, d As Long)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC41009: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'. Dim x1 As (a As Integer, b As Integer) = DirectCast((e:=1, f:=2), (c As Long, d As Long)) ~~~~ BC41009: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'. Dim x1 As (a As Integer, b As Integer) = DirectCast((e:=1, f:=2), (c As Long, d As Long)) ~~~~ BC30512: Option Strict On disallows implicit conversions from '(c As Integer, d As Integer)' to '(a As Short, b As Short)'. Dim x2 As (a As Short, b As Short) = DirectCast((e:=1, f:=2), (c As Integer, d As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC41009: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(c As Integer, d As Integer)'. Dim x2 As (a As Short, b As Short) = DirectCast((e:=1, f:=2), (c As Integer, d As Integer)) ~~~~ BC41009: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(c As Integer, d As Integer)'. Dim x2 As (a As Short, b As Short) = DirectCast((e:=1, f:=2), (c As Integer, d As Integer)) ~~~~ BC30512: Option Strict On disallows implicit conversions from '(c As Long, d As Long)' to '(a As Integer, b As Integer)'. Dim x3 As (a As Integer, b As Integer) = DirectCast((e:=1, f:="qq"), (c As Long, d As Long)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC41009: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'. Dim x3 As (a As Integer, b As Integer) = DirectCast((e:=1, f:="qq"), (c As Long, d As Long)) ~~~~ BC41009: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'. Dim x3 As (a As Integer, b As Integer) = DirectCast((e:=1, f:="qq"), (c As Long, d As Long)) ~~~~~~~ </errors>) End Sub <Fact> <WorkItem(11288, "https://github.com/dotnet/roslyn/issues/11288")> Public Sub TupleConversion02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x4 As (a As Integer, b As Integer) = DirectCast((1, Nothing, 2), (c As Long, d As Long)) End Sub End Module <%= s_trivial2uple %><%= s_trivial3uple %> </file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC30311: Value of type '(Integer, Object, Integer)' cannot be converted to '(c As Long, d As Long)'. Dim x4 As (a As Integer, b As Integer) = DirectCast((1, Nothing, 2), (c As Long, d As Long)) ~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleConvertedType01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Short, b As String)? = (e:=1, f:="hello") End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Dim typeInfo As TypeInfo = model.GetTypeInfo(node) Assert.Equal("(e As System.Int32, f As System.String)", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (a As System.Int16, b As System.String))", typeInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Dim e = node.Arguments(0).Expression Assert.Equal("1", e.ToString()) typeInfo = model.GetTypeInfo(e) Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.Int16", typeInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(e).Kind) Dim f = node.Arguments(1).Expression Assert.Equal("""hello""", f.ToString()) typeInfo = model.GetTypeInfo(f) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.String", typeInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(f).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As System.Nullable(Of (a As System.Int16, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType01_StrictOn() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Module C Sub Main() Dim x As (a As Short, b As String)? = (e:=1, f:="hello") End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (a As System.Int16, b As System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As System.Nullable(Of (a As System.Int16, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType01insource() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Short, b As String)? = DirectCast((e:=1, f:="hello"), (c As Short, d As String)?) Dim y As Short? = DirectCast(11, Short?) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim l11 = nodes.OfType(Of LiteralExpressionSyntax)().ElementAt(2) Assert.Equal("11", l11.ToString()) Assert.Equal("System.Int32", model.GetTypeInfo(l11).Type.ToTestDisplayString()) Assert.Equal("System.Int32", model.GetTypeInfo(l11).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(l11).Kind) Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (c As System.Int16, d As System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Assert.Equal("System.Nullable(Of (c As System.Int16, d As System.String))", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (c As System.Int16, d As System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As System.Nullable(Of (a As System.Int16, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType01insourceImplicit() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Short, b As String)? = (1, "hello") End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(1, ""hello"")", node.ToString()) Dim typeInfo As TypeInfo = model.GetTypeInfo(node) Assert.Equal("(System.Int32, System.String)", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (a As System.Int16, b As System.String))", typeInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) CompileAndVerify(comp) End Sub <Fact> Public Sub TupleConvertedType02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Short, b As String)? = (e:=1, f:="hello") End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Dim typeInfo As TypeInfo = model.GetTypeInfo(node) Assert.Equal("(e As System.Int32, f As System.String)", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (a As System.Int16, b As System.String))", typeInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Dim e = node.Arguments(0).Expression Assert.Equal("1", e.ToString()) typeInfo = model.GetTypeInfo(e) Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.Int16", typeInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(e).Kind) Dim f = node.Arguments(1).Expression Assert.Equal("""hello""", f.ToString()) typeInfo = model.GetTypeInfo(f) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.String", typeInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(f).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As System.Nullable(Of (a As System.Int16, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType02insource00() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Short, b As String)? = DirectCast((e:=1, f:="hello"), (c As Short, d As String)) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Assert.Equal("DirectCast((e:=1, f:=""hello""), (c As Short, d As String))", node.Parent.ToString()) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (a As System.Int16, b As System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As System.Nullable(Of (a As System.Int16, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType02insource00_StrictOn() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Module C Sub Main() Dim x As (a As Short, b As String)? = DirectCast((e:=1, f:="hello"), (c As Short, d As String)) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (a As System.Int16, b As System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As System.Nullable(Of (a As System.Int16, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType02insource01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x = (e:=1, f:="hello") Dim x1 As (a As Object, b As String) = DirectCast((x), (c As Long, d As String)) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of ParenthesizedExpressionSyntax)().Single().Parent Assert.Equal("DirectCast((x), (c As Long, d As String))", node.ToString()) Assert.Equal("(c As System.Int64, d As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(a As System.Object, b As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of ParenthesizedExpressionSyntax)().Single() Assert.Equal("(x)", x.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(x).Type.ToTestDisplayString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(x).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(x).Kind) End Sub <Fact> Public Sub TupleConvertedType02insource01_StrictOn() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Module C Sub Main() Dim x = (e:=1, f:="hello") Dim x1 As (a As Object, b As String) = DirectCast((x), (c As Long, d As String)) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of ParenthesizedExpressionSyntax)().Single().Parent Assert.Equal("DirectCast((x), (c As Long, d As String))", node.ToString()) Assert.Equal("(c As System.Int64, d As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(a As System.Object, b As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of ParenthesizedExpressionSyntax)().Single() Assert.Equal("(x)", x.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(x).Type.ToTestDisplayString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(x).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(x).Kind) End Sub <Fact> Public Sub TupleConvertedType02insource02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x = (e:=1, f:="hello") Dim x1 As (a As Object, b As String)? = DirectCast((x), (c As Long, d As String)) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of ParenthesizedExpressionSyntax)().Single().Parent Assert.Equal("DirectCast((x), (c As Long, d As String))", node.ToString()) Assert.Equal("(c As System.Int64, d As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (a As System.Object, b As System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of ParenthesizedExpressionSyntax)().Single() Assert.Equal("(x)", x.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(x).Type.ToTestDisplayString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(x).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(x).Kind) End Sub <Fact> Public Sub TupleConvertedType03() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Integer, b As String)? = (e:=1, f:="hello") End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (a As System.Int32, b As System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As System.Nullable(Of (a As System.Int32, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType03insource() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Integer, b As String)? = DirectCast((e:=1, f:="hello"), (c As Integer, d As String)?) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (c As System.Int32, d As System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(node).Kind) Assert.Equal("DirectCast((e:=1, f:=""hello""), (c As Integer, d As String)?)", node.Parent.ToString()) Assert.Equal("System.Nullable(Of (c As System.Int32, d As System.String))", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (c As System.Int32, d As System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(node.Parent).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As System.Nullable(Of (a As System.Int32, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType04() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Integer, b As String)? = DirectCast((e:=1, f:="hello"), (c As Integer, d As String)) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(c As System.Int32, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(node).Kind) Assert.Equal("(c As System.Int32, d As System.String)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (a As System.Int32, b As System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullable, model.GetConversion(node.Parent).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As System.Nullable(Of (a As System.Int32, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType05() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Integer, b As String) = (e:=1, f:="hello") End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(a As System.Int32, b As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As (a As System.Int32, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType05insource() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Integer, b As String) = DirectCast((e:=1, f:="hello"), (c As Integer, d As String)) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(c As System.Int32, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As (a As System.Int32, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType05insource_StrictOn() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Module C Sub Main() Dim x As (a As Integer, b As String) = DirectCast((e:=1, f:="hello"), (c As Integer, d As String)) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(c As System.Int32, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As (a As System.Int32, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType06() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Short, b As String) = (e:=1, f:="hello") End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(a As System.Int16, b As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Dim e = node.Arguments(0).Expression Assert.Equal("1", e.ToString()) Dim typeInfo = model.GetTypeInfo(e) Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.Int16", typeInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(e).Kind) Dim f = node.Arguments(1).Expression Assert.Equal("""hello""", f.ToString()) typeInfo = model.GetTypeInfo(f) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.String", typeInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(f).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As (a As System.Int16, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType06insource() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Short, b As String) = DirectCast((e:=1, f:="hello"), (c As Short, d As String)) Dim y As Short = DirectCast(11, short) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim l11 = nodes.OfType(Of LiteralExpressionSyntax)().ElementAt(2) Assert.Equal("11", l11.ToString()) Assert.Equal("System.Int32", model.GetTypeInfo(l11).Type.ToTestDisplayString()) Assert.Equal("System.Int32", model.GetTypeInfo(l11).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(l11).Kind) Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(node.Parent).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As (a As System.Int16, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedTypeNull01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Short, b As String) = (e:=1, f:=Nothing) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Assert.Equal("(a As System.Int16, b As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As (a As System.Int16, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedTypeNull01insource() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Short, b As String) = DirectCast((e:=1, f:=Nothing), (c As Short, d As String)) Dim y As String = DirectCast(Nothing, String) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim lnothing = nodes.OfType(Of LiteralExpressionSyntax)().ElementAt(2) Assert.Equal("Nothing", lnothing.ToString()) Assert.Null(model.GetTypeInfo(lnothing).Type) Assert.Equal("System.Object", model.GetTypeInfo(lnothing).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNothingLiteral, model.GetConversion(lnothing).Kind) Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(node.Parent).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As (a As System.Int16, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedTypeUDC01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x As (a As Short, b As String) = (e:=1, f:=New C1("qq")) System.Console.Write(x.ToString()) End Sub Class C1 Public Dim s As String Public Sub New(ByVal arg As String) s = arg + "1" End Sub Public Shared Narrowing Operator CType(ByVal arg As C1) As String Return arg.s End Operator End Class End Class <%= s_trivial2uple %> </file> </compilation>, options:=TestOptions.DebugExe) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=New C1(""qq""))", node.ToString()) Assert.Equal("(e As System.Int32, f As C.C1)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(a As System.Int16, b As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.NarrowingTuple, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As (a As System.Int16, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString()) CompileAndVerify(comp, expectedOutput:="{1, qq1}") End Sub <Fact> Public Sub TupleConvertedTypeUDC01_StrictOn() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Class C Shared Sub Main() Dim x As (a As Short, b As String) = (e:=1, f:=New C1("qq")) System.Console.Write(x.ToString()) End Sub Class C1 Public Dim s As String Public Sub New(ByVal arg As String) s = arg + "1" End Sub Public Shared Narrowing Operator CType(ByVal arg As C1) As String Return arg.s End Operator End Class End Class <%= s_trivial2uple %> </file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC41009: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(a As Short, b As String)'. Dim x As (a As Short, b As String) = (e:=1, f:=New C1("qq")) ~~~~ BC41009: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(a As Short, b As String)'. Dim x As (a As Short, b As String) = (e:=1, f:=New C1("qq")) ~~~~~~~~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'C.C1' to 'String'. Dim x As (a As Short, b As String) = (e:=1, f:=New C1("qq")) ~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleConvertedTypeUDC01insource() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x As (a As Short, b As String) = DirectCast((e:=1, f:=New C1("qq")), (c As Short, d As String)) System.Console.Write(x.ToString()) End Sub Class C1 Public Dim s As String Public Sub New(ByVal arg As String) s = arg + "1" End Sub Public Shared Narrowing Operator CType(ByVal arg As C1) As String Return arg.s End Operator End Class End Class <%= s_trivial2uple %> </file> </compilation>, options:=TestOptions.DebugExe) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=New C1(""qq""))", node.ToString()) Assert.Equal("(e As System.Int32, f As C.C1)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.NarrowingTuple, model.GetConversion(node).Kind) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(node.Parent).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As (a As System.Int16, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString()) CompileAndVerify(comp, expectedOutput:="{1, qq1}") End Sub <Fact> <WorkItem(11289, "https://github.com/dotnet/roslyn/issues/11289")> Public Sub TupleConvertedTypeUDC02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x As C1 = (1, "qq") System.Console.Write(x.ToString()) End Sub Class C1 Public Dim val As (Byte, String) Public Sub New(ByVal arg As (Byte, String)) val = arg End Sub Public Shared Narrowing Operator CType(ByVal arg As (Byte, String)) As C1 Return New C1(arg) End Operator Public Overrides Function ToString() As String Return val.ToString() End Function End Class End Class <%= s_trivial2uple %> </file> </compilation>, options:=TestOptions.DebugExe) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(1, ""qq"")", node.ToString()) Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("C.C1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Narrowing Or ConversionKind.UserDefined, model.GetConversion(node).Kind) CompileAndVerify(comp, expectedOutput:="{1, qq}") End Sub <Fact> Public Sub TupleConvertedTypeUDC03() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x As C1 = ("1", "qq") System.Console.Write(x.ToString()) End Sub Class C1 Public Dim val As (Byte, String) Public Sub New(ByVal arg As (Byte, String)) val = arg End Sub Public Shared Narrowing Operator CType(ByVal arg As (Byte, String)) As C1 Return New C1(arg) End Operator Public Overrides Function ToString() As String Return val.ToString() End Function End Class End Class </file> </compilation>, options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> </errors>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(""1"", ""qq"")", node.ToString()) Assert.Equal("(System.String, System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("C.C1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Narrowing Or ConversionKind.UserDefined, model.GetConversion(node).Kind) CompileAndVerify(comp, expectedOutput:="(1, qq)") End Sub <Fact> Public Sub TupleConvertedTypeUDC03_StrictOn() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Class C Shared Sub Main() Dim x As C1 = ("1", "qq") System.Console.Write(x.ToString()) End Sub Class C1 Public Dim val As (Byte, String) Public Sub New(ByVal arg As (Byte, String)) val = arg End Sub Public Shared Narrowing Operator CType(ByVal arg As (Byte, String)) As C1 Return New C1(arg) End Operator Public Overrides Function ToString() As String Return val.ToString() End Function End Class End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30512: Option Strict On disallows implicit conversions from '(String, String)' to 'C.C1'. Dim x As C1 = ("1", "qq") ~~~~~~~~~~~ </errors>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(""1"", ""qq"")", node.ToString()) Assert.Equal("(System.String, System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("C.C1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Narrowing Or ConversionKind.UserDefined, model.GetConversion(node).Kind) End Sub <Fact> <WorkItem(11289, "https://github.com/dotnet/roslyn/issues/11289")> Public Sub TupleConvertedTypeUDC04() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Dim x As C1 = (1, "qq") System.Console.Write(x.ToString()) End Sub Public Class C1 Public Dim val As (Byte, String) Public Sub New(ByVal arg As (Byte, String)) val = arg End Sub Public Overrides Function ToString() As String Return val.ToString() End Function End Class End Class Namespace System Public Structure ValueTuple(Of T1, T2) Public Dim Item1 As T1 Public Dim Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}" End Function Public Shared Narrowing Operator CType(ByVal arg As (T1, T2)) As C.C1 Return New C.C1((CType(DirectCast(DirectCast(arg.Item1, Object), Integer), Byte), DirectCast(DirectCast(arg.Item2, Object), String))) End Operator End Structure End Namespace </file> </compilation>, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics() Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().First() Assert.Equal("(1, ""qq"")", node.ToString()) Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("C.C1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Narrowing Or ConversionKind.UserDefined, model.GetConversion(node).Kind) CompileAndVerify(comp, expectedOutput:="{1, qq}") End Sub <Fact> <WorkItem(11289, "https://github.com/dotnet/roslyn/issues/11289")> Public Sub TupleConvertedTypeUDC05() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Dim x As C1 = (1, "qq") System.Console.Write(x.ToString()) End Sub Public Class C1 Public Dim val As (Byte, String) Public Sub New(ByVal arg As (Byte, String)) val = arg End Sub Public Shared Narrowing Operator CType(ByVal arg As (Byte, String)) As C1 System.Console.Write("C1") Return New C1(arg) End Operator Public Overrides Function ToString() As String Return val.ToString() End Function End Class End Class Namespace System Public Structure ValueTuple(Of T1, T2) Public Dim Item1 As T1 Public Dim Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}" End Function Public Shared Narrowing Operator CType(ByVal arg As (T1, T2)) As C.C1 System.Console.Write("VT ") Return New C.C1((CType(DirectCast(DirectCast(arg.Item1, Object), Integer), Byte), DirectCast(DirectCast(arg.Item2, Object), String))) End Operator End Structure End Namespace </file> </compilation>, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics() Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().First() Assert.Equal("(1, ""qq"")", node.ToString()) Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("C.C1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Narrowing Or ConversionKind.UserDefined, model.GetConversion(node).Kind) CompileAndVerify(comp, expectedOutput:="VT {1, qq}") End Sub <Fact> <WorkItem(11289, "https://github.com/dotnet/roslyn/issues/11289")> Public Sub TupleConvertedTypeUDC06() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Dim x As C1 = (1, Nothing) System.Console.Write(x.ToString()) End Sub Public Class C1 Public Dim val As (Byte, String) Public Sub New(ByVal arg As (Byte, String)) val = arg End Sub Public Shared Narrowing Operator CType(ByVal arg As (Byte, String)) As C1 System.Console.Write("C1") Return New C1(arg) End Operator Public Overrides Function ToString() As String Return val.ToString() End Function End Class End Class Namespace System Public Structure ValueTuple(Of T1, T2) Public Dim Item1 As T1 Public Dim Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}" End Function Public Shared Narrowing Operator CType(ByVal arg As (T1, T2)) As C.C1 System.Console.Write("VT ") Return New C.C1((CType(DirectCast(DirectCast(arg.Item1, Object), Integer), Byte), DirectCast(DirectCast(arg.Item2, Object), String))) End Operator End Structure End Namespace </file> </compilation>, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics() Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().First() Assert.Equal("(1, Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Assert.Equal("C.C1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Narrowing Or ConversionKind.UserDefined, model.GetConversion(node).Kind) CompileAndVerify(comp, expectedOutput:="VT {1, }") End Sub <Fact> Public Sub TupleConvertedTypeUDC07_StrictOff_Narrowing() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Dim x As C1 = M1() System.Console.Write(x.ToString()) End Sub Shared Function M1() As (Integer, String) Return (1, "qq") End Function Public Class C1 Public Dim val As (Byte, String) Public Sub New(ByVal arg As (Byte, String)) val = arg End Sub Public Shared Narrowing Operator CType(ByVal arg As (Byte, String)) As C1 System.Console.Write("C1 ") Return New C1(arg) End Operator End Class End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics() Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() CompileAndVerify(comp, expectedOutput:="C1 C+C1") End Sub <Fact> Public Sub TupleConvertedTypeUDC07() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class C Shared Sub Main() Dim x As C1 = M1() System.Console.Write(x.ToString()) End Sub Shared Function M1() As (Integer, String) Return (1, "qq") End Function Public Class C1 Public Dim val As (Byte, String) Public Sub New(ByVal arg As (Byte, String)) val = arg End Sub Public Shared Widening Operator CType(ByVal arg As (Byte, String)) As C1 System.Console.Write("C1 ") Return New C1(arg) End Operator End Class End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30512: Option Strict On disallows implicit conversions from '(Integer, String)' to 'C.C1'. Dim x As C1 = M1() ~~~~ </errors>) End Sub <Fact> Public Sub Inference01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Test((Nothing, Nothing)) Test((1, 1)) Test((Function() 7, Function() 8), 2) End Sub Shared Sub Test(Of T)(x As (T, T)) System.Console.WriteLine("first") End Sub Shared Sub Test(x As (Object, Object)) System.Console.WriteLine("second") End Sub Shared Sub Test(Of T)(x As (System.Func(Of T), System.Func(Of T)), y As T) System.Console.WriteLine("third") System.Console.WriteLine(x.Item1().ToString()) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" second first third 7 ") End Sub <Fact> Public Sub Inference02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Test1((Function() 7, Function() 8)) Test2(Function() 7, Function() 8) Test3((Function() 7, Function() 8)) End Sub Shared Sub Test1(Of T)(x As (T, T)) System.Console.WriteLine("first") End Sub Shared Sub Test1(x As (Object, Object)) System.Console.WriteLine("second") End Sub Shared Sub Test1(Of T)(x As (System.Func(Of T), System.Func(Of T))) System.Console.WriteLine("third") End Sub Shared Sub Test2(Of T)(x As T, y As T) System.Console.WriteLine("first") End Sub Shared Sub Test2(x As Object, y As Object) System.Console.WriteLine("second") End Sub Shared Sub Test2(Of T)(x As System.Func(Of T), y As System.Func(Of T)) System.Console.WriteLine("third") End Sub Shared Sub Test3(Of T)(x As (T, T)?) System.Console.WriteLine("first") End Sub Shared Sub Test3(x As (Object, Object)?) System.Console.WriteLine("second") End Sub Shared Sub Test3(Of T)(x As (System.Func(Of T), System.Func(Of T))?) System.Console.WriteLine("third") End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" first first first") End Sub <Fact> Public Sub DelegateRelaxationLevel_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Test1((Function() 7, Function() 8)) Test2(Function() 7, Function() 8) Test3((Function() 7, Function() 8)) End Sub Shared Sub Test1(x As (System.Func(Of Integer), System.Func(Of Integer))) System.Console.WriteLine("second") End Sub Shared Sub Test1(x As (System.Func(Of Integer, Integer), System.Func(Of Integer, Integer))) System.Console.WriteLine("third") End Sub Shared Sub Test2(x As System.Func(Of Integer), y As System.Func(Of Integer)) System.Console.WriteLine("second") End Sub Shared Sub Test2(x As System.Func(Of Integer, Integer), y As System.Func(Of Integer, Integer)) System.Console.WriteLine("third") End Sub Shared Sub Test3(x As (System.Func(Of Integer), System.Func(Of Integer))?) System.Console.WriteLine("second") End Sub Shared Sub Test3(x As (System.Func(Of Integer, Integer), System.Func(Of Integer, Integer))?) System.Console.WriteLine("third") End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" second second second") End Sub <Fact> Public Sub DelegateRelaxationLevel_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Dim int = 1 Dim a = Function(x as Integer) x Test1(a, int) Test2((a, int)) Test3((a, int)) Dim b = (a, int) Test2(b) Test3(b) End Sub Shared Sub Test1(x As System.Action(Of Integer), y As Integer) System.Console.WriteLine("second") End Sub Shared Sub Test1(x As System.Func(Of Integer, Integer), y As Integer) System.Console.WriteLine("third") End Sub Shared Sub Test2(x As (System.Action(Of Integer), Integer)) System.Console.WriteLine("second") End Sub Shared Sub Test2(x As (System.Func(Of Integer, Integer), Integer)) System.Console.WriteLine("third") End Sub Shared Sub Test3(x As (System.Action(Of Integer), Integer)?) System.Console.WriteLine("second") End Sub Shared Sub Test3(x As (System.Func(Of Integer, Integer), Integer)?) System.Console.WriteLine("third") End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" third third third third third") End Sub <Fact> Public Sub DelegateRelaxationLevel_03() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Imports System Public Class C Shared Sub Main() Dim int as integer = 1 Dim x00 As (Integer, Func(Of Integer)) = (int, Function() int) Dim x01 As (Integer, Func(Of Long)) = (int, Function() int) Dim x02 As (Integer, Action) = (int, Function() int) Dim x03 As (Integer, Object) = (int, Function() int) Dim x04 As (Integer, Func(Of Short)) = (int, Function() int) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ToArray() AssertConversions(model, nodes(0), ConversionKind.WideningTuple, ConversionKind.Identity, ConversionKind.Widening Or ConversionKind.Lambda) AssertConversions(model, nodes(1), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWidening, ConversionKind.Identity, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWidening) AssertConversions(model, nodes(2), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs, ConversionKind.Identity, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs) AssertConversions(model, nodes(3), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda, ConversionKind.Identity, ConversionKind.WideningReference Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda) AssertConversions(model, nodes(4), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, ConversionKind.Identity, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelNarrowing) End Sub <Fact> Public Sub DelegateRelaxationLevel_04() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Imports System Public Class C Shared Sub Main() Dim int as integer = 1 Dim x00 As (Func(Of Integer), Integer) = (Function() int, int) Dim x01 As (Func(Of Long), Integer) = (Function() int, int) Dim x02 As (Action, Integer) = (Function() int, int) Dim x03 As (Object, Integer) = (Function() int, int) Dim x04 As (Func(Of Short), Integer) = (Function() int, int) Dim x05 As (Func(Of Short), Func(Of Long)) = (Function() int, Function() int) Dim x06 As (Func(Of Long), Func(Of Short)) = (Function() int, Function() int) Dim x07 As (Short, (Func(Of Long), Func(Of Short))) = (int, (Function() int, Function() int)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ToArray() AssertConversions(model, nodes(0), ConversionKind.WideningTuple, ConversionKind.Widening Or ConversionKind.Lambda, ConversionKind.Identity) AssertConversions(model, nodes(1), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWidening, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWidening, ConversionKind.Identity) AssertConversions(model, nodes(2), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs, ConversionKind.Identity) AssertConversions(model, nodes(3), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda, ConversionKind.WideningReference Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda, ConversionKind.Identity) AssertConversions(model, nodes(4), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelNarrowing, ConversionKind.Identity) AssertConversions(model, nodes(5), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelNarrowing, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWidening) AssertConversions(model, nodes(6), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWidening, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelNarrowing) AssertConversions(model, nodes(7), ConversionKind.NarrowingTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, ConversionKind.NarrowingNumeric, ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelNarrowing) End Sub <Fact> Public Sub DelegateRelaxationLevel_05() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Imports System Public Class C Shared Sub Main() Dim int as integer = 1 Dim x00 As (Integer, Func(Of Integer))? = (int, Function() int) Dim x01 As (Short, Func(Of Long))? = (int, Function() int) Dim x02 As (Integer, Action)? = (int, Function() int) Dim x03 As (Integer, Object)? = (int, Function() int) Dim x04 As (Integer, Func(Of Short))? = (int, Function() int) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ToArray() AssertConversions(model, nodes(0), ConversionKind.WideningNullableTuple, ConversionKind.Identity, ConversionKind.Widening Or ConversionKind.Lambda) AssertConversions(model, nodes(1), ConversionKind.NarrowingNullableTuple Or ConversionKind.DelegateRelaxationLevelWidening, ConversionKind.NarrowingNumeric, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWidening) AssertConversions(model, nodes(2), ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs, ConversionKind.Identity, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs) AssertConversions(model, nodes(3), ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda, ConversionKind.Identity, ConversionKind.WideningReference Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda) AssertConversions(model, nodes(4), ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, ConversionKind.Identity, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelNarrowing) End Sub <Fact> Public Sub DelegateRelaxationLevel_06() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Imports System Public Class C Shared Sub Main() Dim int as integer = 1 Dim t = (int, Function() int) Dim x00 As (Integer, Func(Of Integer)) = t Dim x01 As (Integer, Func(Of Long)) = t Dim x02 As (Integer, Action) = t Dim x03 As (Integer, Object) = t Dim x04 As (Integer, Func(Of Short)) = t End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(id) id.Identifier.ValueText = "t").ToArray() Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(nodes(0)).Kind) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWidening, model.GetConversion(nodes(1)).Kind) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs, model.GetConversion(nodes(2)).Kind) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda, model.GetConversion(nodes(3)).Kind) Assert.Equal(ConversionKind.NarrowingTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, model.GetConversion(nodes(4)).Kind) End Sub <Fact> Public Sub DelegateRelaxationLevel_07() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Imports System Public Class C Shared Sub Main() Dim int as integer = 1 Dim t = (int, Function() int) Dim x00 As (Integer, Func(Of Integer))? = t Dim x01 As (Integer, Func(Of Long))? = t Dim x02 As (Integer, Action)? = t Dim x03 As (Integer, Object)? = t Dim x04 As (Integer, Func(Of Short))? = t End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(id) id.Identifier.ValueText = "t").ToArray() Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(nodes(0)).Kind) Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWidening, model.GetConversion(nodes(1)).Kind) Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs, model.GetConversion(nodes(2)).Kind) Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda, model.GetConversion(nodes(3)).Kind) Assert.Equal(ConversionKind.NarrowingNullableTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, model.GetConversion(nodes(4)).Kind) End Sub <Fact> Public Sub DelegateRelaxationLevel_08() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Imports System Public Class C Shared Sub Main() Dim int as integer = 1 Dim t? = (int, Function() int) Dim x00 As (Integer, Func(Of Integer))? = t Dim x01 As (Integer, Func(Of Long))? = t Dim x02 As (Integer, Action)? = t Dim x03 As (Integer, Object)? = t Dim x04 As (Integer, Func(Of Short))? = t End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(id) id.Identifier.ValueText = "t").ToArray() Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(nodes(0)).Kind) Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWidening, model.GetConversion(nodes(1)).Kind) Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs, model.GetConversion(nodes(2)).Kind) Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda, model.GetConversion(nodes(3)).Kind) Assert.Equal(ConversionKind.NarrowingNullableTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, model.GetConversion(nodes(4)).Kind) End Sub <Fact> Public Sub DelegateRelaxationLevel_09() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Imports System Public Class C Shared Sub Main() Dim int as integer = 1 Dim t? = (int, Function() int) Dim x00 As (Integer, Func(Of Integer)) = t Dim x01 As (Integer, Func(Of Long)) = t Dim x02 As (Integer, Action) = t Dim x03 As (Integer, Object) = t Dim x04 As (Integer, Func(Of Short)) = t End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(id) id.Identifier.ValueText = "t").ToArray() Assert.Equal(ConversionKind.NarrowingNullableTuple, model.GetConversion(nodes(0)).Kind) Assert.Equal(ConversionKind.NarrowingNullableTuple Or ConversionKind.DelegateRelaxationLevelWidening, model.GetConversion(nodes(1)).Kind) Assert.Equal(ConversionKind.NarrowingNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs, model.GetConversion(nodes(2)).Kind) Assert.Equal(ConversionKind.NarrowingNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda, model.GetConversion(nodes(3)).Kind) Assert.Equal(ConversionKind.NarrowingNullableTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, model.GetConversion(nodes(4)).Kind) End Sub <Fact> Public Sub AnonymousDelegate_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Dim int = 1 Dim a = Function(x as Integer) x Test1(a) Test2((a, int)) Test3((a, int)) Dim b = (a, int) Test2(b) Test3(b) End Sub Shared Sub Test1(x As Object) System.Console.WriteLine("second") End Sub Shared Sub Test2(x As (Object, Integer)) System.Console.WriteLine("second") End Sub Shared Sub Test3(x As (Object, Integer)?) System.Console.WriteLine("second") End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" second second second second second") End Sub <Fact> <WorkItem(14529, "https://github.com/dotnet/roslyn/issues/14529")> <WorkItem(14530, "https://github.com/dotnet/roslyn/issues/14530")> Public Sub AnonymousDelegate_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Dim int = 1 Dim a = Function(x as Integer) x Test1(a) Test2((a, int)) Test3((a, int)) Dim b = (a, int) Test2(b) Test3(b) Test4({a}) End Sub Shared Sub Test1(Of T)(x As System.Func(Of T, T)) System.Console.WriteLine("third") End Sub Shared Sub Test2(Of T)(x As (System.Func(Of T, T), Integer)) System.Console.WriteLine("third") End Sub Shared Sub Test3(Of T)(x As (System.Func(Of T, T), Integer)?) System.Console.WriteLine("third") End Sub Shared Sub Test4(Of T)(x As System.Func(Of T, T)()) System.Console.WriteLine("third") End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" third third third third third third") End Sub <Fact> Public Sub UserDefinedConversions_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Public Class C Shared Sub Main() Dim int = 1 Dim tuple = (int, int) Dim a as (A, Integer) = tuple Dim b as (A, Integer) = (int, int) Dim c as (A, Integer)? = tuple Dim d as (A, Integer)? = (int, int) System.Console.WriteLine(a) System.Console.WriteLine(b) System.Console.WriteLine(c) System.Console.WriteLine(d) End Sub End Class Class A Public Shared Widening Operator CType(val As String) As A System.Console.WriteLine(val) Return New A() End Operator End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" 1 1 1 1 (A, 1) (A, 1) (A, 1) (A, 1)") End Sub <Fact> Public Sub UserDefinedConversions_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Public Class C Shared Sub Main() Dim int = 1 Dim val as new B() Dim tuple = (val, int) Dim a as (Integer, Integer) = tuple Dim b as (Integer, Integer) = (val, int) Dim c as (Integer, Integer)? = tuple Dim d as (Integer, Integer)? = (val, int) System.Console.WriteLine(a) System.Console.WriteLine(b) System.Console.WriteLine(c) System.Console.WriteLine(d) End Sub End Class Class B Public Shared Widening Operator CType(val As B) As String System.Console.WriteLine(val Is Nothing) Return "2" End Operator End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" False False False False (2, 1) (2, 1) (2, 1) (2, 1)") End Sub <Fact> <WorkItem(14530, "https://github.com/dotnet/roslyn/issues/14530")> Public Sub UserDefinedConversions_03() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Public Class C Shared Sub Main() Dim int = 1 Dim ad = Function() 2 Dim tuple = (ad, int) Dim a as (A, Integer) = tuple Dim b as (A, Integer) = (ad, int) Dim c as (A, Integer)? = tuple Dim d as (A, Integer)? = (ad, int) System.Console.WriteLine(a) System.Console.WriteLine(b) System.Console.WriteLine(c) System.Console.WriteLine(d) End Sub End Class Class A Public Shared Widening Operator CType(val As System.Func(Of Integer, Integer)) As A System.Console.WriteLine(val) Return New A() End Operator End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" System.Func`2[System.Int32,System.Int32] System.Func`2[System.Int32,System.Int32] System.Func`2[System.Int32,System.Int32] System.Func`2[System.Int32,System.Int32] (A, 1) (A, 1) (A, 1) (A, 1)") End Sub <Fact> Public Sub Inference02_Addressof() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Function M() As Integer Return 7 End Function Shared Sub Main() Test((AddressOf M, AddressOf M)) End Sub Shared Sub Test(Of T)(x As (T, T)) System.Console.WriteLine("first") End Sub Shared Sub Test(x As (Object, Object)) System.Console.WriteLine("second") End Sub Shared Sub Test(Of T)(x As (System.Func(Of T), System.Func(Of T))) System.Console.WriteLine("third") System.Console.WriteLine(x.Item1().ToString()) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" third 7 ") End Sub <Fact> Public Sub Inference03_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Test((Function(x) x, Function(x) x)) End Sub Shared Sub Test(Of T)(x As (T, T)) End Sub Shared Sub Test(x As (Object, Object)) End Sub Shared Sub Test(Of T)(x As (System.Func(Of Integer, T), System.Func(Of T, T))) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected><![CDATA[ BC30521: Overload resolution failed because no accessible 'Test' is most specific for these arguments: 'Public Shared Sub Test(Of <generated method>)(x As (<generated method>, <generated method>))': Not most specific. 'Public Shared Sub Test(Of Integer)(x As (Func(Of Integer, Integer), Func(Of Integer, Integer)))': Not most specific. Test((Function(x) x, Function(x) x)) ~~~~ ]]></expected>) End Sub <Fact> Public Sub Inference03_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Test((Function(x) x, Function(x) x)) End Sub Shared Sub Test(x As (Object, Object)) System.Console.WriteLine("second") End Sub Shared Sub Test(Of T)(x As (System.Func(Of Integer, T), System.Func(Of T, T))) System.Console.WriteLine("third") System.Console.WriteLine(x.Item1(5).ToString()) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" third 5 ") End Sub <Fact> Public Sub Inference03_03() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Test((Function(x) x, Function(x) x)) End Sub Shared Sub Test(Of T)(x As T, y As T) System.Console.WriteLine("first") End Sub Shared Sub Test(x As (Object, Object)) System.Console.WriteLine("second") End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" second ") End Sub <Fact> Public Sub Inference05() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Test((Function(x) x.x, Function(x) x.Item2)) Test((Function(x) x.bob, Function(x) x.Item1)) End Sub Shared Sub Test(Of T)(x As (f1 As Func(Of (x As Byte, y As Byte), T), f2 As Func(Of (Integer, Integer), T))) Console.WriteLine("first") Console.WriteLine(x.f1((2, 3)).ToString()) Console.WriteLine(x.f2((2, 3)).ToString()) End Sub Shared Sub Test(Of T)(x As (f1 As Func(Of (alice As Integer, bob As Integer), T), f2 As Func(Of (Integer, Integer), T))) Console.WriteLine("second") Console.WriteLine(x.f1((4, 5)).ToString()) Console.WriteLine(x.f2((4, 5)).ToString()) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:="first 2 3 second 5 4 ") End Sub <Fact> Public Sub Inference08() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Test1((a:=1, b:=2), (c:=3, d:=4)) Test2((a:=1, b:=2), (c:=3, d:=4), Function(t) t.Item2) Test2((a:=1, b:=2), (a:=3, b:=4), Function(t) t.a) Test2((a:=1, b:=2), (c:=3, d:=4), Function(t) t.a) End Sub Shared Sub Test1(Of T)(x As T, y As T) Console.WriteLine("test1") Console.WriteLine(x) End Sub Shared Sub Test2(Of T)(x As T, y As T, f As Func(Of T, Integer)) Console.WriteLine("test2_1") Console.WriteLine(f(x)) End Sub Shared Sub Test2(Of T)(x As T, y As Object, f As Func(Of T, Integer)) Console.WriteLine("test2_2") Console.WriteLine(f(x)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" test1 (1, 2) test2_1 2 test2_1 1 test2_2 1 ") End Sub <Fact> Public Sub Inference08t() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim ab = (a:=1, b:=2) Dim cd = (c:=3, d:=4) Test1(ab, cd) Test2(ab, cd, Function(t) t.Item2) Test2(ab, ab, Function(t) t.a) Test2(ab, cd, Function(t) t.a) End Sub Shared Sub Test1(Of T)(x As T, y As T) Console.WriteLine("test1") Console.WriteLine(x) End Sub Shared Sub Test2(Of T)(x As T, y As T, f As Func(Of T, Integer)) Console.WriteLine("test2_1") Console.WriteLine(f(x)) End Sub Shared Sub Test2(Of T)(x As T, y As Object, f As Func(Of T, Integer)) Console.WriteLine("test2_2") Console.WriteLine(f(x)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" test1 (1, 2) test2_1 2 test2_1 1 test2_2 1 ") End Sub <Fact> Public Sub Inference09() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Test1((a:=1, b:=2), DirectCast(1, ValueType)) End Sub Shared Sub Test1(Of T)(x As T, y As T) Console.Write(GetType(T)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:="System.ValueType") End Sub <Fact> Public Sub Inference10() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim t = (a:=1, b:=2) Test1(t, DirectCast(1, ValueType)) End Sub Shared Sub Test1(Of T)(ByRef x As T, y As T) Console.Write(GetType(T)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC36651: Data type(s) of the type parameter(s) in method 'Public Shared Sub Test1(Of T)(ByRef x As T, y As T)' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error. Test1(t, DirectCast(1, ValueType)) ~~~~~ </errors>) End Sub <Fact> Public Sub Inference11() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim ab = (a:=1, b:=2) Dim cd = (c:=1, d:=2) Test3(ab, cd) Test1(ab, cd) Test2(ab, cd) End Sub Shared Sub Test1(Of T)(ByRef x As T, y As T) Console.Write(GetType(T)) End Sub Shared Sub Test2(Of T)(x As T, ByRef y As T) Console.Write(GetType(T)) End Sub Shared Sub Test3(Of T)(ByRef x As T, ByRef y As T) Console.Write(GetType(T)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> </errors>) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim test3 = tree.GetRoot().DescendantNodes().OfType(Of InvocationExpressionSyntax)().First() Assert.Equal("Sub C.Test3(Of (System.Int32, System.Int32))(ByRef x As (System.Int32, System.Int32), ByRef y As (System.Int32, System.Int32))", model.GetSymbolInfo(test3).Symbol.ToTestDisplayString()) End Sub <Fact> Public Sub Inference12() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=DirectCast(1, Object))) Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(c:=1, d:=2))) Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(1, 2))) Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(a:=1, b:=2))) End Sub Shared Sub Test1(Of T, U)(x As (T, U), y As (T, U)) Console.WriteLine(GetType(U)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" System.Object System.ValueTuple`2[System.Int32,System.Int32] System.ValueTuple`2[System.Int32,System.Int32] System.ValueTuple`2[System.Int32,System.Int32] ") End Sub <Fact> <WorkItem(14152, "https://github.com/dotnet/roslyn/issues/14152")> Public Sub Inference13() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=DirectCast(1, Object))) Test1(Nullable((a:=1, b:=(a:=1, b:=2))), (a:=1, b:=DirectCast(1, Object))) Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(c:=1, d:=2))) Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(1, 2))) Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(a:=1, b:=2))) End Sub Shared Function Nullable(Of T as structure)(x as T) as T? return x End Function Shared Sub Test1(Of T, U)(x As (T, U)?, y As (T, U)) Console.WriteLine(GetType(U)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" System.Object System.Object System.ValueTuple`2[System.Int32,System.Int32] System.ValueTuple`2[System.Int32,System.Int32] System.ValueTuple`2[System.Int32,System.Int32] ") End Sub <Fact> <WorkItem(22329, "https://github.com/dotnet/roslyn/issues/22329")> <WorkItem(14152, "https://github.com/dotnet/roslyn/issues/14152")> Public Sub Inference13a() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Test2(Nullable((a:=1, b:=(a:=1, b:=2))), (a:=1, b:=DirectCast(1, Object))) Test2((a:=1, b:=(a:=1, b:=2)), Nullable((a:=1, b:=DirectCast((a:=1, b:=2), Object)))) End Sub Shared Function Nullable(Of T as structure)(x as T) as T? return x End Function Shared Sub Test2(Of T, U)(x As (T, U), y As (T, U)) Console.WriteLine(GetType(U)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected> BC36645: Data type(s) of the type parameter(s) in method 'Public Shared Sub Test2(Of T, U)(x As (T, U), y As (T, U))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. Test2(Nullable((a:=1, b:=(a:=1, b:=2))), (a:=1, b:=DirectCast(1, Object))) ~~~~~ BC36645: Data type(s) of the type parameter(s) in method 'Public Shared Sub Test2(Of T, U)(x As (T, U), y As (T, U))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. Test2((a:=1, b:=(a:=1, b:=2)), Nullable((a:=1, b:=DirectCast((a:=1, b:=2), Object)))) ~~~~~ </expected>) End Sub <Fact> Public Sub Inference14() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(c:=1, d:=2))) Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(1, 2))) Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(a:=1, b:=2))) End Sub Shared Sub Test1(Of T, U As Structure)(x As (T, U)?, y As (T, U)?) Console.WriteLine(GetType(U)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" System.ValueTuple`2[System.Int32,System.Int32] System.ValueTuple`2[System.Int32,System.Int32] System.ValueTuple`2[System.Int32,System.Int32] ") ' In C#, there are errors because names matter during best type inference ' This should get fixed after issue https://github.com/dotnet/roslyn/issues/13938 is fixed End Sub <Fact> Public Sub Inference15() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Test1((a:="1", b:=Nothing), (a:=Nothing, b:="w"), Function(x) x.z) End Sub Shared Sub Test1(Of T, U)(x As (T, U), y As (T, U), f As Func(Of (x As T, z As U), T)) Console.WriteLine(GetType(U)) Console.WriteLine(f(y)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" System.String w ") End Sub <Fact> Public Sub Inference16() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim x = (1, 2, 3) Test(x) Dim x1 = (1, 2, CType(3, Long)) Test(x1) Dim x2 = (1, DirectCast(2, Object), CType(3, Long)) Test(x2) End Sub Shared Sub Test(Of T)(x As (T, T, T)) Console.WriteLine(GetType(T)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" System.Int32 System.Int64 System.Object ") End Sub <Fact()> Public Sub Constraints_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Namespace System Public Structure ValueTuple(Of T1 As Class, T2) Sub New(_1 As T1, _2 As T2) End Sub End Structure End Namespace Class C Sub M(p As (Integer, Integer)) Dim t0 = (1, 2) Dim t1 As (Integer, Integer) = t0 End Sub End Class ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T1'. Sub M(p As (Integer, Integer)) ~ BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T1'. Dim t0 = (1, 2) ~ BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T1'. Dim t1 As (Integer, Integer) = t0 ~~~~~~~ </errors>) End Sub <Fact()> Public Sub Constraints_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C Sub M(p As (Integer, ArgIterator), q As ValueTuple(Of Integer, ArgIterator)) Dim t0 As (Integer, ArgIterator) = p Dim t1 = (1, New ArgIterator()) Dim t2 = New ValueTuple(Of Integer, ArgIterator)(1, Nothing) Dim t3 As ValueTuple(Of Integer, ArgIterator) = t2 End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Sub M(p As (Integer, ArgIterator), q As ValueTuple(Of Integer, ArgIterator)) ~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Sub M(p As (Integer, ArgIterator), q As ValueTuple(Of Integer, ArgIterator)) ~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim t0 As (Integer, ArgIterator) = p ~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim t1 = (1, New ArgIterator()) ~~~~~~~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim t2 = New ValueTuple(Of Integer, ArgIterator)(1, Nothing) ~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim t3 As ValueTuple(Of Integer, ArgIterator) = t2 ~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub Constraints_03() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System.Collections.Generic Namespace System Public Structure ValueTuple(Of T1, T2 As Class) Sub New(_1 As T1, _2 As T2) End Sub End Structure End Namespace Class C(Of T) Dim field As List(Of (T, T)) Function M(Of U)(x As U) As (U, U) Dim t0 = New C(Of Integer)() Dim t1 = M(1) Return (Nothing, Nothing) End Function End Class ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC32106: Type argument 'T' does not satisfy the 'Class' constraint for type parameter 'T2'. Dim field As List(Of (T, T)) ~ BC32106: Type argument 'U' does not satisfy the 'Class' constraint for type parameter 'T2'. Function M(Of U)(x As U) As (U, U) ~~~~~~ </errors>) End Sub <Fact()> Public Sub Constraints_04() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System.Collections.Generic Namespace System Public Structure ValueTuple(Of T1, T2 As Class) Sub New(_1 As T1, _2 As T2) End Sub End Structure End Namespace Class C(Of T As Class) Dim field As List(Of (T, T)) Function M(Of U As Class)(x As U) As (U, U) Dim t0 = New C(Of Integer)() Dim t1 = M(1) Return (Nothing, Nothing) End Function End Class ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T'. Dim t0 = New C(Of Integer)() ~~~~~~~ BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'U'. Dim t1 = M(1) ~ </errors>) End Sub <Fact()> Public Sub Constraints_05() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System.Collections.Generic Namespace System Public Structure ValueTuple(Of T1, T2 As Structure) Sub New(_1 As T1, _2 As T2) End Sub End Structure End Namespace Class C(Of T As Class) Dim field As List(Of (T, T)) Function M(Of U As Class)(x As (U, U)) As (U, U) Dim t0 = New C(Of Integer)() Dim t1 = M((1, 2)) Return (Nothing, Nothing) End Function End Class ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC32105: Type argument 'T' does not satisfy the 'Structure' constraint for type parameter 'T2'. Dim field As List(Of (T, T)) ~ BC32105: Type argument 'U' does not satisfy the 'Structure' constraint for type parameter 'T2'. Function M(Of U As Class)(x As (U, U)) As (U, U) ~ BC32105: Type argument 'U' does not satisfy the 'Structure' constraint for type parameter 'T2'. Function M(Of U As Class)(x As (U, U)) As (U, U) ~~~~~~ BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T'. Dim t0 = New C(Of Integer)() ~~~~~~~ BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'U'. Dim t1 = M((1, 2)) ~ BC32105: Type argument 'Object' does not satisfy the 'Structure' constraint for type parameter 'T2'. Return (Nothing, Nothing) ~~~~~~~ </errors>) End Sub <Fact()> Public Sub Constraints_06() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Namespace System Public Structure ValueTuple(Of T1 As Class) Public Sub New(item1 As T1) End Sub End Structure Public Structure ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest As Class) Public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6, item7 As T7, rest As TRest) End Sub End Structure End Namespace Class C Sub M(p As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)) Dim t0 = (1, 2, 3, 4, 5, 6, 7, 8) Dim t1 As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = t0 End Sub End Class ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T1'. Sub M(p As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)) ~ BC32106: Type argument 'ValueTuple(Of Integer)' does not satisfy the 'Class' constraint for type parameter 'TRest'. Sub M(p As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)) ~ BC32106: Type argument 'ValueTuple(Of Integer)' does not satisfy the 'Class' constraint for type parameter 'TRest'. Dim t0 = (1, 2, 3, 4, 5, 6, 7, 8) ~~~~~~~~~~~~~~~~~~~~~~~~ BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T1'. Dim t0 = (1, 2, 3, 4, 5, 6, 7, 8) ~ BC32106: Type argument 'ValueTuple(Of Integer)' does not satisfy the 'Class' constraint for type parameter 'TRest'. Dim t1 As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = t0 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T1'. Dim t1 As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = t0 ~~~~~~~ </errors>) End Sub <Fact()> Public Sub LongTupleConstraints() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C Sub M0(p As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator)) Dim t1 As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator) = p Dim t2 = (1, 2, 3, 4, 5, 6, 7, New ArgIterator()) Dim t3 = New ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer, ArgIterator))() Dim t4 = New ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, ArgIterator))() Dim t5 As ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer, ArgIterator)) = t3 Dim t6 As ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, ArgIterator)) = t4 End Sub Sub M1(q As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator)) Dim v1 As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator) = q Dim v2 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, New ArgIterator()) End Sub End Class]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Sub M0(p As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator)) ~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim t1 As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator) = p ~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim t2 = (1, 2, 3, 4, 5, 6, 7, New ArgIterator()) ~~~~~~~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim t3 = New ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer, ArgIterator))() ~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim t4 = New ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, ArgIterator))() ~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim t5 As ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer, ArgIterator)) = t3 ~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim t6 As ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, ArgIterator)) = t4 ~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Sub M1(q As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator)) ~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim v1 As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator) = q ~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim v2 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, New ArgIterator()) ~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub RestrictedTypes1() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim x = (1, 2, New ArgIterator()) Dim y As (x As Integer, y As Object) = (1, 2, New ArgIterator()) Dim z As (x As Integer, y As ArgIterator) = (1, 2, New ArgIterator()) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x = (1, 2, New ArgIterator()) ~~~~~~~~~~~~~~~~~ BC30311: Value of type '(Integer, Integer, ArgIterator)' cannot be converted to '(x As Integer, y As Object)'. Dim y As (x As Integer, y As Object) = (1, 2, New ArgIterator()) ~~~~~~~~~~~~~~~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim y As (x As Integer, y As Object) = (1, 2, New ArgIterator()) ~~~~~~~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim z As (x As Integer, y As ArgIterator) = (1, 2, New ArgIterator()) ~ BC30311: Value of type '(Integer, Integer, ArgIterator)' cannot be converted to '(x As Integer, y As ArgIterator)'. Dim z As (x As Integer, y As ArgIterator) = (1, 2, New ArgIterator()) ~~~~~~~~~~~~~~~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim z As (x As Integer, y As ArgIterator) = (1, 2, New ArgIterator()) ~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub RestrictedTypes2() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim y As (x As Integer, y As ArgIterator) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC42024: Unused local variable: 'y'. Dim y As (x As Integer, y As ArgIterator) ~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim y As (x As Integer, y As ArgIterator) ~ </errors>) End Sub <Fact> Public Sub ImplementInterface() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Interface I Function M(value As (x As Integer, y As String)) As (Alice As Integer, Bob As String) ReadOnly Property P1 As (Alice As Integer, Bob As String) End Interface Public Class C Implements I Shared Sub Main() Dim c = New C() Dim x = c.M(c.P1) Console.Write(x) End Sub Public Function M(value As (x As Integer, y As String)) As (Alice As Integer, Bob As String) Implements I.M Return value End Function ReadOnly Property P1 As (Alice As Integer, Bob As String) Implements I.P1 Get Return (r:=1, s:="hello") End Get End Property End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:="(1, hello)") End Sub <Fact> Public Sub TupleTypeArguments() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Interface I(Of TA, TB As TA) Function M(a As TA, b As TB) As (TA, TB) End Interface Public Class C Implements I(Of (Integer, String), (Alice As Integer, Bob As String)) Shared Sub Main() Dim c = New C() Dim x = c.M((1, "Australia"), (2, "Brazil")) Console.Write(x) End Sub Public Function M(x As (Integer, String), y As (Alice As Integer, Bob As String)) As ((Integer, String), (Alice As Integer, Bob As String)) Implements I(Of (Integer, String), (Alice As Integer, Bob As String)).M Return (x, y) End Function End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:="((1, Australia), (2, Brazil))") End Sub <Fact> Public Sub OverrideGenericInterfaceWithDifferentNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Interface I(Of TA, TB As TA) Function M(paramA As TA, paramB As TB) As (returnA As TA, returnB As TB) End Interface Public Class C Implements I(Of (a As Integer, b As String), (Integer, String)) Public Overridable Function M(x As ((Integer, Integer), (Integer, Integer))) As (x As (Integer, Integer), y As (Integer, Integer)) Implements I(Of (b As Integer, a As Integer), (a As Integer, b As Integer)).M Throw New Exception() End Function End Class </file> </compilation>, options:=TestOptions.DebugDll, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30149: Class 'C' must implement 'Function M(paramA As (a As Integer, b As String), paramB As (Integer, String)) As (returnA As (a As Integer, b As String), returnB As (Integer, String))' for interface 'I(Of (a As Integer, b As String), (Integer, String))'. Implements I(Of (a As Integer, b As String), (Integer, String)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31035: Interface 'I(Of (b As Integer, a As Integer), (a As Integer, b As Integer))' is not implemented by this class. Public Overridable Function M(x As ((Integer, Integer), (Integer, Integer))) As (x As (Integer, Integer), y As (Integer, Integer)) Implements I(Of (b As Integer, a As Integer), (a As Integer, b As Integer)).M ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleWithoutFeatureFlag() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim x As (Integer, Integer) = (1, 1) Else End Sub End Class </file> </compilation>, options:=TestOptions.DebugDll, additionalRefs:=s_valueTupleRefs, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic14)) comp.AssertTheseDiagnostics( <errors> BC36716: Visual Basic 14.0 does not support tuples. Dim x As (Integer, Integer) = (1, 1) ~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 14.0 does not support tuples. Dim x As (Integer, Integer) = (1, 1) ~~~~~~ BC30086: 'Else' must be preceded by a matching 'If' or 'ElseIf'. Else ~~~~ </errors>) Dim x = comp.GetDiagnostics() Assert.Equal("15", Compilation.GetRequiredLanguageVersion(comp.GetDiagnostics()(0))) Assert.Null(Compilation.GetRequiredLanguageVersion(comp.GetDiagnostics()(2))) Assert.Throws(Of ArgumentNullException)(Sub() Compilation.GetRequiredLanguageVersion(Nothing)) End Sub <Fact> Public Sub DefaultAndFriendlyElementNames_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim v1 = M1() Console.WriteLine($"{v1.Item1} {v1.Item2}") Dim v2 = M2() Console.WriteLine($"{v2.Item1} {v2.Item2} {v2.a2} {v2.b2}") Dim v6 = M6() Console.WriteLine($"{v6.Item1} {v6.Item2} {v6.item1} {v6.item2}") Console.WriteLine(v1.ToString()) Console.WriteLine(v2.ToString()) Console.WriteLine(v6.ToString()) End Sub Shared Function M1() As (Integer, Integer) Return (1, 11) End Function Shared Function M2() As (a2 As Integer, b2 As Integer) Return (2, 22) End Function Shared Function M6() As (item1 As Integer, item2 As Integer) Return (6, 66) End Function End Class </file> </compilation>, options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" 1 11 2 22 2 22 6 66 6 66 (1, 11) (2, 22) (6, 66) ") Dim c = comp.GetTypeByMetadataName("C") Dim m1Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M1").ReturnType, NamedTypeSymbol) Dim m2Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M2").ReturnType, NamedTypeSymbol) Dim m6Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M6").ReturnType, NamedTypeSymbol) AssertTestDisplayString(m1Tuple.GetMembers(), "(System.Int32, System.Int32).Item1 As System.Int32", "(System.Int32, System.Int32).Item2 As System.Int32", "Sub (System.Int32, System.Int32)..ctor()", "Sub (System.Int32, System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)", "Function (System.Int32, System.Int32).Equals(obj As System.Object) As System.Boolean", "Function (System.Int32, System.Int32).Equals(other As (System.Int32, System.Int32)) As System.Boolean", "Function (System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function (System.Int32, System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function (System.Int32, System.Int32).CompareTo(other As (System.Int32, System.Int32)) As System.Int32", "Function (System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function (System.Int32, System.Int32).GetHashCode() As System.Int32", "Function (System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32).ToString() As System.String", "Function (System.Int32, System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function (System.Int32, System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property (System.Int32, System.Int32).System.ITupleInternal.Size As System.Int32" ) Assert.Equal({ ".ctor", ".ctor", "CompareTo", "Equals", "Equals", "GetHashCode", "Item1", "Item2", "System.Collections.IStructuralComparable.CompareTo", "System.Collections.IStructuralEquatable.Equals", "System.Collections.IStructuralEquatable.GetHashCode", "System.IComparable.CompareTo", "System.ITupleInternal.get_Size", "System.ITupleInternal.GetHashCode", "System.ITupleInternal.Size", "System.ITupleInternal.ToStringEnd", "ToString"}, DirectCast(m1Tuple, TupleTypeSymbol).UnderlyingDefinitionToMemberMap.Values.Select(Function(s) s.Name).OrderBy(Function(s) s).ToArray() ) AssertTestDisplayString(m2Tuple.GetMembers(), "(a2 As System.Int32, b2 As System.Int32).Item1 As System.Int32", "(a2 As System.Int32, b2 As System.Int32).a2 As System.Int32", "(a2 As System.Int32, b2 As System.Int32).Item2 As System.Int32", "(a2 As System.Int32, b2 As System.Int32).b2 As System.Int32", "Sub (a2 As System.Int32, b2 As System.Int32)..ctor()", "Sub (a2 As System.Int32, b2 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)", "Function (a2 As System.Int32, b2 As System.Int32).Equals(obj As System.Object) As System.Boolean", "Function (a2 As System.Int32, b2 As System.Int32).Equals(other As (System.Int32, System.Int32)) As System.Boolean", "Function (a2 As System.Int32, b2 As System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function (a2 As System.Int32, b2 As System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function (a2 As System.Int32, b2 As System.Int32).CompareTo(other As (System.Int32, System.Int32)) As System.Int32", "Function (a2 As System.Int32, b2 As System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function (a2 As System.Int32, b2 As System.Int32).GetHashCode() As System.Int32", "Function (a2 As System.Int32, b2 As System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (a2 As System.Int32, b2 As System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (a2 As System.Int32, b2 As System.Int32).ToString() As System.String", "Function (a2 As System.Int32, b2 As System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function (a2 As System.Int32, b2 As System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property (a2 As System.Int32, b2 As System.Int32).System.ITupleInternal.Size As System.Int32" ) Assert.Equal({ ".ctor", ".ctor", "CompareTo", "Equals", "Equals", "GetHashCode", "Item1", "Item2", "System.Collections.IStructuralComparable.CompareTo", "System.Collections.IStructuralEquatable.Equals", "System.Collections.IStructuralEquatable.GetHashCode", "System.IComparable.CompareTo", "System.ITupleInternal.get_Size", "System.ITupleInternal.GetHashCode", "System.ITupleInternal.Size", "System.ITupleInternal.ToStringEnd", "ToString"}, DirectCast(m2Tuple, TupleTypeSymbol).UnderlyingDefinitionToMemberMap.Values.Select(Function(s) s.Name).OrderBy(Function(s) s).ToArray() ) AssertTestDisplayString(m6Tuple.GetMembers(), "(Item1 As System.Int32, Item2 As System.Int32).Item1 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32).Item2 As System.Int32", "Sub (Item1 As System.Int32, Item2 As System.Int32)..ctor()", "Sub (Item1 As System.Int32, Item2 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)", "Function (Item1 As System.Int32, Item2 As System.Int32).Equals(obj As System.Object) As System.Boolean", "Function (Item1 As System.Int32, Item2 As System.Int32).Equals(other As (System.Int32, System.Int32)) As System.Boolean", "Function (Item1 As System.Int32, Item2 As System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function (Item1 As System.Int32, Item2 As System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32).CompareTo(other As (System.Int32, System.Int32)) As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32).GetHashCode() As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32).ToString() As System.String", "Function (Item1 As System.Int32, Item2 As System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function (Item1 As System.Int32, Item2 As System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property (Item1 As System.Int32, Item2 As System.Int32).System.ITupleInternal.Size As System.Int32" ) Assert.Equal({ ".ctor", ".ctor", "CompareTo", "Equals", "Equals", "GetHashCode", "Item1", "Item2", "System.Collections.IStructuralComparable.CompareTo", "System.Collections.IStructuralEquatable.Equals", "System.Collections.IStructuralEquatable.GetHashCode", "System.IComparable.CompareTo", "System.ITupleInternal.get_Size", "System.ITupleInternal.GetHashCode", "System.ITupleInternal.Size", "System.ITupleInternal.ToStringEnd", "ToString"}, DirectCast(m6Tuple, TupleTypeSymbol).UnderlyingDefinitionToMemberMap.Values.Select(Function(s) s.Name).OrderBy(Function(s) s).ToArray() ) Assert.Equal("", m1Tuple.Name) Assert.Equal(SymbolKind.NamedType, m1Tuple.Kind) Assert.Equal(TypeKind.Struct, m1Tuple.TypeKind) Assert.False(m1Tuple.IsImplicitlyDeclared) Assert.True(m1Tuple.IsTupleType) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32)", m1Tuple.TupleUnderlyingType.ToTestDisplayString()) Assert.Same(m1Tuple, m1Tuple.ConstructedFrom) Assert.Same(m1Tuple, m1Tuple.OriginalDefinition) AssertTupleTypeEquality(m1Tuple) Assert.Same(m1Tuple.TupleUnderlyingType.ContainingSymbol, m1Tuple.ContainingSymbol) Assert.Null(m1Tuple.EnumUnderlyingType) Assert.Equal({ "Item1", "Item2", ".ctor", "Equals", "System.Collections.IStructuralEquatable.Equals", "System.IComparable.CompareTo", "CompareTo", "System.Collections.IStructuralComparable.CompareTo", "GetHashCode", "System.Collections.IStructuralEquatable.GetHashCode", "System.ITupleInternal.GetHashCode", "ToString", "System.ITupleInternal.ToStringEnd", "System.ITupleInternal.get_Size", "System.ITupleInternal.Size"}, m1Tuple.MemberNames.ToArray()) Assert.Equal({ "Item1", "a2", "Item2", "b2", ".ctor", "Equals", "System.Collections.IStructuralEquatable.Equals", "System.IComparable.CompareTo", "CompareTo", "System.Collections.IStructuralComparable.CompareTo", "GetHashCode", "System.Collections.IStructuralEquatable.GetHashCode", "System.ITupleInternal.GetHashCode", "ToString", "System.ITupleInternal.ToStringEnd", "System.ITupleInternal.get_Size", "System.ITupleInternal.Size"}, m2Tuple.MemberNames.ToArray()) Assert.Equal(0, m1Tuple.Arity) Assert.True(m1Tuple.TypeParameters.IsEmpty) Assert.Equal("System.ValueType", m1Tuple.BaseType.ToTestDisplayString()) Assert.False(m1Tuple.HasTypeArgumentsCustomModifiers) Assert.False(m1Tuple.IsComImport) Assert.True(m1Tuple.TypeArgumentsNoUseSiteDiagnostics.IsEmpty) Assert.True(m1Tuple.GetAttributes().IsEmpty) Assert.Equal("(a2 As System.Int32, b2 As System.Int32).Item1 As System.Int32", m2Tuple.GetMembers("Item1").Single().ToTestDisplayString()) Assert.Equal("(a2 As System.Int32, b2 As System.Int32).a2 As System.Int32", m2Tuple.GetMembers("a2").Single().ToTestDisplayString()) Assert.True(m1Tuple.GetTypeMembers().IsEmpty) Assert.True(m1Tuple.GetTypeMembers("C9").IsEmpty) Assert.True(m1Tuple.GetTypeMembers("C9", 0).IsEmpty) Assert.Equal(6, m1Tuple.Interfaces.Length) Assert.True(m1Tuple.GetTypeMembersUnordered().IsEmpty) Assert.Equal(1, m1Tuple.Locations.Length) Assert.Equal("(Integer, Integer)", m1Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.Equal("(a2 As Integer, b2 As Integer)", m2Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) AssertTupleTypeEquality(m2Tuple) AssertTupleTypeEquality(m6Tuple) Assert.False(m1Tuple.Equals(m2Tuple)) Assert.False(m1Tuple.Equals(m6Tuple)) Assert.False(m6Tuple.Equals(m2Tuple)) AssertTupleTypeMembersEquality(m1Tuple, m2Tuple) AssertTupleTypeMembersEquality(m1Tuple, m6Tuple) AssertTupleTypeMembersEquality(m2Tuple, m6Tuple) Dim m1Item1 = DirectCast(m1Tuple.GetMembers()(0), FieldSymbol) Dim m2Item1 = DirectCast(m2Tuple.GetMembers()(0), FieldSymbol) Dim m2a2 = DirectCast(m2Tuple.GetMembers()(1), FieldSymbol) AssertNonvirtualTupleElementField(m1Item1) AssertNonvirtualTupleElementField(m2Item1) AssertVirtualTupleElementField(m2a2) Assert.True(m1Item1.IsTupleField) Assert.Same(m1Item1, m1Item1.OriginalDefinition) Assert.True(m1Item1.Equals(m1Item1)) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m1Item1.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m1Item1.AssociatedSymbol) Assert.Same(m1Tuple, m1Item1.ContainingSymbol) Assert.Same(m1Tuple.TupleUnderlyingType, m1Item1.TupleUnderlyingField.ContainingSymbol) Assert.True(m1Item1.CustomModifiers.IsEmpty) Assert.True(m1Item1.GetAttributes().IsEmpty) Assert.Null(m1Item1.GetUseSiteErrorInfo()) Assert.False(m1Item1.Locations.IsEmpty) Assert.True(m1Item1.DeclaringSyntaxReferences.IsEmpty) Assert.Equal("Item1", m1Item1.TupleUnderlyingField.Name) Assert.True(m1Item1.IsImplicitlyDeclared) Assert.Null(m1Item1.TypeLayoutOffset) Assert.True(m2Item1.IsTupleField) Assert.Same(m2Item1, m2Item1.OriginalDefinition) Assert.True(m2Item1.Equals(m2Item1)) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m2Item1.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m2Item1.AssociatedSymbol) Assert.Same(m2Tuple, m2Item1.ContainingSymbol) Assert.Same(m2Tuple.TupleUnderlyingType, m2Item1.TupleUnderlyingField.ContainingSymbol) Assert.True(m2Item1.CustomModifiers.IsEmpty) Assert.True(m2Item1.GetAttributes().IsEmpty) Assert.Null(m2Item1.GetUseSiteErrorInfo()) Assert.False(m2Item1.Locations.IsEmpty) Assert.Equal("Item1", m2Item1.Name) Assert.Equal("Item1", m2Item1.TupleUnderlyingField.Name) Assert.NotEqual(m2Item1.Locations.Single(), m2Item1.TupleUnderlyingField.Locations.Single()) Assert.Equal("MetadataFile(System.ValueTuple.dll)", m2Item1.TupleUnderlyingField.Locations.Single().ToString()) Assert.Equal("SourceFile(a.vb[589..591))", m2Item1.Locations.Single().ToString()) Assert.True(m2Item1.IsImplicitlyDeclared) Assert.Null(m2Item1.TypeLayoutOffset) Assert.True(m2a2.IsTupleField) Assert.Same(m2a2, m2a2.OriginalDefinition) Assert.True(m2a2.Equals(m2a2)) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m2a2.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m2a2.AssociatedSymbol) Assert.Same(m2Tuple, m2a2.ContainingSymbol) Assert.Same(m2Tuple.TupleUnderlyingType, m2a2.TupleUnderlyingField.ContainingSymbol) Assert.True(m2a2.CustomModifiers.IsEmpty) Assert.True(m2a2.GetAttributes().IsEmpty) Assert.Null(m2a2.GetUseSiteErrorInfo()) Assert.False(m2a2.Locations.IsEmpty) Assert.Equal("a2 As Integer", m2a2.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.Equal("Item1", m2a2.TupleUnderlyingField.Name) Assert.False(m2a2.IsImplicitlyDeclared) Assert.Null(m2a2.TypeLayoutOffset) End Sub Private Sub AssertTupleTypeEquality(tuple As NamedTypeSymbol) Assert.True(tuple.Equals(tuple)) Dim members = tuple.GetMembers() For i = 0 To members.Length - 1 For j = 0 To members.Length - 1 If i <> j Then Assert.NotSame(members(i), members(j)) Assert.False(members(i).Equals(members(j))) Assert.False(members(j).Equals(members(i))) End If Next Next Dim underlyingMembers = tuple.TupleUnderlyingType.GetMembers() For Each m In members Assert.False(underlyingMembers.Any(Function(u) u.Equals(m))) Assert.False(underlyingMembers.Any(Function(u) m.Equals(u))) Next End Sub Private Sub AssertTupleTypeMembersEquality(tuple1 As NamedTypeSymbol, tuple2 As NamedTypeSymbol) Assert.NotSame(tuple1, tuple2) If tuple1.Equals(tuple2) Then Assert.True(tuple2.Equals(tuple1)) Dim members1 = tuple1.GetMembers() Dim members2 = tuple2.GetMembers() Assert.Equal(members1.Length, members2.Length) For i = 0 To members1.Length - 1 Assert.NotSame(members1(i), members2(i)) Assert.True(members1(i).Equals(members2(i))) Assert.True(members2(i).Equals(members1(i))) Assert.Equal(members2(i).GetHashCode(), members1(i).GetHashCode()) If members1(i).Kind = SymbolKind.Method Then Dim parameters1 = DirectCast(members1(i), MethodSymbol).Parameters Dim parameters2 = DirectCast(members2(i), MethodSymbol).Parameters AssertTupleMembersParametersEquality(parameters1, parameters2) Dim typeParameters1 = DirectCast(members1(i), MethodSymbol).TypeParameters Dim typeParameters2 = DirectCast(members2(i), MethodSymbol).TypeParameters Assert.Equal(typeParameters1.Length, typeParameters2.Length) For j = 0 To typeParameters1.Length - 1 Assert.NotSame(typeParameters1(j), typeParameters2(j)) Assert.True(typeParameters1(j).Equals(typeParameters2(j))) Assert.True(typeParameters2(j).Equals(typeParameters1(j))) Assert.Equal(typeParameters2(j).GetHashCode(), typeParameters1(j).GetHashCode()) Next ElseIf members1(i).Kind = SymbolKind.Property Then Dim parameters1 = DirectCast(members1(i), PropertySymbol).Parameters Dim parameters2 = DirectCast(members2(i), PropertySymbol).Parameters AssertTupleMembersParametersEquality(parameters1, parameters2) End If Next For i = 0 To members1.Length - 1 For j = 0 To members2.Length - 1 If i <> j Then Assert.NotSame(members1(i), members2(j)) Assert.False(members1(i).Equals(members2(j))) End If Next Next Else Assert.False(tuple2.Equals(tuple1)) Dim members1 = tuple1.GetMembers() Dim members2 = tuple2.GetMembers() For Each m In members1 Assert.False(members2.Any(Function(u) u.Equals(m))) Assert.False(members2.Any(Function(u) m.Equals(u))) Next End If End Sub Private Sub AssertTupleMembersParametersEquality(parameters1 As ImmutableArray(Of ParameterSymbol), parameters2 As ImmutableArray(Of ParameterSymbol)) Assert.Equal(parameters1.Length, parameters2.Length) For j = 0 To parameters1.Length - 1 Assert.NotSame(parameters1(j), parameters2(j)) Assert.True(parameters1(j).Equals(parameters2(j))) Assert.True(parameters2(j).Equals(parameters1(j))) Assert.Equal(parameters2(j).GetHashCode(), parameters1(j).GetHashCode()) Next End Sub Private Sub AssertVirtualTupleElementField(sym As FieldSymbol) Assert.True(sym.IsTupleField) Assert.True(sym.IsVirtualTupleField) ' it is an element so must have nonnegative index Assert.True(sym.TupleElementIndex >= 0) End Sub Private Sub AssertNonvirtualTupleElementField(sym As FieldSymbol) Assert.True(sym.IsTupleField) Assert.False(sym.IsVirtualTupleField) ' it is an element so must have nonnegative index Assert.True(sym.TupleElementIndex >= 0) ' if it was 8th or after, it would be virtual Assert.True(sym.TupleElementIndex < TupleTypeSymbol.RestPosition - 1) End Sub Private Shared Sub AssertTestDisplayString(symbols As ImmutableArray(Of Symbol), ParamArray baseLine As String()) ' Re-ordering arguments because expected is usually first. AssertEx.Equal(baseLine, symbols.Select(Function(s) s.ToTestDisplayString())) End Sub <Fact> Public Sub DefaultAndFriendlyElementNames_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim v3 = M3() Console.WriteLine(v3.Item1) Console.WriteLine(v3.Item2) Console.WriteLine(v3.Item3) Console.WriteLine(v3.Item4) Console.WriteLine(v3.Item5) Console.WriteLine(v3.Item6) Console.WriteLine(v3.Item7) Console.WriteLine(v3.Item8) Console.WriteLine(v3.Item9) Console.WriteLine(v3.Rest.Item1) Console.WriteLine(v3.Rest.Item2) Console.WriteLine(v3.ToString()) End Sub Shared Function M3() As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) Return (31, 32, 33, 34, 35, 36, 37, 38, 39) End Function End Class </file> </compilation>, options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" 31 32 33 34 35 36 37 38 39 38 39 (31, 32, 33, 34, 35, 36, 37, 38, 39) ") Dim c = comp.GetTypeByMetadataName("C") Dim m3Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M3").ReturnType, NamedTypeSymbol) AssertTestDisplayString(m3Tuple.GetMembers(), "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item1 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item2 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item3 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item4 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item5 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item6 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item7 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Rest As (System.Int32, System.Int32)", "Sub (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor()", "Sub (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32, item3 As System.Int32, item4 As System.Int32, item5 As System.Int32, item6 As System.Int32, item7 As System.Int32, rest As (System.Int32, System.Int32))", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(obj As System.Object) As System.Boolean", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Boolean", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).CompareTo(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).GetHashCode() As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).ToString() As System.String", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.Size As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item8 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item9 As System.Int32" ) Dim m3Item8 = DirectCast(m3Tuple.GetMembers("Item8").Single(), FieldSymbol) AssertVirtualTupleElementField(m3Item8) Assert.True(m3Item8.IsTupleField) Assert.Same(m3Item8, m3Item8.OriginalDefinition) Assert.True(m3Item8.Equals(m3Item8)) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m3Item8.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m3Item8.AssociatedSymbol) Assert.Same(m3Tuple, m3Item8.ContainingSymbol) Assert.NotEqual(m3Tuple.TupleUnderlyingType, m3Item8.TupleUnderlyingField.ContainingSymbol) Assert.True(m3Item8.CustomModifiers.IsEmpty) Assert.True(m3Item8.GetAttributes().IsEmpty) Assert.Null(m3Item8.GetUseSiteErrorInfo()) Assert.False(m3Item8.Locations.IsEmpty) Assert.True(m3Item8.DeclaringSyntaxReferences.IsEmpty) Assert.Equal("Item1", m3Item8.TupleUnderlyingField.Name) Assert.True(m3Item8.IsImplicitlyDeclared) Assert.Null(m3Item8.TypeLayoutOffset) Assert.False(DirectCast(m3Item8, IFieldSymbol).IsExplicitlyNamedTupleElement) Dim m3TupleRestTuple = DirectCast(DirectCast(m3Tuple.GetMembers("Rest").Single(), FieldSymbol).Type, NamedTypeSymbol) AssertTestDisplayString(m3TupleRestTuple.GetMembers(), "(System.Int32, System.Int32).Item1 As System.Int32", "(System.Int32, System.Int32).Item2 As System.Int32", "Sub (System.Int32, System.Int32)..ctor()", "Sub (System.Int32, System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)", "Function (System.Int32, System.Int32).Equals(obj As System.Object) As System.Boolean", "Function (System.Int32, System.Int32).Equals(other As (System.Int32, System.Int32)) As System.Boolean", "Function (System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function (System.Int32, System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function (System.Int32, System.Int32).CompareTo(other As (System.Int32, System.Int32)) As System.Int32", "Function (System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function (System.Int32, System.Int32).GetHashCode() As System.Int32", "Function (System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32).ToString() As System.String", "Function (System.Int32, System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function (System.Int32, System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property (System.Int32, System.Int32).System.ITupleInternal.Size As System.Int32" ) Assert.True(m3TupleRestTuple.IsTupleType) AssertTupleTypeEquality(m3TupleRestTuple) Assert.True(m3TupleRestTuple.Locations.IsEmpty) Assert.True(m3TupleRestTuple.DeclaringSyntaxReferences.IsEmpty) For Each m In m3TupleRestTuple.GetMembers().OfType(Of FieldSymbol)() Assert.True(m.Locations.IsEmpty) Next End Sub <Fact> Public Sub DefaultAndFriendlyElementNames_03() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim v4 = M4() Console.WriteLine(v4.Item1) Console.WriteLine(v4.Item2) Console.WriteLine(v4.Item3) Console.WriteLine(v4.Item4) Console.WriteLine(v4.Item5) Console.WriteLine(v4.Item6) Console.WriteLine(v4.Item7) Console.WriteLine(v4.Item8) Console.WriteLine(v4.Item9) Console.WriteLine(v4.Rest.Item1) Console.WriteLine(v4.Rest.Item2) Console.WriteLine(v4.a4) Console.WriteLine(v4.b4) Console.WriteLine(v4.c4) Console.WriteLine(v4.d4) Console.WriteLine(v4.e4) Console.WriteLine(v4.f4) Console.WriteLine(v4.g4) Console.WriteLine(v4.h4) Console.WriteLine(v4.i4) Console.WriteLine(v4.ToString()) End Sub Shared Function M4() As (a4 As Integer, b4 As Integer, c4 As Integer, d4 As Integer, e4 As Integer, f4 As Integer, g4 As Integer, h4 As Integer, i4 As Integer) Return (41, 42, 43, 44, 45, 46, 47, 48, 49) End Function End Class </file> </compilation>, options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" 41 42 43 44 45 46 47 48 49 48 49 41 42 43 44 45 46 47 48 49 (41, 42, 43, 44, 45, 46, 47, 48, 49) ") Dim c = comp.GetTypeByMetadataName("C") Dim m4Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M4").ReturnType, NamedTypeSymbol) AssertTupleTypeEquality(m4Tuple) AssertTestDisplayString(m4Tuple.GetMembers(), "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item1 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).a4 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item2 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).b4 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item3 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).c4 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item4 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).d4 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item5 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).e4 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item6 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).f4 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item7 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).g4 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Rest As (System.Int32, System.Int32)", "Sub (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32)..ctor()", "Sub (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32, item3 As System.Int32, item4 As System.Int32, item5 As System.Int32, item6 As System.Int32, item7 As System.Int32, rest As (System.Int32, System.Int32))", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Equals(obj As System.Object) As System.Boolean", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Equals(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Boolean", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).CompareTo(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Int32", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).GetHashCode() As System.Int32", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).ToString() As System.String", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.ITupleInternal.Size As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item8 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).h4 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item9 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).i4 As System.Int32" ) Dim m4Item8 = DirectCast(m4Tuple.GetMembers("Item8").Single(), FieldSymbol) AssertVirtualTupleElementField(m4Item8) Assert.True(m4Item8.IsTupleField) Assert.Same(m4Item8, m4Item8.OriginalDefinition) Assert.True(m4Item8.Equals(m4Item8)) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m4Item8.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m4Item8.AssociatedSymbol) Assert.Same(m4Tuple, m4Item8.ContainingSymbol) Assert.NotEqual(m4Tuple.TupleUnderlyingType, m4Item8.TupleUnderlyingField.ContainingSymbol) Assert.True(m4Item8.CustomModifiers.IsEmpty) Assert.True(m4Item8.GetAttributes().IsEmpty) Assert.Null(m4Item8.GetUseSiteErrorInfo()) Assert.False(m4Item8.Locations.IsEmpty) Assert.Equal("Item1", m4Item8.TupleUnderlyingField.Name) Assert.True(m4Item8.IsImplicitlyDeclared) Assert.Null(m4Item8.TypeLayoutOffset) Assert.False(DirectCast(m4Item8, IFieldSymbol).IsExplicitlyNamedTupleElement) Dim m4h4 = DirectCast(m4Tuple.GetMembers("h4").Single(), FieldSymbol) AssertVirtualTupleElementField(m4h4) Assert.True(m4h4.IsTupleField) Assert.Same(m4h4, m4h4.OriginalDefinition) Assert.True(m4h4.Equals(m4h4)) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m4h4.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m4h4.AssociatedSymbol) Assert.Same(m4Tuple, m4h4.ContainingSymbol) Assert.NotEqual(m4Tuple.TupleUnderlyingType, m4h4.TupleUnderlyingField.ContainingSymbol) Assert.True(m4h4.CustomModifiers.IsEmpty) Assert.True(m4h4.GetAttributes().IsEmpty) Assert.Null(m4h4.GetUseSiteErrorInfo()) Assert.False(m4h4.Locations.IsEmpty) Assert.Equal("Item1", m4h4.TupleUnderlyingField.Name) Assert.False(m4h4.IsImplicitlyDeclared) Assert.Null(m4h4.TypeLayoutOffset) Assert.True(DirectCast(m4h4, IFieldSymbol).IsExplicitlyNamedTupleElement) Dim m4TupleRestTuple = DirectCast(DirectCast(m4Tuple.GetMembers("Rest").Single(), FieldSymbol).Type, NamedTypeSymbol) AssertTestDisplayString(m4TupleRestTuple.GetMembers(), "(System.Int32, System.Int32).Item1 As System.Int32", "(System.Int32, System.Int32).Item2 As System.Int32", "Sub (System.Int32, System.Int32)..ctor()", "Sub (System.Int32, System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)", "Function (System.Int32, System.Int32).Equals(obj As System.Object) As System.Boolean", "Function (System.Int32, System.Int32).Equals(other As (System.Int32, System.Int32)) As System.Boolean", "Function (System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function (System.Int32, System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function (System.Int32, System.Int32).CompareTo(other As (System.Int32, System.Int32)) As System.Int32", "Function (System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function (System.Int32, System.Int32).GetHashCode() As System.Int32", "Function (System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32).ToString() As System.String", "Function (System.Int32, System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function (System.Int32, System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property (System.Int32, System.Int32).System.ITupleInternal.Size As System.Int32" ) For Each m In m4TupleRestTuple.GetMembers().OfType(Of FieldSymbol)() Assert.True(m.Locations.IsEmpty) Next End Sub <Fact> Public Sub DefaultAndFriendlyElementNames_04() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim v4 = M4() Console.WriteLine(v4.Rest.a4) Console.WriteLine(v4.Rest.b4) Console.WriteLine(v4.Rest.c4) Console.WriteLine(v4.Rest.d4) Console.WriteLine(v4.Rest.e4) Console.WriteLine(v4.Rest.f4) Console.WriteLine(v4.Rest.g4) Console.WriteLine(v4.Rest.h4) Console.WriteLine(v4.Rest.i4) Console.WriteLine(v4.ToString()) End Sub Shared Function M4() As (a4 As Integer, b4 As Integer, c4 As Integer, d4 As Integer, e4 As Integer, f4 As Integer, g4 As Integer, h4 As Integer, i4 As Integer) Return (41, 42, 43, 44, 45, 46, 47, 48, 49) End Function End Class </file> </compilation>, options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30456: 'a4' is not a member of '(Integer, Integer)'. Console.WriteLine(v4.Rest.a4) ~~~~~~~~~~ BC30456: 'b4' is not a member of '(Integer, Integer)'. Console.WriteLine(v4.Rest.b4) ~~~~~~~~~~ BC30456: 'c4' is not a member of '(Integer, Integer)'. Console.WriteLine(v4.Rest.c4) ~~~~~~~~~~ BC30456: 'd4' is not a member of '(Integer, Integer)'. Console.WriteLine(v4.Rest.d4) ~~~~~~~~~~ BC30456: 'e4' is not a member of '(Integer, Integer)'. Console.WriteLine(v4.Rest.e4) ~~~~~~~~~~ BC30456: 'f4' is not a member of '(Integer, Integer)'. Console.WriteLine(v4.Rest.f4) ~~~~~~~~~~ BC30456: 'g4' is not a member of '(Integer, Integer)'. Console.WriteLine(v4.Rest.g4) ~~~~~~~~~~ BC30456: 'h4' is not a member of '(Integer, Integer)'. Console.WriteLine(v4.Rest.h4) ~~~~~~~~~~ BC30456: 'i4' is not a member of '(Integer, Integer)'. Console.WriteLine(v4.Rest.i4) ~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub DefaultAndFriendlyElementNames_05() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim v5 = M5() Console.WriteLine(v5.Item1) Console.WriteLine(v5.Item2) Console.WriteLine(v5.Item3) Console.WriteLine(v5.Item4) Console.WriteLine(v5.Item5) Console.WriteLine(v5.Item6) Console.WriteLine(v5.Item7) Console.WriteLine(v5.Item8) Console.WriteLine(v5.Item9) Console.WriteLine(v5.Item10) Console.WriteLine(v5.Item11) Console.WriteLine(v5.Item12) Console.WriteLine(v5.Item13) Console.WriteLine(v5.Item14) Console.WriteLine(v5.Item15) Console.WriteLine(v5.Item16) Console.WriteLine(v5.Rest.Item1) Console.WriteLine(v5.Rest.Item2) Console.WriteLine(v5.Rest.Item3) Console.WriteLine(v5.Rest.Item4) Console.WriteLine(v5.Rest.Item5) Console.WriteLine(v5.Rest.Item6) Console.WriteLine(v5.Rest.Item7) Console.WriteLine(v5.Rest.Item8) Console.WriteLine(v5.Rest.Item9) Console.WriteLine(v5.Rest.Rest.Item1) Console.WriteLine(v5.Rest.Rest.Item2) Console.WriteLine(v5.ToString()) End Sub Shared Function M5() As (Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer, Item9 As Integer, Item10 As Integer, Item11 As Integer, Item12 As Integer, Item13 As Integer, Item14 As Integer, Item15 As Integer, Item16 As Integer) Return (501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516) End Function End Class </file> </compilation>, options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 508 509 510 511 512 513 514 515 516 515 516 (501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516) ") Dim c = comp.GetTypeByMetadataName("C") Dim m5Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M5").ReturnType, NamedTypeSymbol) AssertTupleTypeEquality(m5Tuple) AssertTestDisplayString(m5Tuple.GetMembers(), "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item1 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item2 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item3 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item4 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item5 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item6 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item7 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Rest As (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", "Sub (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32)..ctor()", "Sub (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32, item3 As System.Int32, item4 As System.Int32, item5 As System.Int32, item6 As System.Int32, item7 As System.Int32, rest As (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32))", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Equals(obj As System.Object) As System.Boolean", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Equals(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32))) As System.Boolean", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).CompareTo(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32))) As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).GetHashCode() As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).ToString() As System.String", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.ITupleInternal.Size As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item8 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item9 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item10 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item11 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item12 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item13 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item14 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item15 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item16 As System.Int32" ) Dim m5Item8 = DirectCast(m5Tuple.GetMembers("Item8").Single(), FieldSymbol) AssertVirtualTupleElementField(m5Item8) Assert.True(m5Item8.IsTupleField) Assert.Same(m5Item8, m5Item8.OriginalDefinition) Assert.True(m5Item8.Equals(m5Item8)) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32)).Item1 As System.Int32", m5Item8.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m5Item8.AssociatedSymbol) Assert.Same(m5Tuple, m5Item8.ContainingSymbol) Assert.NotEqual(m5Tuple.TupleUnderlyingType, m5Item8.TupleUnderlyingField.ContainingSymbol) Assert.True(m5Item8.CustomModifiers.IsEmpty) Assert.True(m5Item8.GetAttributes().IsEmpty) Assert.Null(m5Item8.GetUseSiteErrorInfo()) Assert.False(m5Item8.Locations.IsEmpty) Assert.Equal("Item8 As Integer", m5Item8.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.Equal("Item1", m5Item8.TupleUnderlyingField.Name) Assert.False(m5Item8.IsImplicitlyDeclared) Assert.True(DirectCast(m5Item8, IFieldSymbol).IsExplicitlyNamedTupleElement) Assert.Null(m5Item8.TypeLayoutOffset) Dim m5TupleRestTuple = DirectCast(DirectCast(m5Tuple.GetMembers("Rest").Single(), FieldSymbol).Type, NamedTypeSymbol) AssertVirtualTupleElementField(m5Item8) AssertTestDisplayString(m5TupleRestTuple.GetMembers(), "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item1 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item2 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item3 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item4 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item5 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item6 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item7 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Rest As (System.Int32, System.Int32)", "Sub (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor()", "Sub (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32, item3 As System.Int32, item4 As System.Int32, item5 As System.Int32, item6 As System.Int32, item7 As System.Int32, rest As (System.Int32, System.Int32))", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(obj As System.Object) As System.Boolean", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Boolean", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).CompareTo(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).GetHashCode() As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).ToString() As System.String", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.Size As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item8 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item9 As System.Int32" ) For Each m In m5TupleRestTuple.GetMembers().OfType(Of FieldSymbol)() If m.Name <> "Rest" Then Assert.True(m.Locations.IsEmpty) Else Assert.Equal("Rest", m.Name) End If Next Dim m5TupleRestTupleRestTuple = DirectCast(DirectCast(m5TupleRestTuple.GetMembers("Rest").Single(), FieldSymbol).Type, NamedTypeSymbol) AssertTupleTypeEquality(m5TupleRestTupleRestTuple) AssertTestDisplayString(m5TupleRestTuple.GetMembers(), "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item1 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item2 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item3 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item4 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item5 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item6 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item7 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Rest As (System.Int32, System.Int32)", "Sub (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor()", "Sub (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32, item3 As System.Int32, item4 As System.Int32, item5 As System.Int32, item6 As System.Int32, item7 As System.Int32, rest As (System.Int32, System.Int32))", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(obj As System.Object) As System.Boolean", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Boolean", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).CompareTo(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).GetHashCode() As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).ToString() As System.String", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.Size As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item8 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item9 As System.Int32" ) For Each m In m5TupleRestTupleRestTuple.GetMembers().OfType(Of FieldSymbol)() Assert.True(m.Locations.IsEmpty) Next End Sub <Fact> Public Sub DefaultAndFriendlyElementNames_06() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim v5 = M5() Console.WriteLine(v5.Rest.Item10) Console.WriteLine(v5.Rest.Item11) Console.WriteLine(v5.Rest.Item12) Console.WriteLine(v5.Rest.Item13) Console.WriteLine(v5.Rest.Item14) Console.WriteLine(v5.Rest.Item15) Console.WriteLine(v5.Rest.Item16) Console.WriteLine(v5.Rest.Rest.Item3) Console.WriteLine(v5.Rest.Rest.Item4) Console.WriteLine(v5.Rest.Rest.Item5) Console.WriteLine(v5.Rest.Rest.Item6) Console.WriteLine(v5.Rest.Rest.Item7) Console.WriteLine(v5.Rest.Rest.Item8) Console.WriteLine(v5.Rest.Rest.Item9) Console.WriteLine(v5.Rest.Rest.Item10) Console.WriteLine(v5.Rest.Rest.Item11) Console.WriteLine(v5.Rest.Rest.Item12) Console.WriteLine(v5.Rest.Rest.Item13) Console.WriteLine(v5.Rest.Rest.Item14) Console.WriteLine(v5.Rest.Rest.Item15) Console.WriteLine(v5.Rest.Rest.Item16) End Sub Shared Function M5() As (Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer, Item9 As Integer, Item10 As Integer, Item11 As Integer, Item12 As Integer, Item13 As Integer, Item14 As Integer, Item15 As Integer, Item16 As Integer) Return (501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516) End Function End Class </file> </compilation>, options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30456: 'Item10' is not a member of '(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'. Console.WriteLine(v5.Rest.Item10) ~~~~~~~~~~~~~~ BC30456: 'Item11' is not a member of '(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'. Console.WriteLine(v5.Rest.Item11) ~~~~~~~~~~~~~~ BC30456: 'Item12' is not a member of '(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'. Console.WriteLine(v5.Rest.Item12) ~~~~~~~~~~~~~~ BC30456: 'Item13' is not a member of '(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'. Console.WriteLine(v5.Rest.Item13) ~~~~~~~~~~~~~~ BC30456: 'Item14' is not a member of '(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'. Console.WriteLine(v5.Rest.Item14) ~~~~~~~~~~~~~~ BC30456: 'Item15' is not a member of '(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'. Console.WriteLine(v5.Rest.Item15) ~~~~~~~~~~~~~~ BC30456: 'Item16' is not a member of '(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'. Console.WriteLine(v5.Rest.Item16) ~~~~~~~~~~~~~~ BC30456: 'Item3' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item3) ~~~~~~~~~~~~~~~~~~ BC30456: 'Item4' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item4) ~~~~~~~~~~~~~~~~~~ BC30456: 'Item5' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item5) ~~~~~~~~~~~~~~~~~~ BC30456: 'Item6' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item6) ~~~~~~~~~~~~~~~~~~ BC30456: 'Item7' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item7) ~~~~~~~~~~~~~~~~~~ BC30456: 'Item8' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item8) ~~~~~~~~~~~~~~~~~~ BC30456: 'Item9' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item9) ~~~~~~~~~~~~~~~~~~ BC30456: 'Item10' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item10) ~~~~~~~~~~~~~~~~~~~ BC30456: 'Item11' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item11) ~~~~~~~~~~~~~~~~~~~ BC30456: 'Item12' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item12) ~~~~~~~~~~~~~~~~~~~ BC30456: 'Item13' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item13) ~~~~~~~~~~~~~~~~~~~ BC30456: 'Item14' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item14) ~~~~~~~~~~~~~~~~~~~ BC30456: 'Item15' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item15) ~~~~~~~~~~~~~~~~~~~ BC30456: 'Item16' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item16) ~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub DefaultAndFriendlyElementNames_07() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() End Sub Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer) Return (701, 702, 703, 704, 705, 706, 707, 708, 709) End Function End Class <%= s_trivial2uple %><%= s_trivial3uple %><%= s_trivialRemainingTuples %> </file> </compilation>, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics( <errors> BC37261: Tuple element name 'Item9' is only allowed at position 9. Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer) ~~~~~ BC37261: Tuple element name 'Item1' is only allowed at position 1. Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer) ~~~~~ BC37261: Tuple element name 'Item2' is only allowed at position 2. Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer) ~~~~~ BC37261: Tuple element name 'Item3' is only allowed at position 3. Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer) ~~~~~ BC37261: Tuple element name 'Item4' is only allowed at position 4. Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer) ~~~~~ BC37261: Tuple element name 'Item5' is only allowed at position 5. Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer) ~~~~~ BC37261: Tuple element name 'Item6' is only allowed at position 6. Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer) ~~~~~ BC37261: Tuple element name 'Item7' is only allowed at position 7. Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer) ~~~~~ BC37261: Tuple element name 'Item8' is only allowed at position 8. Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer) ~~~~~ </errors>) Dim c = comp.GetTypeByMetadataName("C") Dim m7Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M7").ReturnType, NamedTypeSymbol) AssertTupleTypeEquality(m7Tuple) AssertTestDisplayString(m7Tuple.GetMembers(), "Sub (Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32)..ctor()", "Sub (Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32, item3 As System.Int32, item4 As System.Int32, item5 As System.Int32, item6 As System.Int32, item7 As System.Int32, rest As (System.Int32, System.Int32))", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item8 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item7 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item9 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item8 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item1 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item9 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item2 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item1 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item3 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item2 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item4 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item3 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item5 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item4 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item6 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item5 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item7 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item6 As System.Int32" ) End Sub <Fact> Public Sub DefaultAndFriendlyElementNames_08() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() End Sub Shared Function M8() As (a1 As Integer, a2 As Integer, a3 As Integer, a4 As Integer, a5 As Integer, a6 As Integer, a7 As Integer, Item1 As Integer) Return (801, 802, 803, 804, 805, 806, 807, 808) End Function End Class </file> </compilation>, options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37261: Tuple element name 'Item1' is only allowed at position 1. Shared Function M8() As (a1 As Integer, a2 As Integer, a3 As Integer, a4 As Integer, a5 As Integer, a6 As Integer, a7 As Integer, Item1 As Integer) ~~~~~ </errors>) Dim c = comp.GetTypeByMetadataName("C") Dim m8Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M8").ReturnType, NamedTypeSymbol) AssertTupleTypeEquality(m8Tuple) AssertTestDisplayString(m8Tuple.GetMembers(), "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item1 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).a1 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item2 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).a2 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item3 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).a3 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item4 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).a4 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item5 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).a5 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item6 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).a6 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item7 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).a7 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Rest As ValueTuple(Of System.Int32)", "Sub (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32)..ctor()", "Sub (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32, item3 As System.Int32, item4 As System.Int32, item5 As System.Int32, item6 As System.Int32, item7 As System.Int32, rest As ValueTuple(Of System.Int32))", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Equals(obj As System.Object) As System.Boolean", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Equals(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, ValueTuple(Of System.Int32))) As System.Boolean", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).CompareTo(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, ValueTuple(Of System.Int32))) As System.Int32", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).GetHashCode() As System.Int32", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).ToString() As System.String", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.ITupleInternal.Size As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item8 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item1 As System.Int32" ) Dim m8Item8 = DirectCast(m8Tuple.GetMembers("Item8").Single(), FieldSymbol) AssertVirtualTupleElementField(m8Item8) Assert.True(m8Item8.IsTupleField) Assert.Same(m8Item8, m8Item8.OriginalDefinition) Assert.True(m8Item8.Equals(m8Item8)) Assert.Equal("System.ValueTuple(Of System.Int32).Item1 As System.Int32", m8Item8.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m8Item8.AssociatedSymbol) Assert.Same(m8Tuple, m8Item8.ContainingSymbol) Assert.NotEqual(m8Tuple.TupleUnderlyingType, m8Item8.TupleUnderlyingField.ContainingSymbol) Assert.True(m8Item8.CustomModifiers.IsEmpty) Assert.True(m8Item8.GetAttributes().IsEmpty) Assert.Null(m8Item8.GetUseSiteErrorInfo()) Assert.False(m8Item8.Locations.IsEmpty) Assert.Equal("Item1", m8Item8.TupleUnderlyingField.Name) Assert.True(m8Item8.IsImplicitlyDeclared) Assert.False(DirectCast(m8Item8, IFieldSymbol).IsExplicitlyNamedTupleElement) Assert.Null(m8Item8.TypeLayoutOffset) Dim m8Item1 = DirectCast(m8Tuple.GetMembers("Item1").Last(), FieldSymbol) AssertVirtualTupleElementField(m8Item1) Assert.True(m8Item1.IsTupleField) Assert.Same(m8Item1, m8Item1.OriginalDefinition) Assert.True(m8Item1.Equals(m8Item1)) Assert.Equal("System.ValueTuple(Of System.Int32).Item1 As System.Int32", m8Item1.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m8Item1.AssociatedSymbol) Assert.Same(m8Tuple, m8Item1.ContainingSymbol) Assert.NotEqual(m8Tuple.TupleUnderlyingType, m8Item1.TupleUnderlyingField.ContainingSymbol) Assert.True(m8Item1.CustomModifiers.IsEmpty) Assert.True(m8Item1.GetAttributes().IsEmpty) Assert.Null(m8Item1.GetUseSiteErrorInfo()) Assert.False(m8Item1.Locations.IsEmpty) Assert.Equal("Item1", m8Item1.TupleUnderlyingField.Name) Assert.False(m8Item1.IsImplicitlyDeclared) Assert.True(DirectCast(m8Item1, IFieldSymbol).IsExplicitlyNamedTupleElement) Assert.Null(m8Item1.TypeLayoutOffset) Dim m8TupleRestTuple = DirectCast(DirectCast(m8Tuple.GetMembers("Rest").Single(), FieldSymbol).Type, NamedTypeSymbol) AssertTupleTypeEquality(m8TupleRestTuple) AssertTestDisplayString(m8TupleRestTuple.GetMembers(), "ValueTuple(Of System.Int32).Item1 As System.Int32", "Sub ValueTuple(Of System.Int32)..ctor()", "Sub ValueTuple(Of System.Int32)..ctor(item1 As System.Int32)", "Function ValueTuple(Of System.Int32).Equals(obj As System.Object) As System.Boolean", "Function ValueTuple(Of System.Int32).Equals(other As ValueTuple(Of System.Int32)) As System.Boolean", "Function ValueTuple(Of System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function ValueTuple(Of System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function ValueTuple(Of System.Int32).CompareTo(other As ValueTuple(Of System.Int32)) As System.Int32", "Function ValueTuple(Of System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function ValueTuple(Of System.Int32).GetHashCode() As System.Int32", "Function ValueTuple(Of System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function ValueTuple(Of System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function ValueTuple(Of System.Int32).ToString() As System.String", "Function ValueTuple(Of System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function ValueTuple(Of System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property ValueTuple(Of System.Int32).System.ITupleInternal.Size As System.Int32" ) End Sub <Fact> Public Sub DefaultAndFriendlyElementNames_09() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim v1 = (1, 11) Console.WriteLine(v1.Item1) Console.WriteLine(v1.Item2) Dim v2 = (a2:=2, b2:=22) Console.WriteLine(v2.Item1) Console.WriteLine(v2.Item2) Console.WriteLine(v2.a2) Console.WriteLine(v2.b2) Dim v6 = (item1:=6, item2:=66) Console.WriteLine(v6.Item1) Console.WriteLine(v6.Item2) Console.WriteLine(v6.item1) Console.WriteLine(v6.item2) Console.WriteLine(v1.ToString()) Console.WriteLine(v2.ToString()) Console.WriteLine(v6.ToString()) End Sub End Class <%= s_trivial2uple %> </file> </compilation>, options:=TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:=" 1 11 2 22 2 22 6 66 6 66 {1, 11} {2, 22} {6, 66} ") Dim c = comp.GetTypeByMetadataName("C") Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().First() Dim m1Tuple = DirectCast(model.LookupSymbols(node.SpanStart, name:="v1").OfType(Of LocalSymbol)().Single().Type, NamedTypeSymbol) Dim m2Tuple = DirectCast(model.LookupSymbols(node.SpanStart, name:="v2").OfType(Of LocalSymbol)().Single().Type, NamedTypeSymbol) Dim m6Tuple = DirectCast(model.LookupSymbols(node.SpanStart, name:="v6").OfType(Of LocalSymbol)().Single().Type, NamedTypeSymbol) AssertTestDisplayString(m1Tuple.GetMembers(), "Sub (System.Int32, System.Int32)..ctor()", "(System.Int32, System.Int32).Item1 As System.Int32", "(System.Int32, System.Int32).Item2 As System.Int32", "Sub (System.Int32, System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)", "Function (System.Int32, System.Int32).ToString() As System.String" ) AssertTestDisplayString(m2Tuple.GetMembers(), "Sub (a2 As System.Int32, b2 As System.Int32)..ctor()", "(a2 As System.Int32, b2 As System.Int32).Item1 As System.Int32", "(a2 As System.Int32, b2 As System.Int32).a2 As System.Int32", "(a2 As System.Int32, b2 As System.Int32).Item2 As System.Int32", "(a2 As System.Int32, b2 As System.Int32).b2 As System.Int32", "Sub (a2 As System.Int32, b2 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)", "Function (a2 As System.Int32, b2 As System.Int32).ToString() As System.String" ) AssertTestDisplayString(m6Tuple.GetMembers(), "Sub (Item1 As System.Int32, Item2 As System.Int32)..ctor()", "(Item1 As System.Int32, Item2 As System.Int32).Item1 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32).Item2 As System.Int32", "Sub (Item1 As System.Int32, Item2 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)", "Function (Item1 As System.Int32, Item2 As System.Int32).ToString() As System.String" ) Assert.Equal("", m1Tuple.Name) Assert.Equal(SymbolKind.NamedType, m1Tuple.Kind) Assert.Equal(TypeKind.Struct, m1Tuple.TypeKind) Assert.False(m1Tuple.IsImplicitlyDeclared) Assert.True(m1Tuple.IsTupleType) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32)", m1Tuple.TupleUnderlyingType.ToTestDisplayString()) Assert.Same(m1Tuple, m1Tuple.ConstructedFrom) Assert.Same(m1Tuple, m1Tuple.OriginalDefinition) AssertTupleTypeEquality(m1Tuple) Assert.Same(m1Tuple.TupleUnderlyingType.ContainingSymbol, m1Tuple.ContainingSymbol) Assert.Null(m1Tuple.GetUseSiteErrorInfo()) Assert.Null(m1Tuple.EnumUnderlyingType) Assert.Equal({".ctor", "Item1", "Item2", "ToString"}, m1Tuple.MemberNames.ToArray()) Assert.Equal({".ctor", "Item1", "a2", "Item2", "b2", "ToString"}, m2Tuple.MemberNames.ToArray()) Assert.Equal(0, m1Tuple.Arity) Assert.True(m1Tuple.TypeParameters.IsEmpty) Assert.Equal("System.ValueType", m1Tuple.BaseType.ToTestDisplayString()) Assert.False(m1Tuple.HasTypeArgumentsCustomModifiers) Assert.False(m1Tuple.IsComImport) Assert.True(m1Tuple.TypeArgumentsNoUseSiteDiagnostics.IsEmpty) Assert.True(m1Tuple.GetAttributes().IsEmpty) Assert.Equal("(a2 As System.Int32, b2 As System.Int32).Item1 As System.Int32", m2Tuple.GetMembers("Item1").Single().ToTestDisplayString()) Assert.Equal("(a2 As System.Int32, b2 As System.Int32).a2 As System.Int32", m2Tuple.GetMembers("a2").Single().ToTestDisplayString()) Assert.True(m1Tuple.GetTypeMembers().IsEmpty) Assert.True(m1Tuple.GetTypeMembers("C9").IsEmpty) Assert.True(m1Tuple.GetTypeMembers("C9", 0).IsEmpty) Assert.True(m1Tuple.Interfaces.IsEmpty) Assert.True(m1Tuple.GetTypeMembersUnordered().IsEmpty) Assert.Equal(1, m1Tuple.Locations.Length) Assert.Equal("(1, 11)", m1Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.Equal("(a2:=2, b2:=22)", m2Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.Equal("Public Structure ValueTuple(Of T1, T2)", m1Tuple.TupleUnderlyingType.DeclaringSyntaxReferences.Single().GetSyntax().ToString().Substring(0, 38)) AssertTupleTypeEquality(m2Tuple) AssertTupleTypeEquality(m6Tuple) Assert.False(m1Tuple.Equals(m2Tuple)) Assert.False(m1Tuple.Equals(m6Tuple)) Assert.False(m6Tuple.Equals(m2Tuple)) AssertTupleTypeMembersEquality(m1Tuple, m2Tuple) AssertTupleTypeMembersEquality(m1Tuple, m6Tuple) AssertTupleTypeMembersEquality(m2Tuple, m6Tuple) Dim m1Item1 = DirectCast(m1Tuple.GetMembers()(1), FieldSymbol) AssertNonvirtualTupleElementField(m1Item1) Assert.True(m1Item1.IsTupleField) Assert.Same(m1Item1, m1Item1.OriginalDefinition) Assert.True(m1Item1.Equals(m1Item1)) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m1Item1.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m1Item1.AssociatedSymbol) Assert.Same(m1Tuple, m1Item1.ContainingSymbol) Assert.Same(m1Tuple.TupleUnderlyingType, m1Item1.TupleUnderlyingField.ContainingSymbol) Assert.True(m1Item1.CustomModifiers.IsEmpty) Assert.True(m1Item1.GetAttributes().IsEmpty) Assert.Null(m1Item1.GetUseSiteErrorInfo()) Assert.False(m1Item1.Locations.IsEmpty) Assert.True(m1Item1.DeclaringSyntaxReferences.IsEmpty) Assert.Equal("Item1", m1Item1.TupleUnderlyingField.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.True(m1Item1.IsImplicitlyDeclared) Assert.False(DirectCast(m1Item1, IFieldSymbol).IsExplicitlyNamedTupleElement) Assert.Null(m1Item1.TypeLayoutOffset) Dim m2Item1 = DirectCast(m2Tuple.GetMembers()(1), FieldSymbol) AssertNonvirtualTupleElementField(m2Item1) Assert.True(m2Item1.IsTupleField) Assert.Same(m2Item1, m2Item1.OriginalDefinition) Assert.True(m2Item1.Equals(m2Item1)) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m2Item1.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m2Item1.AssociatedSymbol) Assert.Same(m2Tuple, m2Item1.ContainingSymbol) Assert.Same(m2Tuple.TupleUnderlyingType, m2Item1.TupleUnderlyingField.ContainingSymbol) Assert.True(m2Item1.CustomModifiers.IsEmpty) Assert.True(m2Item1.GetAttributes().IsEmpty) Assert.Null(m2Item1.GetUseSiteErrorInfo()) Assert.False(m2Item1.Locations.IsEmpty) Assert.True(m2Item1.DeclaringSyntaxReferences.IsEmpty) Assert.Equal("Item1", m2Item1.TupleUnderlyingField.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.NotEqual(m2Item1.Locations.Single(), m2Item1.TupleUnderlyingField.Locations.Single()) Assert.Equal("SourceFile(a.vb[760..765))", m2Item1.TupleUnderlyingField.Locations.Single().ToString()) Assert.Equal("SourceFile(a.vb[175..177))", m2Item1.Locations.Single().ToString()) Assert.True(m2Item1.IsImplicitlyDeclared) Assert.False(DirectCast(m2Item1, IFieldSymbol).IsExplicitlyNamedTupleElement) Assert.Null(m2Item1.TypeLayoutOffset) Dim m2a2 = DirectCast(m2Tuple.GetMembers()(2), FieldSymbol) AssertVirtualTupleElementField(m2a2) Assert.True(m2a2.IsTupleField) Assert.Same(m2a2, m2a2.OriginalDefinition) Assert.True(m2a2.Equals(m2a2)) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m2a2.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m2a2.AssociatedSymbol) Assert.Same(m2Tuple, m2a2.ContainingSymbol) Assert.Same(m2Tuple.TupleUnderlyingType, m2a2.TupleUnderlyingField.ContainingSymbol) Assert.True(m2a2.CustomModifiers.IsEmpty) Assert.True(m2a2.GetAttributes().IsEmpty) Assert.Null(m2a2.GetUseSiteErrorInfo()) Assert.False(m2a2.Locations.IsEmpty) Assert.Equal("a2", m2a2.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.Equal("Item1", m2a2.TupleUnderlyingField.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.False(m2a2.IsImplicitlyDeclared) Assert.True(DirectCast(m2a2, IFieldSymbol).IsExplicitlyNamedTupleElement) Assert.Null(m2a2.TypeLayoutOffset) Dim m1ToString = m1Tuple.GetMember(Of MethodSymbol)("ToString") Assert.True(m1ToString.IsTupleMethod) Assert.Same(m1ToString, m1ToString.OriginalDefinition) Assert.Same(m1ToString, m1ToString.ConstructedFrom) Assert.Equal("Function System.ValueTuple(Of System.Int32, System.Int32).ToString() As System.String", m1ToString.TupleUnderlyingMethod.ToTestDisplayString()) Assert.Same(m1ToString.TupleUnderlyingMethod, m1ToString.TupleUnderlyingMethod.ConstructedFrom) Assert.Same(m1Tuple, m1ToString.ContainingSymbol) Assert.Same(m1Tuple.TupleUnderlyingType, m1ToString.TupleUnderlyingMethod.ContainingType) Assert.Null(m1ToString.AssociatedSymbol) Assert.True(m1ToString.ExplicitInterfaceImplementations.IsEmpty) Assert.False(m1ToString.ReturnType.SpecialType = SpecialType.System_Void) Assert.True(m1ToString.TypeArguments.IsEmpty) Assert.True(m1ToString.TypeParameters.IsEmpty) Assert.True(m1ToString.GetAttributes().IsEmpty) Assert.Null(m1ToString.GetUseSiteErrorInfo()) Assert.Equal("Function System.ValueType.ToString() As System.String", m1ToString.OverriddenMethod.ToTestDisplayString()) Assert.False(m1ToString.Locations.IsEmpty) Assert.Equal("Public Overrides Function ToString()", m1ToString.DeclaringSyntaxReferences.Single().GetSyntax().ToString().Substring(0, 36)) Assert.Equal(m1ToString.Locations.Single(), m1ToString.TupleUnderlyingMethod.Locations.Single()) End Sub <Fact> Public Sub OverriddenMethodWithDifferentTupleNamesInReturn() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Base Public Overridable Function M1() As (a As Integer, b As Integer) Return (1, 2) End Function Public Overridable Function M2() As (a As Integer, b As Integer) Return (1, 2) End Function Public Overridable Function M3() As (a As Integer, b As Integer)() Return {(1, 2)} End Function Public Overridable Function M4() As (a As Integer, b As Integer)? Return (1, 2) End Function Public Overridable Function M5() As (c As (a As Integer, b As Integer), d As Integer) Return ((1, 2), 3) End Function End Class Public Class Derived Inherits Base Public Overrides Function M1() As (A As Integer, B As Integer) Return (1, 2) End Function Public Overrides Function M2() As (notA As Integer, notB As Integer) Return (1, 2) End Function Public Overrides Function M3() As (notA As Integer, notB As Integer)() Return {(1, 2)} End Function Public Overrides Function M4() As (notA As Integer, notB As Integer)? Return (1, 2) End Function Public Overrides Function M5() As (c As (notA As Integer, notB As Integer), d As Integer) Return ((1, 2), 3) End Function End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC40001: 'Public Overrides Function M2() As (notA As Integer, notB As Integer)' cannot override 'Public Overridable Function M2() As (a As Integer, b As Integer)' because they differ by their tuple element names. Public Overrides Function M2() As (notA As Integer, notB As Integer) ~~ BC40001: 'Public Overrides Function M3() As (notA As Integer, notB As Integer)()' cannot override 'Public Overridable Function M3() As (a As Integer, b As Integer)()' because they differ by their tuple element names. Public Overrides Function M3() As (notA As Integer, notB As Integer)() ~~ BC40001: 'Public Overrides Function M4() As (notA As Integer, notB As Integer)?' cannot override 'Public Overridable Function M4() As (a As Integer, b As Integer)?' because they differ by their tuple element names. Public Overrides Function M4() As (notA As Integer, notB As Integer)? ~~ BC40001: 'Public Overrides Function M5() As (c As (notA As Integer, notB As Integer), d As Integer)' cannot override 'Public Overridable Function M5() As (c As (a As Integer, b As Integer), d As Integer)' because they differ by their tuple element names. Public Overrides Function M5() As (c As (notA As Integer, notB As Integer), d As Integer) ~~ </errors>) Dim m3 = comp.GetMember(Of MethodSymbol)("Derived.M3").ReturnType Assert.Equal("(notA As System.Int32, notB As System.Int32)()", m3.ToTestDisplayString()) Assert.Equal({"System.Collections.Generic.IList(Of (notA As System.Int32, notB As System.Int32))"}, m3.Interfaces.SelectAsArray(Function(t) t.ToTestDisplayString())) End Sub <Fact> Public Sub OverriddenMethodWithNoTupleNamesInReturn() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Base Public Overridable Function M6() As (a As Integer, b As Integer) Return (1, 2) End Function End Class Public Class Derived Inherits Base Public Overrides Function M6() As (Integer, Integer) Return (1, 2) End Function Sub M() Dim result = Me.M6() Dim result2 = MyBase.M6() System.Console.Write(result.a) System.Console.Write(result2.a) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30456: 'a' is not a member of '(Integer, Integer)'. System.Console.Write(result.a) ~~~~~~~~ </errors>) Dim m6 = comp.GetMember(Of MethodSymbol)("Derived.M6").ReturnType Assert.Equal("(System.Int32, System.Int32)", m6.ToTestDisplayString()) Dim tree = comp.SyntaxTrees.First() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim invocation = nodes.OfType(Of InvocationExpressionSyntax)().ElementAt(0) Assert.Equal("Me.M6()", invocation.ToString()) Assert.Equal("Function Derived.M6() As (System.Int32, System.Int32)", model.GetSymbolInfo(invocation).Symbol.ToTestDisplayString()) Dim invocation2 = nodes.OfType(Of InvocationExpressionSyntax)().ElementAt(1) Assert.Equal("MyBase.M6()", invocation2.ToString()) Assert.Equal("Function Base.M6() As (a As System.Int32, b As System.Int32)", model.GetSymbolInfo(invocation2).Symbol.ToTestDisplayString()) End Sub <Fact> Public Sub OverriddenMethodWithDifferentTupleNamesInReturnUsingTypeArg() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Base Public Overridable Function M1(Of T)() As (a As T, b As T) Return (Nothing, Nothing) End Function Public Overridable Function M2(Of T)() As (a As T, b As T) Return (Nothing, Nothing) End Function Public Overridable Function M3(Of T)() As (a As T, b As T)() Return {(Nothing, Nothing)} End Function Public Overridable Function M4(Of T)() As (a As T, b As T)? Return (Nothing, Nothing) End Function Public Overridable Function M5(Of T)() As (c As (a As T, b As T), d As T) Return ((Nothing, Nothing), Nothing) End Function End Class Public Class Derived Inherits Base Public Overrides Function M1(Of T)() As (A As T, B As T) Return (Nothing, Nothing) End Function Public Overrides Function M2(Of T)() As (notA As T, notB As T) Return (Nothing, Nothing) End Function Public Overrides Function M3(Of T)() As (notA As T, notB As T)() Return {(Nothing, Nothing)} End Function Public Overrides Function M4(Of T)() As (notA As T, notB As T)? Return (Nothing, Nothing) End Function Public Overrides Function M5(Of T)() As (c As (notA As T, notB As T), d As T) Return ((Nothing, Nothing), Nothing) End Function End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC40001: 'Public Overrides Function M2(Of T)() As (notA As T, notB As T)' cannot override 'Public Overridable Function M2(Of T)() As (a As T, b As T)' because they differ by their tuple element names. Public Overrides Function M2(Of T)() As (notA As T, notB As T) ~~ BC40001: 'Public Overrides Function M3(Of T)() As (notA As T, notB As T)()' cannot override 'Public Overridable Function M3(Of T)() As (a As T, b As T)()' because they differ by their tuple element names. Public Overrides Function M3(Of T)() As (notA As T, notB As T)() ~~ BC40001: 'Public Overrides Function M4(Of T)() As (notA As T, notB As T)?' cannot override 'Public Overridable Function M4(Of T)() As (a As T, b As T)?' because they differ by their tuple element names. Public Overrides Function M4(Of T)() As (notA As T, notB As T)? ~~ BC40001: 'Public Overrides Function M5(Of T)() As (c As (notA As T, notB As T), d As T)' cannot override 'Public Overridable Function M5(Of T)() As (c As (a As T, b As T), d As T)' because they differ by their tuple element names. Public Overrides Function M5(Of T)() As (c As (notA As T, notB As T), d As T) ~~ </errors>) End Sub <Fact> Public Sub OverriddenMethodWithDifferentTupleNamesInParameters() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Base Public Overridable Sub M1(x As (a As Integer, b As Integer)) End Sub Public Overridable Sub M2(x As (a As Integer, b As Integer)) End Sub Public Overridable Sub M3(x As (a As Integer, b As Integer)()) End Sub Public Overridable Sub M4(x As (a As Integer, b As Integer)?) End Sub Public Overridable Sub M5(x As (c As (a As Integer, b As Integer), d As Integer)) End Sub End Class Public Class Derived Inherits Base Public Overrides Sub M1(x As (A As Integer, B As Integer)) End Sub Public Overrides Sub M2(x As (notA As Integer, notB As Integer)) End Sub Public Overrides Sub M3(x As (notA As Integer, notB As Integer)()) End Sub Public Overrides Sub M4(x As (notA As Integer, notB As Integer)?) End Sub Public Overrides Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer)) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC40001: 'Public Overrides Sub M2(x As (notA As Integer, notB As Integer))' cannot override 'Public Overridable Sub M2(x As (a As Integer, b As Integer))' because they differ by their tuple element names. Public Overrides Sub M2(x As (notA As Integer, notB As Integer)) ~~ BC40001: 'Public Overrides Sub M3(x As (notA As Integer, notB As Integer)())' cannot override 'Public Overridable Sub M3(x As (a As Integer, b As Integer)())' because they differ by their tuple element names. Public Overrides Sub M3(x As (notA As Integer, notB As Integer)()) ~~ BC40001: 'Public Overrides Sub M4(x As (notA As Integer, notB As Integer)?)' cannot override 'Public Overridable Sub M4(x As (a As Integer, b As Integer)?)' because they differ by their tuple element names. Public Overrides Sub M4(x As (notA As Integer, notB As Integer)?) ~~ BC40001: 'Public Overrides Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer))' cannot override 'Public Overridable Sub M5(x As (c As (a As Integer, b As Integer), d As Integer))' because they differ by their tuple element names. Public Overrides Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer)) ~~ </errors>) End Sub <Fact> Public Sub OverriddenMethodWithDifferentTupleNamesInParametersUsingTypeArg() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Base Public Overridable Sub M1(Of T)(x As (a As T, b As T)) End Sub Public Overridable Sub M2(Of T)(x As (a As T, b As T)) End Sub Public Overridable Sub M3(Of T)(x As (a As T, b As T)()) End Sub Public Overridable Sub M4(Of T)(x As (a As T, b As T)?) End Sub Public Overridable Sub M5(Of T)(x As (c As (a As T, b As T), d As T)) End Sub End Class Public Class Derived Inherits Base Public Overrides Sub M1(Of T)(x As (A As T, B As T)) End Sub Public Overrides Sub M2(Of T)(x As (notA As T, notB As T)) End Sub Public Overrides Sub M3(Of T)(x As (notA As T, notB As T)()) End Sub Public Overrides Sub M4(Of T)(x As (notA As T, notB As T)?) End Sub Public Overrides Sub M5(Of T)(x As (c As (notA As T, notB As T), d As T)) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC40001: 'Public Overrides Sub M2(Of T)(x As (notA As T, notB As T))' cannot override 'Public Overridable Sub M2(Of T)(x As (a As T, b As T))' because they differ by their tuple element names. Public Overrides Sub M2(Of T)(x As (notA As T, notB As T)) ~~ BC40001: 'Public Overrides Sub M3(Of T)(x As (notA As T, notB As T)())' cannot override 'Public Overridable Sub M3(Of T)(x As (a As T, b As T)())' because they differ by their tuple element names. Public Overrides Sub M3(Of T)(x As (notA As T, notB As T)()) ~~ BC40001: 'Public Overrides Sub M4(Of T)(x As (notA As T, notB As T)?)' cannot override 'Public Overridable Sub M4(Of T)(x As (a As T, b As T)?)' because they differ by their tuple element names. Public Overrides Sub M4(Of T)(x As (notA As T, notB As T)?) ~~ BC40001: 'Public Overrides Sub M5(Of T)(x As (c As (notA As T, notB As T), d As T))' cannot override 'Public Overridable Sub M5(Of T)(x As (c As (a As T, b As T), d As T))' because they differ by their tuple element names. Public Overrides Sub M5(Of T)(x As (c As (notA As T, notB As T), d As T)) ~~ </errors>) End Sub <Fact> Public Sub HiddenMethodsWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Base Public Overridable Function M1() As (a As Integer, b As Integer) Return (1, 2) End Function Public Overridable Function M2() As (a As Integer, b As Integer) Return (1, 2) End Function Public Overridable Function M3() As (a As Integer, b As Integer)() Return {(1, 2)} End Function Public Overridable Function M4() As (a As Integer, b As Integer)? Return (1, 2) End Function Public Overridable Function M5() As (c As (a As Integer, b As Integer), d As Integer) Return ((1, 2), 3) End Function End Class Public Class Derived Inherits Base Public Function M1() As (A As Integer, B As Integer) Return (1, 2) End Function Public Function M2() As (notA As Integer, notB As Integer) Return (1, 2) End Function Public Function M3() As (notA As Integer, notB As Integer)() Return {(1, 2)} End Function Public Function M4() As (notA As Integer, notB As Integer)? Return (1, 2) End Function Public Function M5() As (c As (notA As Integer, notB As Integer), d As Integer) Return ((1, 2), 3) End Function End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC40005: function 'M1' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'. Public Function M1() As (A As Integer, B As Integer) ~~ BC40005: function 'M2' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'. Public Function M2() As (notA As Integer, notB As Integer) ~~ BC40005: function 'M3' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'. Public Function M3() As (notA As Integer, notB As Integer)() ~~ BC40005: function 'M4' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'. Public Function M4() As (notA As Integer, notB As Integer)? ~~ BC40005: function 'M5' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'. Public Function M5() As (c As (notA As Integer, notB As Integer), d As Integer) ~~ </errors>) End Sub <Fact> Public Sub DuplicateMethodDetectionWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Public Sub M1(x As (A As Integer, B As Integer)) End Sub Public Sub M1(x As (a As Integer, b As Integer)) End Sub Public Sub M2(x As (noIntegerA As Integer, noIntegerB As Integer)) End Sub Public Sub M2(x As (a As Integer, b As Integer)) End Sub Public Sub M3(x As (notA As Integer, notB As Integer)()) End Sub Public Sub M3(x As (a As Integer, b As Integer)()) End Sub Public Sub M4(x As (notA As Integer, notB As Integer)?) End Sub Public Sub M4(x As (a As Integer, b As Integer)?) End Sub Public Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer)) End Sub Public Sub M5(x As (c As (a As Integer, b As Integer), d As Integer)) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30269: 'Public Sub M1(x As (A As Integer, B As Integer))' has multiple definitions with identical signatures. Public Sub M1(x As (A As Integer, B As Integer)) ~~ BC37271: 'Public Sub M2(x As (noIntegerA As Integer, noIntegerB As Integer))' has multiple definitions with identical signatures with different tuple element names, including 'Public Sub M2(x As (a As Integer, b As Integer))'. Public Sub M2(x As (noIntegerA As Integer, noIntegerB As Integer)) ~~ BC37271: 'Public Sub M3(x As (notA As Integer, notB As Integer)())' has multiple definitions with identical signatures with different tuple element names, including 'Public Sub M3(x As (a As Integer, b As Integer)())'. Public Sub M3(x As (notA As Integer, notB As Integer)()) ~~ BC37271: 'Public Sub M4(x As (notA As Integer, notB As Integer)?)' has multiple definitions with identical signatures with different tuple element names, including 'Public Sub M4(x As (a As Integer, b As Integer)?)'. Public Sub M4(x As (notA As Integer, notB As Integer)?) ~~ BC37271: 'Public Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer))' has multiple definitions with identical signatures with different tuple element names, including 'Public Sub M5(x As (c As (a As Integer, b As Integer), d As Integer))'. Public Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer)) ~~ </errors>) End Sub <Fact> Public Sub HiddenMethodParametersWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Base Public Overridable Sub M1(x As (a As Integer, b As Integer)) End Sub Public Overridable Sub M2(x As (a As Integer, b As Integer)) End Sub Public Overridable Sub M3(x As (a As Integer, b As Integer)()) End Sub Public Overridable Sub M4(x As (a As Integer, b As Integer)?) End Sub Public Overridable Sub M5(x As (c As (a As Integer, b As Integer), d As Integer)) End Sub End Class Public Class Derived Inherits Base Public Sub M1(x As (A As Integer, B As Integer)) End Sub Public Sub M2(x As (notA As Integer, notB As Integer)) End Sub Public Sub M3(x As (notA As Integer, notB As Integer)()) End Sub Public Sub M4(x As (notA As Integer, notB As Integer)?) End Sub Public Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer)) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC40005: sub 'M1' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'. Public Sub M1(x As (A As Integer, B As Integer)) ~~ BC40005: sub 'M2' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'. Public Sub M2(x As (notA As Integer, notB As Integer)) ~~ BC40005: sub 'M3' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'. Public Sub M3(x As (notA As Integer, notB As Integer)()) ~~ BC40005: sub 'M4' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'. Public Sub M4(x As (notA As Integer, notB As Integer)?) ~~ BC40005: sub 'M5' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'. Public Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer)) ~~ </errors>) End Sub <Fact> Public Sub ExplicitInterfaceImplementationWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Interface I0 Sub M1(x As (Integer, (Integer, c As Integer))) Sub M2(x As (a As Integer, (b As Integer, c As Integer))) Function MR1() As (Integer, (Integer, c As Integer)) Function MR2() As (a As Integer, (b As Integer, c As Integer)) End Interface Public Class Derived Implements I0 Public Sub M1(x As (notMissing As Integer, (notMissing As Integer, c As Integer))) Implements I0.M1 End Sub Public Sub M2(x As (notA As Integer, (notB As Integer, c As Integer))) Implements I0.M2 End Sub Public Function MR1() As (notMissing As Integer, (notMissing As Integer, c As Integer)) Implements I0.MR1 Return (1, (2, 3)) End Function Public Function MR2() As (notA As Integer, (notB As Integer, c As Integer)) Implements I0.MR2 Return (1, (2, 3)) End Function End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30402: 'M1' cannot implement sub 'M1' on interface 'I0' because the tuple element names in 'Public Sub M1(x As (notMissing As Integer, (notMissing As Integer, c As Integer)))' do not match those in 'Sub M1(x As (Integer, (Integer, c As Integer)))'. Public Sub M1(x As (notMissing As Integer, (notMissing As Integer, c As Integer))) Implements I0.M1 ~~~~~ BC30402: 'M2' cannot implement sub 'M2' on interface 'I0' because the tuple element names in 'Public Sub M2(x As (notA As Integer, (notB As Integer, c As Integer)))' do not match those in 'Sub M2(x As (a As Integer, (b As Integer, c As Integer)))'. Public Sub M2(x As (notA As Integer, (notB As Integer, c As Integer))) Implements I0.M2 ~~~~~ BC30402: 'MR1' cannot implement function 'MR1' on interface 'I0' because the tuple element names in 'Public Function MR1() As (notMissing As Integer, (notMissing As Integer, c As Integer))' do not match those in 'Function MR1() As (Integer, (Integer, c As Integer))'. Public Function MR1() As (notMissing As Integer, (notMissing As Integer, c As Integer)) Implements I0.MR1 ~~~~~~ BC30402: 'MR2' cannot implement function 'MR2' on interface 'I0' because the tuple element names in 'Public Function MR2() As (notA As Integer, (notB As Integer, c As Integer))' do not match those in 'Function MR2() As (a As Integer, (b As Integer, c As Integer))'. Public Function MR2() As (notA As Integer, (notB As Integer, c As Integer)) Implements I0.MR2 ~~~~~~ </errors>) End Sub <Fact> Public Sub InterfaceImplementationOfPropertyWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Interface I0 Property P1 As (a As Integer, b As Integer) Property P2 As (Integer, b As Integer) End Interface Public Class Derived Implements I0 Public Property P1 As (notA As Integer, notB As Integer) Implements I0.P1 Public Property P2 As (notMissing As Integer, b As Integer) Implements I0.P2 End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30402: 'P1' cannot implement property 'P1' on interface 'I0' because the tuple element names in 'Public Property P1 As (notA As Integer, notB As Integer)' do not match those in 'Property P1 As (a As Integer, b As Integer)'. Public Property P1 As (notA As Integer, notB As Integer) Implements I0.P1 ~~~~~ BC30402: 'P2' cannot implement property 'P2' on interface 'I0' because the tuple element names in 'Public Property P2 As (notMissing As Integer, b As Integer)' do not match those in 'Property P2 As (Integer, b As Integer)'. Public Property P2 As (notMissing As Integer, b As Integer) Implements I0.P2 ~~~~~ </errors>) End Sub <Fact> Public Sub InterfaceImplementationOfEventWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Interface I0 Event E1 As Action(Of (a As Integer, b As Integer)) Event E2 As Action(Of (Integer, b As Integer)) End Interface Public Class Derived Implements I0 Public Event E1 As Action(Of (notA As Integer, notB As Integer)) Implements I0.E1 Public Event E2 As Action(Of (notMissing As Integer, notB As Integer)) Implements I0.E2 End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30402: 'E1' cannot implement event 'E1' on interface 'I0' because the tuple element names in 'Public Event E1 As Action(Of (notA As Integer, notB As Integer))' do not match those in 'Event E1 As Action(Of (a As Integer, b As Integer))'. Public Event E1 As Action(Of (notA As Integer, notB As Integer)) Implements I0.E1 ~~~~~ BC30402: 'E2' cannot implement event 'E2' on interface 'I0' because the tuple element names in 'Public Event E2 As Action(Of (notMissing As Integer, notB As Integer))' do not match those in 'Event E2 As Action(Of (Integer, b As Integer))'. Public Event E2 As Action(Of (notMissing As Integer, notB As Integer)) Implements I0.E2 ~~~~~ </errors>) End Sub <Fact> Public Sub InterfaceHidingAnotherInterfaceWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Interface I0 Sub M1(x As (a As Integer, b As Integer)) Sub M2(x As (a As Integer, b As Integer)) Function MR1() As (a As Integer, b As Integer) Function MR2() As (a As Integer, b As Integer) End Interface Public Interface I1 Inherits I0 Sub M1(x As (notA As Integer, b As Integer)) Shadows Sub M2(x As (notA As Integer, b As Integer)) Function MR1() As (notA As Integer, b As Integer) Shadows Function MR2() As (notA As Integer, b As Integer) End Interface </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC40003: sub 'M1' shadows an overloadable member declared in the base interface 'I0'. If you want to overload the base method, this method must be declared 'Overloads'. Sub M1(x As (notA As Integer, b As Integer)) ~~ BC40003: function 'MR1' shadows an overloadable member declared in the base interface 'I0'. If you want to overload the base method, this method must be declared 'Overloads'. Function MR1() As (notA As Integer, b As Integer) ~~~ </errors>) End Sub <Fact> Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Interface I0(Of T) End Interface Public Class C1 Implements I0(Of (a As Integer, b As Integer)), I0(Of (notA As Integer, notB As Integer)) End Class Public Class C2 Implements I0(Of (a As Integer, b As Integer)), I0(Of (a As Integer, b As Integer)) End Class Public Class C3 Implements I0(Of Integer), I0(Of Integer) End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37272: Interface 'I0(Of (notA As Integer, notB As Integer))' can be implemented only once by this type, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))'. Implements I0(Of (a As Integer, b As Integer)), I0(Of (notA As Integer, notB As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31033: Interface 'I0(Of (a As Integer, b As Integer))' can be implemented only once by this type. Implements I0(Of (a As Integer, b As Integer)), I0(Of (a As Integer, b As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31033: Interface 'I0(Of Integer)' can be implemented only once by this type. Implements I0(Of Integer), I0(Of Integer) ~~~~~~~~~~~~~~ </errors>) Dim tree = comp.SyntaxTrees.First() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim c1 = model.GetDeclaredSymbol(nodes.OfType(Of TypeBlockSyntax)().ElementAt(1)) Assert.Equal("C1", c1.Name) Assert.Equal(2, c1.AllInterfaces.Count) Assert.Equal("I0(Of (a As System.Int32, b As System.Int32))", c1.AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I0(Of (notA As System.Int32, notB As System.Int32))", c1.AllInterfaces(1).ToTestDisplayString()) Dim c2 = model.GetDeclaredSymbol(nodes.OfType(Of TypeBlockSyntax)().ElementAt(2)) Assert.Equal("C2", c2.Name) Assert.Equal(1, c2.AllInterfaces.Count) Assert.Equal("I0(Of (a As System.Int32, b As System.Int32))", c2.AllInterfaces(0).ToTestDisplayString()) Dim c3 = model.GetDeclaredSymbol(nodes.OfType(Of TypeBlockSyntax)().ElementAt(3)) Assert.Equal("C3", c3.Name) Assert.Equal(1, c3.AllInterfaces.Count) Assert.Equal("I0(Of System.Int32)", c3.AllInterfaces(0).ToTestDisplayString()) End Sub <Fact> Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames_02() Dim comp = CreateCompilation( <compilation> <file name="a.vb"> public interface I1(Of T) Sub M() end interface public interface I2 Inherits I1(Of (a As Integer, b As Integer)) end interface public interface I3 Inherits I1(Of (c As Integer, d As Integer)) end interface public class C1 Implements I2, I1(Of (c As Integer, d As Integer)) Sub M_1() Implements I1(Of (a As Integer, b As Integer)).M End Sub Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C1 End Sub End class public class C2 Implements I1(Of (c As Integer, d As Integer)), I2 Sub M_1() Implements I1(Of (a As Integer, b As Integer)).M End Sub Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C2 End Sub End class public class C3 Implements I1(Of (a As Integer, b As Integer)), I1(Of (c As Integer, d As Integer)) Sub M_1() Implements I1(Of (a As Integer, b As Integer)).M End Sub Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C3 End Sub End class public class C4 Implements I2, I3 Sub M_1() Implements I1(Of (a As Integer, b As Integer)).M End Sub Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C4 End Sub End class </file> </compilation> ) comp.AssertTheseDiagnostics( <errors> BC37273: Interface 'I1(Of (c As Integer, d As Integer))' can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (a As Integer, b As Integer))' (via 'I2'). Implements I2, I1(Of (c As Integer, d As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30583: 'I1(Of (c As Integer, d As Integer)).M' cannot be implemented more than once. Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37274: Interface 'I1(Of (a As Integer, b As Integer))' (via 'I2') can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (c As Integer, d As Integer))'. Implements I1(Of (c As Integer, d As Integer)), I2 ~~ BC30583: 'I1(Of (c As Integer, d As Integer)).M' cannot be implemented more than once. Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37272: Interface 'I1(Of (c As Integer, d As Integer))' can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (a As Integer, b As Integer))'. Implements I1(Of (a As Integer, b As Integer)), I1(Of (c As Integer, d As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30583: 'I1(Of (c As Integer, d As Integer)).M' cannot be implemented more than once. Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37275: Interface 'I1(Of (c As Integer, d As Integer))' (via 'I3') can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (a As Integer, b As Integer))' (via 'I2'). Implements I2, I3 ~~ BC30583: 'I1(Of (c As Integer, d As Integer)).M' cannot be implemented more than once. Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) Dim c1 As INamedTypeSymbol = comp.GetTypeByMetadataName("C1") Dim c1Interfaces = c1.Interfaces Dim c1AllInterfaces = c1.AllInterfaces Assert.Equal(2, c1Interfaces.Length) Assert.Equal(3, c1AllInterfaces.Length) Assert.Equal("I2", c1Interfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c1Interfaces(1).ToTestDisplayString()) Assert.Equal("I2", c1AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c1AllInterfaces(1).ToTestDisplayString()) Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c1AllInterfaces(2).ToTestDisplayString()) DuplicateInterfaceDetectionWithDifferentTupleNames_02_AssertExplicitInterfaceImplementations(c1) Dim c2 As INamedTypeSymbol = comp.GetTypeByMetadataName("C2") Dim c2Interfaces = c2.Interfaces Dim c2AllInterfaces = c2.AllInterfaces Assert.Equal(2, c2Interfaces.Length) Assert.Equal(3, c2AllInterfaces.Length) Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c2Interfaces(0).ToTestDisplayString()) Assert.Equal("I2", c2Interfaces(1).ToTestDisplayString()) Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c2AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I2", c2AllInterfaces(1).ToTestDisplayString()) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c2AllInterfaces(2).ToTestDisplayString()) DuplicateInterfaceDetectionWithDifferentTupleNames_02_AssertExplicitInterfaceImplementations(c2) Dim c3 As INamedTypeSymbol = comp.GetTypeByMetadataName("C3") Dim c3Interfaces = c3.Interfaces Dim c3AllInterfaces = c3.AllInterfaces Assert.Equal(2, c3Interfaces.Length) Assert.Equal(2, c3AllInterfaces.Length) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c3Interfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c3Interfaces(1).ToTestDisplayString()) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c3AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c3AllInterfaces(1).ToTestDisplayString()) DuplicateInterfaceDetectionWithDifferentTupleNames_02_AssertExplicitInterfaceImplementations(c3) Dim c4 As INamedTypeSymbol = comp.GetTypeByMetadataName("C4") Dim c4Interfaces = c4.Interfaces Dim c4AllInterfaces = c4.AllInterfaces Assert.Equal(2, c4Interfaces.Length) Assert.Equal(4, c4AllInterfaces.Length) Assert.Equal("I2", c4Interfaces(0).ToTestDisplayString()) Assert.Equal("I3", c4Interfaces(1).ToTestDisplayString()) Assert.Equal("I2", c4AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c4AllInterfaces(1).ToTestDisplayString()) Assert.Equal("I3", c4AllInterfaces(2).ToTestDisplayString()) Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c4AllInterfaces(3).ToTestDisplayString()) DuplicateInterfaceDetectionWithDifferentTupleNames_02_AssertExplicitInterfaceImplementations(c4) End Sub Private Shared Sub DuplicateInterfaceDetectionWithDifferentTupleNames_02_AssertExplicitInterfaceImplementations(c As INamedTypeSymbol) Dim cMabImplementations = DirectCast(DirectCast(c, TypeSymbol).GetMember("M_1"), IMethodSymbol).ExplicitInterfaceImplementations Assert.Equal(1, cMabImplementations.Length) Assert.Equal("Sub I1(Of (a As System.Int32, b As System.Int32)).M()", cMabImplementations(0).ToTestDisplayString()) Dim cMcdImplementations = DirectCast(DirectCast(c, TypeSymbol).GetMember("M_2"), IMethodSymbol).ExplicitInterfaceImplementations Assert.Equal(1, cMcdImplementations.Length) Assert.Equal("Sub I1(Of (c As System.Int32, d As System.Int32)).M()", cMcdImplementations(0).ToTestDisplayString()) End Sub <Fact> Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames_03() Dim comp = CreateCompilation( <compilation> <file name="a.vb"> public interface I1(Of T) Sub M() end interface public class C1 Implements I1(Of (a As Integer, b As Integer)) Sub M() Implements I1(Of (a As Integer, b As Integer)).M System.Console.WriteLine("C1.M") End Sub End class public class C2 Inherits C1 Implements I1(Of (c As Integer, d As Integer)) Overloads Sub M() Implements I1(Of (c As Integer, d As Integer)).M System.Console.WriteLine("C2.M") End Sub Shared Sub Main() Dim x As C1 = new C2() Dim y As I1(Of (a As Integer, b As Integer)) = x y.M() End Sub End class </file> </compilation>, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics() Dim validate As Action(Of ModuleSymbol) = Sub(m) Dim isMetadata As Boolean = TypeOf m Is PEModuleSymbol Dim c1 As INamedTypeSymbol = m.GlobalNamespace.GetTypeMember("C1") Dim c1Interfaces = c1.Interfaces Dim c1AllInterfaces = c1.AllInterfaces Assert.Equal(1, c1Interfaces.Length) Assert.Equal(1, c1AllInterfaces.Length) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c1Interfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c1AllInterfaces(0).ToTestDisplayString()) Dim c2 As INamedTypeSymbol = m.GlobalNamespace.GetTypeMember("C2") Dim c2Interfaces = c2.Interfaces Dim c2AllInterfaces = c2.AllInterfaces Assert.Equal(1, c2Interfaces.Length) Assert.Equal(2, c2AllInterfaces.Length) Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c2Interfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c2AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c2AllInterfaces(1).ToTestDisplayString()) Dim m2 = DirectCast(DirectCast(c2, TypeSymbol).GetMember("M"), IMethodSymbol) Dim m2Implementations = m2.ExplicitInterfaceImplementations Assert.Equal(1, m2Implementations.Length) Assert.Equal(If(isMetadata, "Sub I1(Of (System.Int32, System.Int32)).M()", "Sub I1(Of (c As System.Int32, d As System.Int32)).M()"), m2Implementations(0).ToTestDisplayString()) Assert.Same(m2, c2.FindImplementationForInterfaceMember(DirectCast(c2Interfaces(0), TypeSymbol).GetMember("M"))) Assert.Same(m2, c2.FindImplementationForInterfaceMember(DirectCast(c1Interfaces(0), TypeSymbol).GetMember("M"))) End Sub CompileAndVerify(comp, sourceSymbolValidator:=validate, symbolValidator:=validate, expectedOutput:="C2.M") End Sub <Fact> Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames_04() Dim csSource = " public interface I1<T> { void M(); } public class C1 : I1<(int a, int b)> { public void M() => System.Console.WriteLine(""C1.M""); } public class C2 : C1, I1<(int c, int d)> { new public void M() => System.Console.WriteLine(""C2.M""); } " Dim csComp = CreateCSharpCompilation(csSource, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedAssemblies:=TargetFrameworkUtil.GetReferences(TargetFramework.StandardAndVBRuntime)) csComp.VerifyDiagnostics() Dim comp = CreateCompilation( <compilation> <file name="a.vb"> public class C3 Shared Sub Main() Dim x As C1 = new C2() Dim y As I1(Of (a As Integer, b As Integer)) = x y.M() End Sub End class </file> </compilation>, options:=TestOptions.DebugExe, references:={csComp.EmitToImageReference()}) comp.AssertTheseDiagnostics() CompileAndVerify(comp, expectedOutput:="C2.M") Dim c1 As INamedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C1") Dim c1Interfaces = c1.Interfaces Dim c1AllInterfaces = c1.AllInterfaces Assert.Equal(1, c1Interfaces.Length) Assert.Equal(1, c1AllInterfaces.Length) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c1Interfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c1AllInterfaces(0).ToTestDisplayString()) Dim c2 As INamedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C2") Dim c2Interfaces = c2.Interfaces Dim c2AllInterfaces = c2.AllInterfaces Assert.Equal(1, c2Interfaces.Length) Assert.Equal(2, c2AllInterfaces.Length) Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c2Interfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c2AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c2AllInterfaces(1).ToTestDisplayString()) Dim m2 = DirectCast(DirectCast(c2, TypeSymbol).GetMember("M"), IMethodSymbol) Dim m2Implementations = m2.ExplicitInterfaceImplementations Assert.Equal(0, m2Implementations.Length) Assert.Same(m2, c2.FindImplementationForInterfaceMember(DirectCast(c2Interfaces(0), TypeSymbol).GetMember("M"))) Assert.Same(m2, c2.FindImplementationForInterfaceMember(DirectCast(c1Interfaces(0), TypeSymbol).GetMember("M"))) End Sub <Fact> Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames_05() Dim comp = CreateCompilation( <compilation> <file name="a.vb"> public interface I1(Of T) Sub M() end interface public interface I2(Of I2T) Inherits I1(Of (a As I2T, b As I2T)) end interface public interface I3(Of I3T) Inherits I1(Of (c As I3T, d As I3T)) end interface public class C1(Of T) Implements I2(Of T), I1(Of (c As T, d As T)) Sub M_1() Implements I1(Of (a As T, b As T)).M End Sub Sub M_2() Implements I1(Of (c As T, d As T)).M ' C1 End Sub End class public class C2(Of T) Implements I1(Of (c As T, d As T)), I2(Of T) Sub M_1() Implements I1(Of (a As T, b As T)).M End Sub Sub M_2() Implements I1(Of (c As T, d As T)).M ' C2 End Sub End class public class C3(Of T) Implements I1(Of (a As T, b As T)), I1(Of (c As T, d As T)) Sub M_1() Implements I1(Of (a As T, b As T)).M End Sub Sub M_2() Implements I1(Of (c As T, d As T)).M ' C3 End Sub End class public class C4(Of T) Implements I2(Of T), I3(Of T) Sub M_1() Implements I1(Of (a As T, b As T)).M End Sub Sub M_2() Implements I1(Of (c As T, d As T)).M ' C4 End Sub End class </file> </compilation> ) comp.AssertTheseDiagnostics( <errors> BC37273: Interface 'I1(Of (c As T, d As T))' can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (a As T, b As T))' (via 'I2(Of T)'). Implements I2(Of T), I1(Of (c As T, d As T)) ~~~~~~~~~~~~~~~~~~~~~~~ BC30583: 'I1(Of (c As T, d As T)).M' cannot be implemented more than once. Sub M_2() Implements I1(Of (c As T, d As T)).M ' C1 ~~~~~~~~~~~~~~~~~~~~~~~~~ BC37274: Interface 'I1(Of (a As T, b As T))' (via 'I2(Of T)') can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (c As T, d As T))'. Implements I1(Of (c As T, d As T)), I2(Of T) ~~~~~~~~ BC30583: 'I1(Of (c As T, d As T)).M' cannot be implemented more than once. Sub M_2() Implements I1(Of (c As T, d As T)).M ' C2 ~~~~~~~~~~~~~~~~~~~~~~~~~ BC37272: Interface 'I1(Of (c As T, d As T))' can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (a As T, b As T))'. Implements I1(Of (a As T, b As T)), I1(Of (c As T, d As T)) ~~~~~~~~~~~~~~~~~~~~~~~ BC30583: 'I1(Of (c As T, d As T)).M' cannot be implemented more than once. Sub M_2() Implements I1(Of (c As T, d As T)).M ' C3 ~~~~~~~~~~~~~~~~~~~~~~~~~ BC37275: Interface 'I1(Of (c As T, d As T))' (via 'I3(Of T)') can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (a As T, b As T))' (via 'I2(Of T)'). Implements I2(Of T), I3(Of T) ~~~~~~~~ BC30583: 'I1(Of (c As T, d As T)).M' cannot be implemented more than once. Sub M_2() Implements I1(Of (c As T, d As T)).M ' C4 ~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) Dim c1 As INamedTypeSymbol = comp.GetTypeByMetadataName("C1`1") Dim c1Interfaces = c1.Interfaces Dim c1AllInterfaces = c1.AllInterfaces Assert.Equal(2, c1Interfaces.Length) Assert.Equal(3, c1AllInterfaces.Length) Assert.Equal("I2(Of T)", c1Interfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (c As T, d As T))", c1Interfaces(1).ToTestDisplayString()) Assert.Equal("I2(Of T)", c1AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (a As T, b As T))", c1AllInterfaces(1).ToTestDisplayString()) Assert.Equal("I1(Of (c As T, d As T))", c1AllInterfaces(2).ToTestDisplayString()) DuplicateInterfaceDetectionWithDifferentTupleNames_05_AssertExplicitInterfaceImplementations(c1) Dim c2 As INamedTypeSymbol = comp.GetTypeByMetadataName("C2`1") Dim c2Interfaces = c2.Interfaces Dim c2AllInterfaces = c2.AllInterfaces Assert.Equal(2, c2Interfaces.Length) Assert.Equal(3, c2AllInterfaces.Length) Assert.Equal("I1(Of (c As T, d As T))", c2Interfaces(0).ToTestDisplayString()) Assert.Equal("I2(Of T)", c2Interfaces(1).ToTestDisplayString()) Assert.Equal("I1(Of (c As T, d As T))", c2AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I2(Of T)", c2AllInterfaces(1).ToTestDisplayString()) Assert.Equal("I1(Of (a As T, b As T))", c2AllInterfaces(2).ToTestDisplayString()) DuplicateInterfaceDetectionWithDifferentTupleNames_05_AssertExplicitInterfaceImplementations(c2) Dim c3 As INamedTypeSymbol = comp.GetTypeByMetadataName("C3`1") Dim c3Interfaces = c3.Interfaces Dim c3AllInterfaces = c3.AllInterfaces Assert.Equal(2, c3Interfaces.Length) Assert.Equal(2, c3AllInterfaces.Length) Assert.Equal("I1(Of (a As T, b As T))", c3Interfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (c As T, d As T))", c3Interfaces(1).ToTestDisplayString()) Assert.Equal("I1(Of (a As T, b As T))", c3AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (c As T, d As T))", c3AllInterfaces(1).ToTestDisplayString()) DuplicateInterfaceDetectionWithDifferentTupleNames_05_AssertExplicitInterfaceImplementations(c3) Dim c4 As INamedTypeSymbol = comp.GetTypeByMetadataName("C4`1") Dim c4Interfaces = c4.Interfaces Dim c4AllInterfaces = c4.AllInterfaces Assert.Equal(2, c4Interfaces.Length) Assert.Equal(4, c4AllInterfaces.Length) Assert.Equal("I2(Of T)", c4Interfaces(0).ToTestDisplayString()) Assert.Equal("I3(Of T)", c4Interfaces(1).ToTestDisplayString()) Assert.Equal("I2(Of T)", c4AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (a As T, b As T))", c4AllInterfaces(1).ToTestDisplayString()) Assert.Equal("I3(Of T)", c4AllInterfaces(2).ToTestDisplayString()) Assert.Equal("I1(Of (c As T, d As T))", c4AllInterfaces(3).ToTestDisplayString()) DuplicateInterfaceDetectionWithDifferentTupleNames_05_AssertExplicitInterfaceImplementations(c4) End Sub Private Shared Sub DuplicateInterfaceDetectionWithDifferentTupleNames_05_AssertExplicitInterfaceImplementations(c As INamedTypeSymbol) Dim cMabImplementations = DirectCast(DirectCast(c, TypeSymbol).GetMember("M_1"), IMethodSymbol).ExplicitInterfaceImplementations Assert.Equal(1, cMabImplementations.Length) Assert.Equal("Sub I1(Of (a As T, b As T)).M()", cMabImplementations(0).ToTestDisplayString()) Dim cMcdImplementations = DirectCast(DirectCast(c, TypeSymbol).GetMember("M_2"), IMethodSymbol).ExplicitInterfaceImplementations Assert.Equal(1, cMcdImplementations.Length) Assert.Equal("Sub I1(Of (c As T, d As T)).M()", cMcdImplementations(0).ToTestDisplayString()) End Sub <Fact> Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames_06() Dim comp = CreateCompilation( <compilation> <file name="a.vb"> public interface I1(Of T) Sub M() end interface public class C3(Of T, U) Implements I1(Of (a As T, b As T)), I1(Of (c As U, d As U)) Sub M_1() Implements I1(Of (a As T, b As T)).M End Sub Sub M_2() Implements I1(Of (c As U, d As U)).M End Sub End class </file> </compilation> ) comp.AssertTheseDiagnostics( <errors> BC32072: Cannot implement interface 'I1(Of (c As U, d As U))' because its implementation could conflict with the implementation of another implemented interface 'I1(Of (a As T, b As T))' for some type arguments. Implements I1(Of (a As T, b As T)), I1(Of (c As U, d As U)) ~~~~~~~~~~~~~~~~~~~~~~~ </errors>) Dim c3 As INamedTypeSymbol = comp.GetTypeByMetadataName("C3`2") Dim c3Interfaces = c3.Interfaces Dim c3AllInterfaces = c3.AllInterfaces Assert.Equal(2, c3Interfaces.Length) Assert.Equal(2, c3AllInterfaces.Length) Assert.Equal("I1(Of (a As T, b As T))", c3Interfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (c As U, d As U))", c3Interfaces(1).ToTestDisplayString()) Assert.Equal("I1(Of (a As T, b As T))", c3AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (c As U, d As U))", c3AllInterfaces(1).ToTestDisplayString()) Dim cMabImplementations = DirectCast(DirectCast(c3, TypeSymbol).GetMember("M_1"), IMethodSymbol).ExplicitInterfaceImplementations Assert.Equal(1, cMabImplementations.Length) Assert.Equal("Sub I1(Of (a As T, b As T)).M()", cMabImplementations(0).ToTestDisplayString()) Dim cMcdImplementations = DirectCast(DirectCast(c3, TypeSymbol).GetMember("M_2"), IMethodSymbol).ExplicitInterfaceImplementations Assert.Equal(1, cMcdImplementations.Length) Assert.Equal("Sub I1(Of (c As U, d As U)).M()", cMcdImplementations(0).ToTestDisplayString()) End Sub <Fact> Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames_07() Dim comp = CreateCompilation( <compilation> <file name="a.vb"> public interface I1(Of T) Sub M() end interface public class C3 Implements I1(Of (a As Integer, b As Integer)) Sub M() Implements I1(Of (c As Integer, d As Integer)).M End Sub End class public class C4 Implements I1(Of (c As Integer, d As Integer)) Sub M() Implements I1(Of (c As Integer, d As Integer)).M End Sub End class </file> </compilation> ) comp.AssertTheseDiagnostics( <errors> BC31035: Interface 'I1(Of (c As Integer, d As Integer))' is not implemented by this class. Sub M() Implements I1(Of (c As Integer, d As Integer)).M ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) Dim c3 As INamedTypeSymbol = comp.GetTypeByMetadataName("C3") Dim c3Interfaces = c3.Interfaces Dim c3AllInterfaces = c3.AllInterfaces Assert.Equal(1, c3Interfaces.Length) Assert.Equal(1, c3AllInterfaces.Length) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c3Interfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c3AllInterfaces(0).ToTestDisplayString()) Dim mImplementations = DirectCast(DirectCast(c3, TypeSymbol).GetMember("M"), IMethodSymbol).ExplicitInterfaceImplementations Assert.Equal(1, mImplementations.Length) Assert.Equal("Sub I1(Of (c As System.Int32, d As System.Int32)).M()", mImplementations(0).ToTestDisplayString()) Assert.Equal("Sub C3.M()", c3.FindImplementationForInterfaceMember(DirectCast(c3Interfaces(0), TypeSymbol).GetMember("M")).ToTestDisplayString()) Assert.Equal("Sub C3.M()", c3.FindImplementationForInterfaceMember(comp.GetTypeByMetadataName("C4").InterfacesNoUseSiteDiagnostics()(0).GetMember("M")).ToTestDisplayString()) End Sub <Fact> Public Sub AccessCheckLooksInsideTuples() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Public Function M() As (C2.C3, Integer) Throw New System.Exception() End Function End Class Public Class C2 Private Class C3 End Class End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30389: 'C2.C3' is not accessible in this context because it is 'Private'. Public Function M() As (C2.C3, Integer) ~~~~~ </errors>) End Sub <Fact> Public Sub AccessCheckLooksInsideTuples2() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Public Function M() As (C2, Integer) Throw New System.Exception() End Function Private Class C2 End Class End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) Dim expectedErrors = <errors><![CDATA[ BC30508: 'M' cannot expose type 'C.C2' in namespace '<Default>' through class 'C'. Public Function M() As (C2, Integer) ~~~~~~~~~~~~~ ]]></errors> comp.AssertTheseDiagnostics(expectedErrors) End Sub <Fact> Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames2() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Interface I0(Of T) End Interface Public Class C2 Implements I0(Of (a As Integer, b As Integer)), I0(Of (a As Integer, b As Integer)) End Class Public Class C3 Implements I0(Of Integer), I0(Of Integer) End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC31033: Interface 'I0(Of (a As Integer, b As Integer))' can be implemented only once by this type. Implements I0(Of (a As Integer, b As Integer)), I0(Of (a As Integer, b As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31033: Interface 'I0(Of Integer)' can be implemented only once by this type. Implements I0(Of Integer), I0(Of Integer) ~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub ImplicitAndExplicitInterfaceImplementationWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Interface I0(Of T) Function Pop() As T Sub Push(x As T) End Interface Public Class C1 Implements I0(Of (a As Integer, b As Integer)) Public Function Pop() As (a As Integer, b As Integer) Implements I0(Of (a As Integer, b As Integer)).Pop Throw New Exception() End Function Public Sub Push(x As (a As Integer, b As Integer)) Implements I0(Of (a As Integer, b As Integer)).Push End Sub End Class Public Class C2 Inherits C1 Implements I0(Of (a As Integer, b As Integer)) Public Overloads Function Pop() As (notA As Integer, notB As Integer) Implements I0(Of (a As Integer, b As Integer)).Pop Throw New Exception() End Function Public Overloads Sub Push(x As (notA As Integer, notB As Integer)) Implements I0(Of (a As Integer, b As Integer)).Push End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30402: 'Pop' cannot implement function 'Pop' on interface 'I0(Of (a As Integer, b As Integer))' because the tuple element names in 'Public Overloads Function Pop() As (notA As Integer, notB As Integer)' do not match those in 'Function Pop() As (a As Integer, b As Integer)'. Public Overloads Function Pop() As (notA As Integer, notB As Integer) Implements I0(Of (a As Integer, b As Integer)).Pop ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30402: 'Push' cannot implement sub 'Push' on interface 'I0(Of (a As Integer, b As Integer))' because the tuple element names in 'Public Overloads Sub Push(x As (notA As Integer, notB As Integer))' do not match those in 'Sub Push(x As (a As Integer, b As Integer))'. Public Overloads Sub Push(x As (notA As Integer, notB As Integer)) Implements I0(Of (a As Integer, b As Integer)).Push ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub PartialMethodsWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Partial Class C1 Private Partial Sub M1(x As (a As Integer, b As Integer)) End Sub Private Partial Sub M2(x As (a As Integer, b As Integer)) End Sub Private Partial Sub M3(x As (a As Integer, b As Integer)) End Sub End Class Public Partial Class C1 Private Sub M1(x As (notA As Integer, notB As Integer)) End Sub Private Sub M2(x As (Integer, Integer)) End Sub Private Sub M3(x As (a As Integer, b As Integer)) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37271: 'Private Sub M1(x As (a As Integer, b As Integer))' has multiple definitions with identical signatures with different tuple element names, including 'Private Sub M1(x As (notA As Integer, notB As Integer))'. Private Partial Sub M1(x As (a As Integer, b As Integer)) ~~ BC37271: 'Private Sub M2(x As (a As Integer, b As Integer))' has multiple definitions with identical signatures with different tuple element names, including 'Private Sub M2(x As (Integer, Integer))'. Private Partial Sub M2(x As (a As Integer, b As Integer)) ~~ </errors>) End Sub <Fact> Public Sub PartialClassWithDifferentTupleNamesInBaseInterfaces() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Interface I0(Of T) End Interface Public Partial Class C Implements I0(Of (a As Integer, b As Integer)) End Class Public Partial Class C Implements I0(Of (notA As Integer, notB As Integer)) End Class Public Partial Class C Implements I0(Of (Integer, Integer)) End Class Public Partial Class D Implements I0(Of (a As Integer, b As Integer)) End Class Public Partial Class D Implements I0(Of (a As Integer, b As Integer)) End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37272: Interface 'I0(Of (notA As Integer, notB As Integer))' can be implemented only once by this type, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))'. Implements I0(Of (notA As Integer, notB As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37272: Interface 'I0(Of (Integer, Integer))' can be implemented only once by this type, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))'. Implements I0(Of (Integer, Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub PartialClassWithDifferentTupleNamesInBaseTypes() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Base(Of T) End Class Public Partial Class C1 Inherits Base(Of (a As Integer, b As Integer)) End Class Public Partial Class C1 Inherits Base(Of (notA As Integer, notB As Integer)) End Class Public Partial Class C2 Inherits Base(Of (a As Integer, b As Integer)) End Class Public Partial Class C2 Inherits Base(Of (Integer, Integer)) End Class Public Partial Class C3 Inherits Base(Of (a As Integer, b As Integer)) End Class Public Partial Class C3 Inherits Base(Of (a As Integer, b As Integer)) End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30928: Base class 'Base(Of (notA As Integer, notB As Integer))' specified for class 'C1' cannot be different from the base class 'Base(Of (a As Integer, b As Integer))' of one of its other partial types. Inherits Base(Of (notA As Integer, notB As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30928: Base class 'Base(Of (Integer, Integer))' specified for class 'C2' cannot be different from the base class 'Base(Of (a As Integer, b As Integer))' of one of its other partial types. Inherits Base(Of (Integer, Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub IndirectInterfaceBasesWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Interface I0(Of T) End Interface Public Interface I1 Inherits I0(Of (a As Integer, b As Integer)) End Interface Public Interface I2 Inherits I0(Of (notA As Integer, notB As Integer)) End Interface Public Interface I3 Inherits I0(Of (a As Integer, b As Integer)) End Interface Public Class C1 Implements I1, I3 End Class Public Class C2 Implements I0(Of (a As Integer, b As Integer)), I0(Of (notA As Integer, notB As Integer)) End Class Public Class C3 Implements I2, I0(Of (a As Integer, b As Integer)) End Class Public Class C4 Implements I0(Of (a As Integer, b As Integer)), I2 End Class Public Class C5 Implements I1, I2 End Class Public Interface I11 Inherits I0(Of (a As Integer, b As Integer)), I0(Of (notA As Integer, notB As Integer)) End Interface Public Interface I12 Inherits I2, I0(Of (a As Integer, b As Integer)) End Interface Public Interface I13 Inherits I0(Of (a As Integer, b As Integer)), I2 End Interface Public Interface I14 Inherits I1, I2 End Interface </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37272: Interface 'I0(Of (notA As Integer, notB As Integer))' can be implemented only once by this type, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))'. Implements I0(Of (a As Integer, b As Integer)), I0(Of (notA As Integer, notB As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37273: Interface 'I0(Of (a As Integer, b As Integer))' can be implemented only once by this type, but already appears with different tuple element names, as 'I0(Of (notA As Integer, notB As Integer))' (via 'I2'). Implements I2, I0(Of (a As Integer, b As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37274: Interface 'I0(Of (notA As Integer, notB As Integer))' (via 'I2') can be implemented only once by this type, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))'. Implements I0(Of (a As Integer, b As Integer)), I2 ~~ BC37275: Interface 'I0(Of (notA As Integer, notB As Integer))' (via 'I2') can be implemented only once by this type, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))' (via 'I1'). Implements I1, I2 ~~ BC37276: Interface 'I0(Of (notA As Integer, notB As Integer))' can be inherited only once by this interface, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))'. Inherits I0(Of (a As Integer, b As Integer)), I0(Of (notA As Integer, notB As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37277: Interface 'I0(Of (a As Integer, b As Integer))' can be inherited only once by this interface, but already appears with different tuple element names, as 'I0(Of (notA As Integer, notB As Integer))' (via 'I2'). Inherits I2, I0(Of (a As Integer, b As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37278: Interface 'I0(Of (notA As Integer, notB As Integer))' (via 'I2') can be inherited only once by this interface, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))'. Inherits I0(Of (a As Integer, b As Integer)), I2 ~~ BC37279: Interface 'I0(Of (notA As Integer, notB As Integer))' (via 'I2') can be inherited only once by this interface, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))' (via 'I1'). Inherits I1, I2 ~~ </errors>) End Sub <Fact> Public Sub InterfaceUnification() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Interface I0(Of T1) End Interface Public Class C1(Of T2) Implements I0(Of Integer), I0(Of T2) End Class Public Class C2(Of T2) Implements I0(Of (Integer, Integer)), I0(Of System.ValueTuple(Of T2, T2)) End Class Public Class C3(Of T2) Implements I0(Of (a As Integer, b As Integer)), I0(Of (T2, T2)) End Class Public Class C4(Of T2) Implements I0(Of (a As Integer, b As Integer)), I0(Of (a As T2, b As T2)) End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC32072: Cannot implement interface 'I0(Of T2)' because its implementation could conflict with the implementation of another implemented interface 'I0(Of Integer)' for some type arguments. Implements I0(Of Integer), I0(Of T2) ~~~~~~~~~ BC32072: Cannot implement interface 'I0(Of (T2, T2))' because its implementation could conflict with the implementation of another implemented interface 'I0(Of (Integer, Integer))' for some type arguments. Implements I0(Of (Integer, Integer)), I0(Of System.ValueTuple(Of T2, T2)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32072: Cannot implement interface 'I0(Of (T2, T2))' because its implementation could conflict with the implementation of another implemented interface 'I0(Of (a As Integer, b As Integer))' for some type arguments. Implements I0(Of (a As Integer, b As Integer)), I0(Of (T2, T2)) ~~~~~~~~~~~~~~~ BC32072: Cannot implement interface 'I0(Of (a As T2, b As T2))' because its implementation could conflict with the implementation of another implemented interface 'I0(Of (a As Integer, b As Integer))' for some type arguments. Implements I0(Of (a As Integer, b As Integer)), I0(Of (a As T2, b As T2)) ~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub InterfaceUnification2() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Public Interface I0(Of T1) End Interface Public Class Derived(Of T) Implements I0(Of Derived(Of (T, T))), I0(Of T) End Class ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> </errors>) ' Didn't run out of memory in trying to substitute T with Derived(Of (T, T)) in a loop End Sub <Fact> Public Sub AmbiguousExtensionMethodWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Public Module M1 <System.Runtime.CompilerServices.Extension()> Public Sub M(self As String, x As (Integer, Integer)) Throw New Exception() End Sub End Module Public Module M2 <System.Runtime.CompilerServices.Extension()> Public Sub M(self As String, x As (a As Integer, b As Integer)) Throw New Exception() End Sub End Module Public Module M3 <System.Runtime.CompilerServices.Extension()> Public Sub M(self As String, x As (c As Integer, d As Integer)) Throw New Exception() End Sub End Module Public Class C Public Sub M(s As String) s.M((1, 1)) s.M((a:=1, b:=1)) s.M((c:=1, d:=1)) End Sub End Class ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30521: Overload resolution failed because no accessible 'M' is most specific for these arguments: Extension method 'Public Sub M(x As (Integer, Integer))' defined in 'M1': Not most specific. Extension method 'Public Sub M(x As (a As Integer, b As Integer))' defined in 'M2': Not most specific. Extension method 'Public Sub M(x As (c As Integer, d As Integer))' defined in 'M3': Not most specific. s.M((1, 1)) ~ BC30521: Overload resolution failed because no accessible 'M' is most specific for these arguments: Extension method 'Public Sub M(x As (Integer, Integer))' defined in 'M1': Not most specific. Extension method 'Public Sub M(x As (a As Integer, b As Integer))' defined in 'M2': Not most specific. Extension method 'Public Sub M(x As (c As Integer, d As Integer))' defined in 'M3': Not most specific. s.M((a:=1, b:=1)) ~ BC30521: Overload resolution failed because no accessible 'M' is most specific for these arguments: Extension method 'Public Sub M(x As (Integer, Integer))' defined in 'M1': Not most specific. Extension method 'Public Sub M(x As (a As Integer, b As Integer))' defined in 'M2': Not most specific. Extension method 'Public Sub M(x As (c As Integer, d As Integer))' defined in 'M3': Not most specific. s.M((c:=1, d:=1)) ~ </errors>) End Sub <Fact> Public Sub InheritFromMetadataWithDifferentNames() Dim il = " .assembly extern mscorlib { } .assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 } .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object { .method public hidebysig newslot virtual instance class [System.ValueTuple]System.ValueTuple`2<int32,int32> M() cil managed { .param [0] .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = {string[2]('a' 'b')} // Code size 13 (0xd) .maxstack 2 .locals init (class [System.ValueTuple]System.ValueTuple`2<int32,int32> V_0) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj instance void class [System.ValueTuple]System.ValueTuple`2<int32,int32>::.ctor(!0, !1) IL_0008: stloc.0 IL_0009: br.s IL_000b IL_000b: ldloc.0 IL_000c: ret } // end of method Base::M .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method Base::.ctor } // end of class Base .class public auto ansi beforefieldinit Base2 extends Base { .method public hidebysig virtual instance class [System.ValueTuple]System.ValueTuple`2<int32,int32> M() cil managed { .param [0] .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = {string[2]('notA' 'notB')} // Code size 13 (0xd) .maxstack 2 .locals init (class [System.ValueTuple]System.ValueTuple`2<int32,int32> V_0) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj instance void class [System.ValueTuple]System.ValueTuple`2<int32,int32>::.ctor(!0, !1) IL_0008: stloc.0 IL_0009: br.s IL_000b IL_000b: ldloc.0 IL_000c: ret } // end of method Base2::M .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void Base::.ctor() IL_0006: nop IL_0007: ret } // end of method Base2::.ctor } // end of class Base2 " Dim compMatching = CreateCompilationWithCustomILSource( <compilation> <file name="a.vb"> Public Class C Inherits Base2 Public Overrides Function M() As (notA As Integer, notB As Integer) Return (1, 2) End Function End Class </file> </compilation>, il, additionalReferences:=s_valueTupleRefs) compMatching.AssertTheseDiagnostics() Dim compDifferent1 = CreateCompilationWithCustomILSource( <compilation> <file name="a.vb"> Public Class C Inherits Base2 Public Overrides Function M() As (a As Integer, b As Integer) Return (1, 2) End Function End Class </file> </compilation>, il, additionalReferences:=s_valueTupleRefs) compDifferent1.AssertTheseDiagnostics( <errors> BC40001: 'Public Overrides Function M() As (a As Integer, b As Integer)' cannot override 'Public Overrides Function M() As (notA As Integer, notB As Integer)' because they differ by their tuple element names. Public Overrides Function M() As (a As Integer, b As Integer) ~ </errors>) Dim compDifferent2 = CreateCompilationWithCustomILSource( <compilation> <file name="a.vb"> Public Class C Inherits Base2 Public Overrides Function M() As (Integer, Integer) Return (1, 2) End Function End Class </file> </compilation>, il, additionalReferences:=s_valueTupleRefs) compDifferent2.AssertTheseDiagnostics( <errors> </errors>) End Sub <Fact> Public Sub TupleNamesInAnonymousTypes() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Public Shared Sub Main() Dim x1 = New With {.Tuple = (a:=1, b:=2) } Dim x2 = New With {.Tuple = (c:=1, 2) } x2 = x1 Console.Write(x1.Tuple.a) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics() Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().First() Dim x1 = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x1 As <anonymous type: Tuple As (a As System.Int32, b As System.Int32)>", model.GetDeclaredSymbol(x1).ToTestDisplayString()) Dim x2 = nodes.OfType(Of VariableDeclaratorSyntax)().Skip(1).First().Names(0) Assert.Equal("x2 As <anonymous type: Tuple As (c As System.Int32, System.Int32)>", model.GetDeclaredSymbol(x2).ToTestDisplayString()) End Sub <Fact> Public Sub OverriddenPropertyWithDifferentTupleNamesInReturn() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Base Public Overridable Property P1 As (a As Integer, b As Integer) Public Overridable Property P2 As (a As Integer, b As Integer) Public Overridable Property P3 As (a As Integer, b As Integer)() Public Overridable Property P4 As (a As Integer, b As Integer)? Public Overridable Property P5 As (c As (a As Integer, b As Integer), d As Integer) End Class Public Class Derived Inherits Base Public Overrides Property P1 As (a As Integer, b As Integer) Public Overrides Property P2 As (notA As Integer, notB As Integer) Public Overrides Property P3 As (notA As Integer, notB As Integer)() Public Overrides Property P4 As (notA As Integer, notB As Integer)? Public Overrides Property P5 As (c As (notA As Integer, notB As Integer), d As Integer) End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC40001: 'Public Overrides Property P2 As (notA As Integer, notB As Integer)' cannot override 'Public Overridable Property P2 As (a As Integer, b As Integer)' because they differ by their tuple element names. Public Overrides Property P2 As (notA As Integer, notB As Integer) ~~ BC40001: 'Public Overrides Property P3 As (notA As Integer, notB As Integer)()' cannot override 'Public Overridable Property P3 As (a As Integer, b As Integer)()' because they differ by their tuple element names. Public Overrides Property P3 As (notA As Integer, notB As Integer)() ~~ BC40001: 'Public Overrides Property P4 As (notA As Integer, notB As Integer)?' cannot override 'Public Overridable Property P4 As (a As Integer, b As Integer)?' because they differ by their tuple element names. Public Overrides Property P4 As (notA As Integer, notB As Integer)? ~~ BC40001: 'Public Overrides Property P5 As (c As (notA As Integer, notB As Integer), d As Integer)' cannot override 'Public Overridable Property P5 As (c As (a As Integer, b As Integer), d As Integer)' because they differ by their tuple element names. Public Overrides Property P5 As (c As (notA As Integer, notB As Integer), d As Integer) ~~ </errors>) End Sub <Fact> Public Sub OverriddenPropertyWithNoTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Base Public Overridable Property P6 As (a As Integer, b As Integer) End Class Public Class Derived Inherits Base Public Overrides Property P6 As (Integer, Integer) Sub M() Dim result = Me.P6 Dim result2 = MyBase.P6 System.Console.Write(result.a) System.Console.Write(result2.a) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> </errors>) Dim tree = comp.SyntaxTrees.First() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim propertyAccess = nodes.OfType(Of MemberAccessExpressionSyntax)().ElementAt(0) Assert.Equal("Me.P6", propertyAccess.ToString()) Assert.Equal("Property Derived.P6 As (System.Int32, System.Int32)", model.GetSymbolInfo(propertyAccess).Symbol.ToTestDisplayString()) Dim propertyAccess2 = nodes.OfType(Of MemberAccessExpressionSyntax)().ElementAt(1) Assert.Equal("MyBase.P6", propertyAccess2.ToString()) Assert.Equal("Property Base.P6 As (a As System.Int32, b As System.Int32)", model.GetSymbolInfo(propertyAccess2).Symbol.ToTestDisplayString()) End Sub <Fact> Public Sub OverriddenPropertyWithNoTupleNamesWithValueTuple() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Base Public Overridable Property P6 As (a As Integer, b As Integer) End Class Public Class Derived Inherits Base Public Overrides Property P6 As System.ValueTuple(Of Integer, Integer) Sub M() Dim result = Me.P6 Dim result2 = MyBase.P6 System.Console.Write(result.a) System.Console.Write(result2.a) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> </errors>) Dim tree = comp.SyntaxTrees.First() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim propertyAccess = nodes.OfType(Of MemberAccessExpressionSyntax)().ElementAt(0) Assert.Equal("Me.P6", propertyAccess.ToString()) Assert.Equal("Property Derived.P6 As (System.Int32, System.Int32)", model.GetSymbolInfo(propertyAccess).Symbol.ToTestDisplayString()) Dim propertyAccess2 = nodes.OfType(Of MemberAccessExpressionSyntax)().ElementAt(1) Assert.Equal("MyBase.P6", propertyAccess2.ToString()) Assert.Equal("Property Base.P6 As (a As System.Int32, b As System.Int32)", model.GetSymbolInfo(propertyAccess2).Symbol.ToTestDisplayString()) End Sub <Fact> Public Sub OverriddenEventWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class Base Public Overridable Event E1 As Action(Of (a As Integer, b As Integer)) End Class Public Class Derived Inherits Base Public Overrides Event E1 As Action(Of (Integer, Integer)) End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30243: 'Overridable' is not valid on an event declaration. Public Overridable Event E1 As Action(Of (a As Integer, b As Integer)) ~~~~~~~~~~~ BC30243: 'Overrides' is not valid on an event declaration. Public Overrides Event E1 As Action(Of (Integer, Integer)) ~~~~~~~~~ BC40004: event 'E1' conflicts with event 'E1' in the base class 'Base' and should be declared 'Shadows'. Public Overrides Event E1 As Action(Of (Integer, Integer)) ~~ </errors>) End Sub <Fact> Public Sub StructInStruct() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Public Structure S Public Field As (S, S) End Structure ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30294: Structure 'S' cannot contain an instance of itself: 'S' contains '(S, S)' (variable 'Field'). '(S, S)' contains 'S' (variable 'Item1'). Public Field As (S, S) ~~~~~ </errors>) End Sub <Fact> Public Sub AssignNullWithMissingValueTuple() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class S Dim t As (Integer, Integer) = Nothing End Class </file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported. Dim t As (Integer, Integer) = Nothing ~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub MultipleImplementsWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Interface I0 Sub M(x As (a0 As Integer, b0 As Integer)) Function MR() As (a0 As Integer, b0 As Integer) End Interface Public Interface I1 Sub M(x As (a1 As Integer, b1 As Integer)) Function MR() As (a1 As Integer, b1 As Integer) End Interface Public Class C1 Implements I0, I1 Public Sub M(x As (a2 As Integer, b2 As Integer)) Implements I0.M, I1.M End Sub Public Function MR() As (a2 As Integer, b2 As Integer) Implements I0.MR, I1.MR Return (1, 2) End Function End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30402: 'M' cannot implement sub 'M' on interface 'I0' because the tuple element names in 'Public Sub M(x As (a2 As Integer, b2 As Integer))' do not match those in 'Sub M(x As (a0 As Integer, b0 As Integer))'. Public Sub M(x As (a2 As Integer, b2 As Integer)) Implements I0.M, I1.M ~~~~ BC30402: 'M' cannot implement sub 'M' on interface 'I1' because the tuple element names in 'Public Sub M(x As (a2 As Integer, b2 As Integer))' do not match those in 'Sub M(x As (a1 As Integer, b1 As Integer))'. Public Sub M(x As (a2 As Integer, b2 As Integer)) Implements I0.M, I1.M ~~~~ BC30402: 'MR' cannot implement function 'MR' on interface 'I0' because the tuple element names in 'Public Function MR() As (a2 As Integer, b2 As Integer)' do not match those in 'Function MR() As (a0 As Integer, b0 As Integer)'. Public Function MR() As (a2 As Integer, b2 As Integer) Implements I0.MR, I1.MR ~~~~~ BC30402: 'MR' cannot implement function 'MR' on interface 'I1' because the tuple element names in 'Public Function MR() As (a2 As Integer, b2 As Integer)' do not match those in 'Function MR() As (a1 As Integer, b1 As Integer)'. Public Function MR() As (a2 As Integer, b2 As Integer) Implements I0.MR, I1.MR ~~~~~ </errors>) End Sub <Fact> Public Sub MethodSignatureComparerTest() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Public Sub M1(x As (a As Integer, b As Integer)) End Sub Public Sub M2(x As (a As Integer, b As Integer)) End Sub Public Sub M3(x As (notA As Integer, notB As Integer)) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics() Dim m1 = comp.GetMember(Of MethodSymbol)("C.M1") Dim m2 = comp.GetMember(Of MethodSymbol)("C.M2") Dim m3 = comp.GetMember(Of MethodSymbol)("C.M3") Dim comparison12 = MethodSignatureComparer.DetailedCompare(m1, m2, SymbolComparisonResults.TupleNamesMismatch) Assert.Equal(0, comparison12) Dim comparison13 = MethodSignatureComparer.DetailedCompare(m1, m3, SymbolComparisonResults.TupleNamesMismatch) Assert.Equal(SymbolComparisonResults.TupleNamesMismatch, comparison13) End Sub <Fact> Public Sub IsSameTypeTest() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Public Sub M1(x As (Integer, Integer)) End Sub Public Sub M2(x As (a As Integer, b As Integer)) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics() Dim m1 = comp.GetMember(Of MethodSymbol)("C.M1") Dim tuple1 As TypeSymbol = m1.Parameters(0).Type Dim underlying1 As NamedTypeSymbol = tuple1.TupleUnderlyingType Assert.True(tuple1.IsSameType(tuple1, TypeCompareKind.ConsiderEverything)) Assert.False(tuple1.IsSameType(underlying1, TypeCompareKind.ConsiderEverything)) Assert.False(underlying1.IsSameType(tuple1, TypeCompareKind.ConsiderEverything)) Assert.True(underlying1.IsSameType(underlying1, TypeCompareKind.ConsiderEverything)) Assert.True(tuple1.IsSameType(tuple1, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) Assert.False(tuple1.IsSameType(underlying1, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) Assert.False(underlying1.IsSameType(tuple1, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) Assert.True(underlying1.IsSameType(underlying1, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) Assert.True(tuple1.IsSameType(tuple1, TypeCompareKind.IgnoreTupleNames)) Assert.True(tuple1.IsSameType(underlying1, TypeCompareKind.IgnoreTupleNames)) Assert.True(underlying1.IsSameType(tuple1, TypeCompareKind.IgnoreTupleNames)) Assert.True(underlying1.IsSameType(underlying1, TypeCompareKind.IgnoreTupleNames)) Assert.False(tuple1.IsSameType(Nothing, TypeCompareKind.ConsiderEverything)) Assert.False(tuple1.IsSameType(Nothing, TypeCompareKind.IgnoreTupleNames)) Dim m2 = comp.GetMember(Of MethodSymbol)("C.M2") Dim tuple2 As TypeSymbol = m2.Parameters(0).Type Dim underlying2 As NamedTypeSymbol = tuple2.TupleUnderlyingType Assert.True(tuple2.IsSameType(tuple2, TypeCompareKind.ConsiderEverything)) Assert.False(tuple2.IsSameType(underlying2, TypeCompareKind.ConsiderEverything)) Assert.False(underlying2.IsSameType(tuple2, TypeCompareKind.ConsiderEverything)) Assert.True(underlying2.IsSameType(underlying2, TypeCompareKind.ConsiderEverything)) Assert.True(tuple2.IsSameType(tuple2, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) Assert.False(tuple2.IsSameType(underlying2, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) Assert.False(underlying2.IsSameType(tuple2, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) Assert.True(underlying2.IsSameType(underlying2, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) Assert.True(tuple2.IsSameType(tuple2, TypeCompareKind.IgnoreTupleNames)) Assert.True(tuple2.IsSameType(underlying2, TypeCompareKind.IgnoreTupleNames)) Assert.True(underlying2.IsSameType(tuple2, TypeCompareKind.IgnoreTupleNames)) Assert.True(underlying2.IsSameType(underlying2, TypeCompareKind.IgnoreTupleNames)) Assert.False(tuple1.IsSameType(tuple2, TypeCompareKind.ConsiderEverything)) Assert.False(tuple2.IsSameType(tuple1, TypeCompareKind.ConsiderEverything)) Assert.False(tuple1.IsSameType(tuple2, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) Assert.False(tuple2.IsSameType(tuple1, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) Assert.True(tuple1.IsSameType(tuple2, TypeCompareKind.IgnoreTupleNames)) Assert.True(tuple2.IsSameType(tuple1, TypeCompareKind.IgnoreTupleNames)) End Sub <Fact> Public Sub PropertySignatureComparer_TupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Public Property P1 As (a As Integer, b As Integer) Public Property P2 As (a As Integer, b As Integer) Public Property P3 As (notA As Integer, notB As Integer) End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics() Dim p1 = comp.GetMember(Of PropertySymbol)("C.P1") Dim p2 = comp.GetMember(Of PropertySymbol)("C.P2") Dim p3 = comp.GetMember(Of PropertySymbol)("C.P3") Dim comparison12 = PropertySignatureComparer.DetailedCompare(p1, p2, SymbolComparisonResults.TupleNamesMismatch) Assert.Equal(0, comparison12) Dim comparison13 = PropertySignatureComparer.DetailedCompare(p1, p3, SymbolComparisonResults.TupleNamesMismatch) Assert.Equal(SymbolComparisonResults.TupleNamesMismatch, comparison13) End Sub <Fact> Public Sub PropertySignatureComparer_TypeCustomModifiers() Dim il = <![CDATA[ .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern System.Core {} .assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 } .assembly '<<GeneratedFileName>>' { } .class public auto ansi beforefieldinit CL1`1<T1> extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method CL1`1::.ctor .property instance !T1 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) Test() { .get instance !T1 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) CL1`1::get_Test() .set instance void CL1`1::set_Test(!T1 modopt([mscorlib]System.Runtime.CompilerServices.IsConst)) } // end of property CL1`1::Test .method public hidebysig newslot specialname virtual instance !T1 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) get_Test() cil managed { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: throw } // end of method CL1`1::get_Test .method public hidebysig newslot specialname virtual instance void set_Test(!T1 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) x) cil managed { // Code size 3 (0x3) .maxstack 1 IL_0000: ldarg.0 IL_0001: throw IL_0002: ret } // end of method CL1`1::set_Test } // end of class CL1`1 ]]>.Value Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class CL2(Of T1) Public Property Test As T1 End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithCustomILSource(source1, il, appendDefaultHeader:=False, additionalReferences:={ValueTupleRef, SystemRuntimeFacadeRef}) comp1.AssertTheseDiagnostics() Dim property1 = comp1.GlobalNamespace.GetMember(Of PropertySymbol)("CL1.Test") Assert.Equal("Property CL1(Of T1).Test As T1 modopt(System.Runtime.CompilerServices.IsConst)", property1.ToTestDisplayString()) Dim property2 = comp1.GlobalNamespace.GetMember(Of PropertySymbol)("CL2.Test") Assert.Equal("Property CL2(Of T1).Test As T1", property2.ToTestDisplayString()) Assert.False(PropertySignatureComparer.RuntimePropertySignatureComparer.Equals(property1, property2)) End Sub <Fact> Public Sub EventSignatureComparerTest() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Public Event E1 As Action(Of (a As Integer, b As Integer)) Public Event E2 As Action(Of (a As Integer, b As Integer)) Public Event E3 As Action(Of (notA As Integer, notB As Integer)) End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics() Dim e1 = comp.GetMember(Of EventSymbol)("C.E1") Dim e2 = comp.GetMember(Of EventSymbol)("C.E2") Dim e3 = comp.GetMember(Of EventSymbol)("C.E3") Assert.True(EventSignatureComparer.ExplicitEventImplementationWithTupleNamesComparer.Equals(e1, e2)) Assert.False(EventSignatureComparer.ExplicitEventImplementationWithTupleNamesComparer.Equals(e1, e3)) End Sub <Fact> Public Sub OperatorOverloadingWithDifferentTupleNames() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Class B1 Shared Operator >=(x1 As (a As B1, b As B1), x2 As B1) As Boolean Return Nothing End Operator Shared Operator <=(x1 As (notA As B1, notB As B1), x2 As B1) As Boolean Return Nothing End Operator End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() End Sub <Fact> Public Sub Shadowing() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C0 Public Function M(x As (a As Integer, (b As Integer, c As Integer))) As (a As Integer, (b As Integer, c As Integer)) Return (1, (2, 3)) End Function End Class Public Class C1 Inherits C0 Public Function M(x As (a As Integer, (notB As Integer, c As Integer))) As (a As Integer, (notB As Integer, c As Integer)) Return (1, (2, 3)) End Function End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC40003: function 'M' shadows an overloadable member declared in the base class 'C0'. If you want to overload the base method, this method must be declared 'Overloads'. Public Function M(x As (a As Integer, (notB As Integer, c As Integer))) As (a As Integer, (notB As Integer, c As Integer)) ~ </errors>) End Sub <Fact> Public Sub UnifyDifferentTupleName() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Interface I0(Of T1) End Interface Class C(Of T2) Implements I0(Of (a As Integer, b As Integer)), I0(Of (notA As T2, notB As T2)) End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC32072: Cannot implement interface 'I0(Of (notA As T2, notB As T2))' because its implementation could conflict with the implementation of another implemented interface 'I0(Of (a As Integer, b As Integer))' for some type arguments. Implements I0(Of (a As Integer, b As Integer)), I0(Of (notA As T2, notB As T2)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub BC31407ERR_MultipleEventImplMismatch3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Interface I1 Event evtTest1(x As (A As Integer, B As Integer)) Event evtTest2(x As (A As Integer, notB As Integer)) End Interface Class C1 Implements I1 Event evtTest3(x As (A As Integer, stilNotB As Integer)) Implements I1.evtTest1, I1.evtTest2 End Class ]]></file> </compilation>, references:=s_valueTupleRefs) Dim expectedErrors1 = <errors><![CDATA[ BC30402: 'evtTest3' cannot implement event 'evtTest1' on interface 'I1' because the tuple element names in 'Public Event evtTest3 As I1.evtTest1EventHandler' do not match those in 'Event evtTest1(x As (A As Integer, B As Integer))'. Event evtTest3(x As (A As Integer, stilNotB As Integer)) Implements I1.evtTest1, I1.evtTest2 ~~~~~~~~~~~ BC30402: 'evtTest3' cannot implement event 'evtTest2' on interface 'I1' because the tuple element names in 'Public Event evtTest3 As I1.evtTest1EventHandler' do not match those in 'Event evtTest2(x As (A As Integer, notB As Integer))'. Event evtTest3(x As (A As Integer, stilNotB As Integer)) Implements I1.evtTest1, I1.evtTest2 ~~~~~~~~~~~ BC31407: Event 'Public Event evtTest3 As I1.evtTest1EventHandler' cannot implement event 'I1.Event evtTest2(x As (A As Integer, notB As Integer))' because its delegate type does not match the delegate type of another event implemented by 'Public Event evtTest3 As I1.evtTest1EventHandler'. Event evtTest3(x As (A As Integer, stilNotB As Integer)) Implements I1.evtTest1, I1.evtTest2 ~~~~~~~~~~~ ]]></errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub ImplementingEventWithDifferentTupleNames() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Interface I1 Event evtTest1 As Action(Of (A As Integer, B As Integer)) Event evtTest2 As Action(Of (A As Integer, notB As Integer)) End Interface Class C1 Implements I1 Event evtTest3 As Action(Of (A As Integer, stilNotB As Integer)) Implements I1.evtTest1, I1.evtTest2 End Class ]]></file> </compilation>, references:=s_valueTupleRefs) Dim expectedErrors1 = <errors><![CDATA[ BC30402: 'evtTest3' cannot implement event 'evtTest1' on interface 'I1' because the tuple element names in 'Public Event evtTest3 As Action(Of (A As Integer, stilNotB As Integer))' do not match those in 'Event evtTest1 As Action(Of (A As Integer, B As Integer))'. Event evtTest3 As Action(Of (A As Integer, stilNotB As Integer)) Implements I1.evtTest1, I1.evtTest2 ~~~~~~~~~~~ BC30402: 'evtTest3' cannot implement event 'evtTest2' on interface 'I1' because the tuple element names in 'Public Event evtTest3 As Action(Of (A As Integer, stilNotB As Integer))' do not match those in 'Event evtTest2 As Action(Of (A As Integer, notB As Integer))'. Event evtTest3 As Action(Of (A As Integer, stilNotB As Integer)) Implements I1.evtTest1, I1.evtTest2 ~~~~~~~~~~~ ]]></errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub ImplementingEventWithNoTupleNames() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Interface I1 Event evtTest1 As Action(Of (A As Integer, B As Integer)) Event evtTest2 As Action(Of (A As Integer, notB As Integer)) End Interface Class C1 Implements I1 Event evtTest3 As Action(Of (Integer, Integer)) Implements I1.evtTest1, I1.evtTest2 End Class ]]></file> </compilation>, references:=s_valueTupleRefs) CompilationUtils.AssertNoDiagnostics(compilation1) End Sub <Fact()> Public Sub ImplementingPropertyWithDifferentTupleNames() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Interface I1 Property P(x As (a As Integer, b As Integer)) As Boolean End Interface Class C1 Implements I1 Property P(x As (notA As Integer, notB As Integer)) As Boolean Implements I1.P Get Return True End Get Set End Set End Property End Class ]]></file> </compilation>, references:=s_valueTupleRefs) compilation.AssertTheseDiagnostics(<errors> BC30402: 'P' cannot implement property 'P' on interface 'I1' because the tuple element names in 'Public Property P(x As (notA As Integer, notB As Integer)) As Boolean' do not match those in 'Property P(x As (a As Integer, b As Integer)) As Boolean'. Property P(x As (notA As Integer, notB As Integer)) As Boolean Implements I1.P ~~~~ </errors>) End Sub <Fact()> Public Sub ImplementingPropertyWithNoTupleNames() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Interface I1 Property P(x As (a As Integer, b As Integer)) As Boolean End Interface Class C1 Implements I1 Property P(x As (Integer, Integer)) As Boolean Implements I1.P Get Return True End Get Set End Set End Property End Class ]]></file> </compilation>, references:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() End Sub <Fact()> Public Sub ImplementingPropertyWithNoTupleNames2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Interface I1 Property P As (a As Integer, b As Integer) End Interface Class C1 Implements I1 Property P As (Integer, Integer) Implements I1.P End Class ]]></file> </compilation>, references:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() End Sub <Fact()> Public Sub ImplementingMethodWithNoTupleNames() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Interface I1 Sub M(x As (a As Integer, b As Integer)) Function M2 As (a As Integer, b As Integer) End Interface Class C1 Implements I1 Sub M(x As (Integer, Integer)) Implements I1.M End Sub Function M2 As (Integer, Integer) Implements I1.M2 Return (1, 2) End Function End Class ]]></file> </compilation>, references:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() End Sub <Fact> Public Sub BC31407ERR_MultipleEventImplMismatch3_2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Interface I1 Event evtTest1 As Action(Of (A As Integer, B As Integer)) Event evtTest2 As Action(Of (A As Integer, notB As Integer)) End Interface Class C1 Implements I1 Event evtTest3(x As (A As Integer, stillNotB As Integer)) Implements I1.evtTest1, I1.evtTest2 End Class ]]></file> </compilation>, references:=s_valueTupleRefs) compilation1.AssertTheseDiagnostics( <errors> BC30402: 'evtTest3' cannot implement event 'evtTest1' on interface 'I1' because the tuple element names in 'Public Event evtTest3 As Action(Of (A As Integer, B As Integer))' do not match those in 'Event evtTest1 As Action(Of (A As Integer, B As Integer))'. Event evtTest3(x As (A As Integer, stillNotB As Integer)) Implements I1.evtTest1, I1.evtTest2 ~~~~~~~~~~~ BC30402: 'evtTest3' cannot implement event 'evtTest2' on interface 'I1' because the tuple element names in 'Public Event evtTest3 As Action(Of (A As Integer, B As Integer))' do not match those in 'Event evtTest2 As Action(Of (A As Integer, notB As Integer))'. Event evtTest3(x As (A As Integer, stillNotB As Integer)) Implements I1.evtTest1, I1.evtTest2 ~~~~~~~~~~~ </errors>) End Sub <WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")> <Fact> Public Sub ValueTupleNotStruct0() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Tuples"> <file name="a.vb"> class C Shared Sub Main() Dim x as (a As Integer, b As String) x.Item1 = 1 x.b = "2" ' by the language rules tuple x is definitely assigned ' since all its elements are definitely assigned System.Console.WriteLine(x) end sub end class namespace System public class ValueTuple(Of T1, T2) public Item1 as T1 public Item2 as T2 public Sub New(item1 as T1 , item2 as T2 ) Me.Item1 = item1 Me.Item2 = item2 end sub End class end Namespace <%= s_tupleattributes %> </file> </compilation>, options:=TestOptions.DebugExe) comp.AssertTheseEmitDiagnostics( <errors> BC37281: Predefined type 'ValueTuple`2' must be a structure. Dim x as (a As Integer, b As String) ~ </errors>) End Sub <WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")> <Fact> Public Sub ValueTupleNotStruct1() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Tuples"> <file name="a.vb"> class C Shared Sub Main() Dim x = (1,2,3,4,5,6,7,8,9) System.Console.WriteLine(x) end sub end class namespace System public class ValueTuple(Of T1, T2) public Item1 as T1 public Item2 as T2 public Sub New(item1 as T1 , item2 as T2 ) Me.Item1 = item1 Me.Item2 = item2 end sub End class public class ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest) public Item1 As T1 public Item2 As T2 public Item3 As T3 public Item4 As T4 public Item5 As T5 public Item6 As T6 public Item7 As T7 public Rest As TRest public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6, item7 As T7, rest As TRest) Item1 = item1 Item2 = item2 Item3 = item3 Item4 = item4 Item5 = item5 Item6 = item6 Item7 = item7 Rest = rest end Sub End Class end Namespace <%= s_tupleattributes %> </file> </compilation>, options:=TestOptions.DebugExe) comp.AssertTheseEmitDiagnostics( <errors> BC37281: Predefined type 'ValueTuple`2' must be a structure. Dim x = (1,2,3,4,5,6,7,8,9) ~ BC37281: Predefined type 'ValueTuple`8' must be a structure. Dim x = (1,2,3,4,5,6,7,8,9) ~ </errors>) End Sub <Fact> Public Sub ConversionToBase() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class Base(Of T) End Class Public Class Derived Inherits Base(Of (a As Integer, b As Integer)) Public Shared Narrowing Operator CType(ByVal arg As Derived) As Base(Of (Integer, Integer)) Return Nothing End Operator Public Shared Narrowing Operator CType(ByVal arg As Base(Of (Integer, Integer))) As Derived Return Nothing End Operator End Class ]]></file> </compilation>, references:=s_valueTupleRefs) compilation1.AssertTheseDiagnostics( <errors> BC33026: Conversion operators cannot convert from a type to its base type. Public Shared Narrowing Operator CType(ByVal arg As Derived) As Base(Of (Integer, Integer)) ~~~~~ BC33030: Conversion operators cannot convert from a base type. Public Shared Narrowing Operator CType(ByVal arg As Base(Of (Integer, Integer))) As Derived ~~~~~ </errors>) End Sub <WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")> <Fact> Public Sub ValueTupleNotStruct2() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Tuples"> <file name="a.vb"> class C Shared Sub Main() end sub Shared Sub Test2(arg as (a As Integer, b As Integer)) End Sub end class namespace System public class ValueTuple(Of T1, T2) public Item1 as T1 public Item2 as T2 public Sub New(item1 as T1 , item2 as T2 ) Me.Item1 = item1 Me.Item2 = item2 end sub End class end Namespace <%= s_tupleattributes %> </file> </compilation>, options:=TestOptions.DebugExe) comp.AssertTheseEmitDiagnostics( <errors> BC37281: Predefined type 'ValueTuple`2' must be a structure. </errors>) End Sub <WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")> <Fact> Public Sub ValueTupleNotStruct2i() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Tuples"> <file name="a.vb"> class C Shared Sub Main() end sub Shared Sub Test2(arg as (a As Integer, b As Integer)) End Sub end class namespace System public interface ValueTuple(Of T1, T2) End Interface end Namespace <%= s_tupleattributes %> </file> </compilation>, options:=TestOptions.DebugExe) comp.AssertTheseEmitDiagnostics( <errors> BC37281: Predefined type 'ValueTuple`2' must be a structure. </errors>) End Sub <WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")> <Fact> Public Sub ValueTupleNotStruct3() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Tuples"> <file name="a.vb"> class C Shared Sub Main() Dim x as (a As Integer, b As String)() = Nothing ' by the language rules tuple x is definitely assigned ' since all its elements are definitely assigned System.Console.WriteLine(x) end sub end class namespace System public class ValueTuple(Of T1, T2) public Item1 as T1 public Item2 as T2 public Sub New(item1 as T1 , item2 as T2 ) Me.Item1 = item1 Me.Item2 = item2 end sub End class end Namespace <%= s_tupleattributes %> </file> </compilation>, options:=TestOptions.DebugExe) comp.AssertTheseEmitDiagnostics( <errors> BC37281: Predefined type 'ValueTuple`2' must be a structure. Dim x as (a As Integer, b As String)() = Nothing ~ </errors>) End Sub <WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")> <Fact> Public Sub ValueTupleNotStruct4() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Tuples"> <file name="a.vb"> class C Shared Sub Main() end sub Shared Function Test2()as (a As Integer, b As Integer) End Function end class namespace System public class ValueTuple(Of T1, T2) public Item1 as T1 public Item2 as T2 public Sub New(item1 as T1 , item2 as T2 ) Me.Item1 = item1 Me.Item2 = item2 end sub End class end Namespace <%= s_tupleattributes %> </file> </compilation>, options:=TestOptions.DebugExe) comp.AssertTheseEmitDiagnostics( <errors> BC37281: Predefined type 'ValueTuple`2' must be a structure. Shared Function Test2()as (a As Integer, b As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub ValueTupleBaseError_NoSystemRuntime() Dim comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I Function F() As ((Integer, Integer), (Integer, Integer)) End Interface </file> </compilation>, references:={ValueTupleRef}) comp.AssertTheseEmitDiagnostics( <errors> BC30652: Reference required to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' containing the type 'ValueType'. Add one to your project. Function F() As ((Integer, Integer), (Integer, Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30652: Reference required to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' containing the type 'ValueType'. Add one to your project. Function F() As ((Integer, Integer), (Integer, Integer)) ~~~~~~~~~~~~~~~~~~ BC30652: Reference required to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' containing the type 'ValueType'. Add one to your project. Function F() As ((Integer, Integer), (Integer, Integer)) ~~~~~~~~~~~~~~~~~~ </errors>) End Sub <WorkItem(16879, "https://github.com/dotnet/roslyn/issues/16879")> <Fact> Public Sub ValueTupleBaseError_MissingReference() Dim comp0 = CreateCompilationWithMscorlib40( <compilation name="5a03232e-1a0f-4d1b-99ba-5d7b40ea931e"> <file name="a.vb"> Public Class A End Class Public Class B End Class </file> </compilation>) comp0.AssertNoDiagnostics() Dim ref0 = comp0.EmitToImageReference() Dim comp1 = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Public Class C(Of T) End Class Namespace System Public Class ValueTuple(Of T1, T2) Inherits A Public Sub New(_1 As T1, _2 As T2) End Sub End Class Public Class ValueTuple(Of T1, T2, T3) Inherits C(Of B) Public Sub New(_1 As T1, _2 As T2, _3 As T3) End Sub End Class End Namespace </file> </compilation>, references:={ref0}) Dim ref1 = comp1.EmitToImageReference() Dim comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I Function F() As (Integer, (Integer, Integer), (Integer, Integer)) End Interface </file> </compilation>, references:={ref1}) comp.AssertTheseEmitDiagnostics( <errors> BC30652: Reference required to assembly '5a03232e-1a0f-4d1b-99ba-5d7b40ea931e, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'A'. Add one to your project. BC30652: Reference required to assembly '5a03232e-1a0f-4d1b-99ba-5d7b40ea931e, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'B'. Add one to your project. </errors>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.TestExecutionNeedsWindowsTypes)> Public Sub ValueTupleBase_AssemblyUnification() Dim signedDllOptions = TestOptions.SigningReleaseDll. WithCryptoKeyFile(SigningTestHelpers.KeyPairFile) Dim comp0v1 = CreateCompilationWithMscorlib40( <compilation name="A"> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyVersion("1.0.0.0")> Public Class A End Class ]]></file> </compilation>, options:=signedDllOptions) comp0v1.AssertNoDiagnostics() Dim ref0v1 = comp0v1.EmitToImageReference() Dim comp0v2 = CreateCompilationWithMscorlib40( <compilation name="A"> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyVersion("2.0.0.0")> Public Class A End Class ]]></file> </compilation>, options:=signedDllOptions) comp0v2.AssertNoDiagnostics() Dim ref0v2 = comp0v2.EmitToImageReference() Dim comp1 = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Public Class B Inherits A End Class </file> </compilation>, references:={ref0v1}) comp1.AssertNoDiagnostics() Dim ref1 = comp1.EmitToImageReference() Dim comp2 = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Namespace System Public Class ValueTuple(Of T1, T2) Inherits B Public Sub New(_1 As T1, _2 As T2) End Sub End Class End Namespace </file> </compilation>, references:={ref0v1, ref1}) Dim ref2 = comp2.EmitToImageReference() Dim comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I Function F() As (Integer, Integer) End Interface </file> </compilation>, references:={ref0v2, ref1, ref2}) comp.AssertTheseEmitDiagnostics( <errors> BC37281: Predefined type 'ValueTuple`2' must be a structure. </errors>) End Sub <Fact> Public Sub TernaryTypeInferenceWithDynamicAndTupleNames() ' No dynamic in VB Dim comp = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Tuples"> <file name="a.vb"><![CDATA[ Class C Sub M() Dim flag As Boolean = True Dim x1 = If(flag, (a:=1, b:=2), (a:=1, c:=3)) System.Console.Write(x1.a) End Sub End Class ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC41009: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'. Dim x1 = If(flag, (a:=1, b:=2), (a:=1, c:=3)) ~~~~ BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'. Dim x1 = If(flag, (a:=1, b:=2), (a:=1, c:=3)) ~~~~ </errors>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim x1 = nodes.OfType(Of VariableDeclaratorSyntax)().Skip(1).First().Names(0) Dim x1Symbol = model.GetDeclaredSymbol(x1) Assert.Equal("x1 As (a As System.Int32, System.Int32)", x1Symbol.ToTestDisplayString()) End Sub <Fact> <WorkItem(16825, "https://github.com/dotnet/roslyn/issues/16825")> Public Sub NullCoalescingOperatorWithTupleNames() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Tuples"> <file name="a.vb"><![CDATA[ Class C Sub M() Dim nab As (a As Integer, b As Integer)? = (1, 2) Dim nac As (a As Integer, c As Integer)? = (1, 3) Dim x1 = If(nab, nac) ' (a, )? Dim x2 = If(nab, nac.Value) ' (a, ) Dim x3 = If(new C(), nac) ' C Dim x4 = If(new D(), nac) ' (a, c)? Dim x5 = If(nab IsNot Nothing, nab, nac) ' (a, )? Dim x6 = If(nab, (a:= 1, c:= 3)) ' (a, ) Dim x7 = If(nab, (a:= 1, 3)) ' (a, ) Dim x8 = If(new C(), (a:= 1, c:= 3)) ' C Dim x9 = If(new D(), (a:= 1, c:= 3)) ' (a, c) Dim x6double = If(nab, (d:= 1.1, c:= 3)) ' (d, c) End Sub Public Shared Narrowing Operator CType(ByVal x As (Integer, Integer)) As C Throw New System.Exception() End Operator End Class Class D Public Shared Narrowing Operator CType(ByVal x As D) As (d1 As Integer, d2 As Integer) Throw New System.Exception() End Operator End Class ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'. Dim x6 = If(nab, (a:= 1, c:= 3)) ' (a, ) ~~~~~ </errors>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim x1 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(2).Names(0) Assert.Equal("x1 As System.Nullable(Of (a As System.Int32, System.Int32))", model.GetDeclaredSymbol(x1).ToTestDisplayString()) Dim x2 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(3).Names(0) Assert.Equal("x2 As (a As System.Int32, System.Int32)", model.GetDeclaredSymbol(x2).ToTestDisplayString()) Dim x3 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(4).Names(0) Assert.Equal("x3 As C", model.GetDeclaredSymbol(x3).ToTestDisplayString()) Dim x4 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(5).Names(0) Assert.Equal("x4 As System.Nullable(Of (a As System.Int32, c As System.Int32))", model.GetDeclaredSymbol(x4).ToTestDisplayString()) Dim x5 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(6).Names(0) Assert.Equal("x5 As System.Nullable(Of (a As System.Int32, System.Int32))", model.GetDeclaredSymbol(x5).ToTestDisplayString()) Dim x6 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(7).Names(0) Assert.Equal("x6 As (a As System.Int32, System.Int32)", model.GetDeclaredSymbol(x6).ToTestDisplayString()) Dim x7 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(8).Names(0) Assert.Equal("x7 As (a As System.Int32, System.Int32)", model.GetDeclaredSymbol(x7).ToTestDisplayString()) Dim x8 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(9).Names(0) Assert.Equal("x8 As C", model.GetDeclaredSymbol(x8).ToTestDisplayString()) Dim x9 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(10).Names(0) Assert.Equal("x9 As (a As System.Int32, c As System.Int32)", model.GetDeclaredSymbol(x9).ToTestDisplayString()) Dim x6double = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(11).Names(0) Assert.Equal("x6double As (d As System.Double, c As System.Int32)", model.GetDeclaredSymbol(x6double).ToTestDisplayString()) End Sub <Fact> Public Sub TernaryTypeInferenceWithNoNames() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Tuples"> <file name="a.vb"><![CDATA[ Class C Sub M() Dim flag As Boolean = True Dim x1 = If(flag, (a:=1, b:=2), (1, 3)) Dim x2 = If(flag, (1, 2), (a:=1, b:=3)) End Sub End Class ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC41009: The tuple element name 'a' is ignored because a different name or no name is specified by the target type '(Integer, Integer)'. Dim x1 = If(flag, (a:=1, b:=2), (1, 3)) ~~~~ BC41009: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(Integer, Integer)'. Dim x1 = If(flag, (a:=1, b:=2), (1, 3)) ~~~~ BC41009: The tuple element name 'a' is ignored because a different name or no name is specified by the target type '(Integer, Integer)'. Dim x2 = If(flag, (1, 2), (a:=1, b:=3)) ~~~~ BC41009: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(Integer, Integer)'. Dim x2 = If(flag, (1, 2), (a:=1, b:=3)) ~~~~ </errors>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim x1 = nodes.OfType(Of VariableDeclaratorSyntax)().Skip(1).First().Names(0) Dim x1Symbol = model.GetDeclaredSymbol(x1) Assert.Equal("x1 As (System.Int32, System.Int32)", x1Symbol.ToTestDisplayString()) Dim x2 = nodes.OfType(Of VariableDeclaratorSyntax)().Skip(2).First().Names(0) Dim x2Symbol = model.GetDeclaredSymbol(x2) Assert.Equal("x2 As (System.Int32, System.Int32)", x2Symbol.ToTestDisplayString()) End Sub <Fact> Public Sub TernaryTypeInferenceDropsCandidates() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Tuples"> <file name="a.vb"><![CDATA[ Class C Sub M() Dim flag As Boolean = True Dim x1 = If(flag, (a:=1, b:=CType(2, Long)), (a:=CType(1, Byte), c:=3)) End Sub End Class ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(a As Integer, b As Long)'. Dim x1 = If(flag, (a:=1, b:=CType(2, Long)), (a:=CType(1, Byte), c:=3)) ~~~~ </errors>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim x1 = nodes.OfType(Of VariableDeclaratorSyntax)().Skip(1).First().Names(0) Dim x1Symbol = model.GetDeclaredSymbol(x1) Assert.Equal("x1 As (a As System.Int32, b As System.Int64)", x1Symbol.ToTestDisplayString()) End Sub <Fact> Public Sub LambdaTypeInferenceWithTupleNames() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Tuples"> <file name="a.vb"><![CDATA[ Class C Sub M() Dim x1 = M2(Function() Dim flag = True If flag Then Return (a:=1, b:=2) Else If flag Then Return (a:=1, c:=3) Else Return (a:=1, d:=4) End If End If End Function) End Sub Function M2(Of T)(f As System.Func(Of T)) As T Return f() End Function End Class ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC41009: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'. Return (a:=1, b:=2) ~~~~ BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'. Return (a:=1, c:=3) ~~~~ BC41009: The tuple element name 'd' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'. Return (a:=1, d:=4) ~~~~ </errors>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim x1 = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Dim x1Symbol = model.GetDeclaredSymbol(x1) Assert.Equal("x1 As (a As System.Int32, System.Int32)", x1Symbol.ToTestDisplayString()) End Sub <Fact> Public Sub LambdaTypeInferenceFallsBackToObject() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Tuples"> <file name="a.vb"><![CDATA[ Class C Sub M() Dim x1 = M2(Function() Dim flag = True Dim l1 = CType(2, Long) If flag Then Return (a:=1, b:=l1) Else If flag Then Return (a:=l1, c:=3) Else Return (a:=1, d:=l1) End If End If End Function) End Sub Function M2(Of T)(f As System.Func(Of T)) As T Return f() End Function End Class ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics() Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim x1 = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Dim x1Symbol = model.GetDeclaredSymbol(x1) Assert.Equal("x1 As System.Object", x1Symbol.ToTestDisplayString()) End Sub <Fact> Public Sub IsBaseOf_WithoutCustomModifiers() ' The IL is from this code, but with modifiers ' public class Base<T> { } ' public class Derived<T> : Base<T> { } ' public class Test ' { ' public Base<Object> GetBaseWithModifiers() { return null; } ' public Derived<Object> GetDerivedWithoutModifiers() { return null; } ' } Dim il = <![CDATA[ .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern System.Core {} .assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 } .assembly '<<GeneratedFileName>>' { } .class public auto ansi beforefieldinit Base`1<T> extends [mscorlib]System.Object { // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2050 // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method Base`1::.ctor } // end of class Base`1 .class public auto ansi beforefieldinit Derived`1<T> extends class Base`1<!T> { // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2059 // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void class Base`1<!T>::.ctor() IL_0006: nop IL_0007: ret } // end of method Derived`1::.ctor } // end of class Derived`1 .class public auto ansi beforefieldinit Test extends [mscorlib]System.Object { // Methods .method public hidebysig instance class Base`1<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)> GetBaseWithModifiers () cil managed { // Method begins at RVA 0x2064 // Code size 7 (0x7) .maxstack 1 .locals init ( [0] class Base`1<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)> ) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: br.s IL_0005 IL_0005: ldloc.0 IL_0006: ret } // end of method Test::GetBaseWithModifiers .method public hidebysig instance class Derived`1<object> GetDerivedWithoutModifiers () cil managed { // Method begins at RVA 0x2078 // Code size 7 (0x7) .maxstack 1 .locals init ( [0] class Derived`1<object> ) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: br.s IL_0005 IL_0005: ldloc.0 IL_0006: ret } // end of method Test::GetDerivedWithoutModifiers .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2050 // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method Test::.ctor } // end of class Test ]]>.Value Dim source1 = <compilation> <file name="c.vb"><![CDATA[ ]]></file> </compilation> Dim comp1 = CreateCompilationWithCustomILSource(source1, il, appendDefaultHeader:=False) comp1.AssertTheseDiagnostics() Dim baseWithModifiers = comp1.GlobalNamespace.GetMember(Of MethodSymbol)("Test.GetBaseWithModifiers").ReturnType Assert.Equal("Base(Of System.Object modopt(System.Runtime.CompilerServices.IsLong))", baseWithModifiers.ToTestDisplayString()) Dim derivedWithoutModifiers = comp1.GlobalNamespace.GetMember(Of MethodSymbol)("Test.GetDerivedWithoutModifiers").ReturnType Assert.Equal("Derived(Of System.Object)", derivedWithoutModifiers.ToTestDisplayString()) Dim diagnostics = New HashSet(Of DiagnosticInfo)() Assert.True(baseWithModifiers.IsBaseTypeOf(derivedWithoutModifiers, diagnostics)) Assert.True(derivedWithoutModifiers.IsOrDerivedFrom(derivedWithoutModifiers, diagnostics)) End Sub <Fact> Public Sub WarnForDroppingNamesInConversion() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Tuples"> <file name="a.vb"><![CDATA[ Class C Sub M() Dim x1 As (a As Integer, Integer) = (1, b:=2) Dim x2 As (a As Integer, String) = (1, b:=Nothing) End Sub End Class ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC41009: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'. Dim x1 As (a As Integer, Integer) = (1, b:=2) ~~~~ BC41009: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(a As Integer, String)'. Dim x2 As (a As Integer, String) = (1, b:=Nothing) ~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub MethodTypeInferenceMergesTupleNames() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Tuples"> <file name="a.vb"><![CDATA[ Class C Sub M() Dim t = M2((a:=1, b:=2), (a:=1, c:=3)) System.Console.Write(t.a) System.Console.Write(t.b) System.Console.Write(t.c) M2((1, 2), (c:=1, d:=3)) M2({(a:=1, b:=2)}, {(1, 3)}) End Sub Function M2(Of T)(x1 As T, x2 As T) As T Return x1 End Function End Class ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC41009: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'. Dim t = M2((a:=1, b:=2), (a:=1, c:=3)) ~~~~ BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'. Dim t = M2((a:=1, b:=2), (a:=1, c:=3)) ~~~~ BC30456: 'b' is not a member of '(a As Integer, Integer)'. System.Console.Write(t.b) ~~~ BC30456: 'c' is not a member of '(a As Integer, Integer)'. System.Console.Write(t.c) ~~~ BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(Integer, Integer)'. M2((1, 2), (c:=1, d:=3)) ~~~~ BC41009: The tuple element name 'd' is ignored because a different name or no name is specified by the target type '(Integer, Integer)'. M2((1, 2), (c:=1, d:=3)) ~~~~ </errors>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim invocation1 = model.GetSymbolInfo(nodes.OfType(Of InvocationExpressionSyntax)().First()) Assert.Equal("(a As System.Int32, System.Int32)", DirectCast(invocation1.Symbol, MethodSymbol).ReturnType.ToTestDisplayString()) Dim invocation2 = model.GetSymbolInfo(nodes.OfType(Of InvocationExpressionSyntax)().Skip(4).First()) Assert.Equal("(System.Int32, System.Int32)", DirectCast(invocation2.Symbol, MethodSymbol).ReturnType.ToTestDisplayString()) Dim invocation3 = model.GetSymbolInfo(nodes.OfType(Of InvocationExpressionSyntax)().Skip(5).First()) Assert.Equal("(a As System.Int32, b As System.Int32)()", DirectCast(invocation3.Symbol, MethodSymbol).ReturnType.ToTestDisplayString()) End Sub <Fact> Public Sub MethodTypeInferenceDropsCandidates() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Tuples"> <file name="a.vb"><![CDATA[ Class C Sub M() M2((a:=1, b:=2), (a:=CType(1, Byte), c:=CType(3, Byte))) M2((CType(1, Long), b:=2), (c:=1, d:=CType(3, Byte))) M2((a:=CType(1, Long), b:=2), (CType(1, Byte), 3)) End Sub Function M2(Of T)(x1 As T, x2 As T) As T Return x1 End Function End Class ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(a As Integer, b As Integer)'. M2((a:=1, b:=2), (a:=CType(1, Byte), c:=CType(3, Byte))) ~~~~~~~~~~~~~~~~~ BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(Long, b As Integer)'. M2((CType(1, Long), b:=2), (c:=1, d:=CType(3, Byte))) ~~~~ BC41009: The tuple element name 'd' is ignored because a different name or no name is specified by the target type '(Long, b As Integer)'. M2((CType(1, Long), b:=2), (c:=1, d:=CType(3, Byte))) ~~~~~~~~~~~~~~~~~ </errors>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim invocation1 = model.GetSymbolInfo(nodes.OfType(Of InvocationExpressionSyntax)().First()) Assert.Equal("(a As System.Int32, b As System.Int32)", DirectCast(invocation1.Symbol, MethodSymbol).ReturnType.ToTestDisplayString()) Dim invocation2 = model.GetSymbolInfo(nodes.OfType(Of InvocationExpressionSyntax)().Skip(1).First()) Assert.Equal("(System.Int64, b As System.Int32)", DirectCast(invocation2.Symbol, MethodSymbol).ReturnType.ToTestDisplayString()) Dim invocation3 = model.GetSymbolInfo(nodes.OfType(Of InvocationExpressionSyntax)().Skip(2).First()) Assert.Equal("(a As System.Int64, b As System.Int32)", DirectCast(invocation3.Symbol, MethodSymbol).ReturnType.ToTestDisplayString()) End Sub <Fact()> <WorkItem(14267, "https://github.com/dotnet/roslyn/issues/14267")> Public Sub NoSystemRuntimeFacade() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim o = (1, 2) End Sub End Module ]]></file> </compilation>, additionalRefs:={ValueTupleRef}) Assert.Equal(TypeKind.Class, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).TypeKind) comp.AssertTheseDiagnostics( <errors> BC30652: Reference required to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' containing the type 'ValueType'. Add one to your project. Dim o = (1, 2) ~~~~~~ </errors>) End Sub <Fact> <WorkItem(14888, "https://github.com/dotnet/roslyn/issues/14888")> Public Sub Iterator_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class C Shared Sub Main() For Each x in Test() Console.WriteLine(x) Next End Sub Shared Iterator Function Test() As IEnumerable(Of (integer, integer)) yield (1, 2) End Function End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:="(1, 2)") End Sub <Fact()> <WorkItem(14888, "https://github.com/dotnet/roslyn/issues/14888")> Public Sub Iterator_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class C Iterator Function Test() As IEnumerable(Of (integer, integer)) yield (1, 2) End Function End Class </file> </compilation>, additionalRefs:={ValueTupleRef}) comp.AssertTheseEmitDiagnostics( <errors> BC30652: Reference required to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' containing the type 'ValueType'. Add one to your project. Iterator Function Test() As IEnumerable(Of (integer, integer)) ~~~~~~~~~~~~~~~~~~ BC30652: Reference required to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' containing the type 'ValueType'. Add one to your project. yield (1, 2) ~~~~~~ </errors>) End Sub <Fact> <WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")> Public Sub UserDefinedConversionsAndNameMismatch_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Test((X1:=1, Y1:=2)) Dim t1 = (X1:=3, Y1:=4) Test(t1) Test((5, 6)) Dim t2 = (7, 8) Test(t2) End Sub Shared Sub Test(val As AA) End Sub End Class Public Class AA Public Shared Widening Operator CType(x As (X1 As Integer, Y1 As Integer)) As AA System.Console.WriteLine(x) return new AA() End Operator End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" (1, 2) (3, 4) (5, 6) (7, 8) ") End Sub <Fact> <WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")> Public Sub UserDefinedConversionsAndNameMismatch_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Test((X1:=1, Y1:=2)) Dim t1 = (X1:=3, Y1:=4) Test(t1) Test((5, 6)) Dim t2 = (7, 8) Test(t2) End Sub Shared Sub Test(val As AA?) End Sub End Class Public Structure AA Public Shared Widening Operator CType(x As (X1 As Integer, Y1 As Integer)) As AA System.Console.WriteLine(x) return new AA() End Operator End Structure </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" (1, 2) (3, 4) (5, 6) (7, 8) ") End Sub <Fact> <WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")> Public Sub UserDefinedConversionsAndNameMismatch_03() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Dim t1 As (X1 as Integer, Y1 as Integer)? = (X1:=3, Y1:=4) Test(t1) Dim t2 As (Integer, Integer)? = (7, 8) Test(t2) System.Console.WriteLine("--") t1 = Nothing Test(t1) t2 = Nothing Test(t2) System.Console.WriteLine("--") End Sub Shared Sub Test(val As AA?) End Sub End Class Public Structure AA Public Shared Widening Operator CType(x As (X1 As Integer, Y1 As Integer)) As AA System.Console.WriteLine(x) return new AA() End Operator End Structure </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" (3, 4) (7, 8) -- -- ") End Sub <Fact> <WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")> Public Sub UserDefinedConversionsAndNameMismatch_04() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Test(new AA()) End Sub Shared Sub Test(val As (X1 As Integer, Y1 As Integer)) System.Console.WriteLine(val) End Sub End Class Public Class AA Public Shared Widening Operator CType(x As AA) As (Integer, Integer) return (1, 2) End Operator End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:="(1, 2)") End Sub <Fact> <WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")> Public Sub UserDefinedConversionsAndNameMismatch_05() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Test(new AA()) End Sub Shared Sub Test(val As (X1 As Integer, Y1 As Integer)) System.Console.WriteLine(val) End Sub End Class Public Class AA Public Shared Widening Operator CType(x As AA) As (X1 As Integer, Y1 As Integer) return (1, 2) End Operator End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:="(1, 2)") End Sub <Fact> <WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")> Public Sub UserDefinedConversionsAndNameMismatch_06() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Dim t1 As BB(Of (X1 as Integer, Y1 as Integer))? = New BB(Of (X1 as Integer, Y1 as Integer))() Test(t1) Dim t2 As BB(Of (Integer, Integer))? = New BB(Of (Integer, Integer))() Test(t2) System.Console.WriteLine("--") t1 = Nothing Test(t1) t2 = Nothing Test(t2) System.Console.WriteLine("--") End Sub Shared Sub Test(val As AA?) End Sub End Class Public Structure AA Public Shared Widening Operator CType(x As BB(Of (X1 As Integer, Y1 As Integer))) As AA System.Console.WriteLine("implicit operator AA") return new AA() End Operator End Structure Public Structure BB(Of T) End Structure </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" implicit operator AA implicit operator AA -- -- ") End Sub <Fact> Public Sub GenericConstraintAttributes() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Imports System.Collections Imports System.Collections.Generic Imports ClassLibrary4 Public Interface ITest(Of T) ReadOnly Property [Get] As T End Interface Public Class Test Implements ITest(Of (key As Integer, val As Integer)) Public ReadOnly Property [Get] As (key As Integer, val As Integer) Implements ITest(Of (key As Integer, val As Integer)).Get Get Return (0, 0) End Get End Property End Class Public Class Base(Of T) : Implements ITest(Of T) Public ReadOnly Property [Get] As T Implements ITest(Of T).Get Protected Sub New(t As T) [Get] = t End Sub End Class Public Class C(Of T As ITest(Of (key As Integer, val As Integer))) Public ReadOnly Property [Get] As T Public Sub New(t As T) [Get] = t End Sub End Class Public Class C2(Of T As Base(Of (key As Integer, val As Integer))) Public ReadOnly Property [Get] As T Public Sub New(t As T) [Get] = t End Sub End Class Public NotInheritable Class Test2 Inherits Base(Of (key As Integer, val As Integer)) Sub New() MyBase.New((-1, -2)) End Sub End Class Public Class C3(Of T As IEnumerable(Of (key As Integer, val As Integer))) Public ReadOnly Property [Get] As T Public Sub New(t As T) [Get] = t End Sub End Class Public Structure TestEnumerable Implements IEnumerable(Of (key As Integer, val As Integer)) Private ReadOnly _backing As (Integer, Integer)() Public Sub New(backing As (Integer, Integer)()) _backing = backing End Sub Private Class Inner Implements IEnumerator(Of (key As Integer, val As Integer)), IEnumerator Private index As Integer = -1 Private ReadOnly _backing As (Integer, Integer)() Public Sub New(backing As (Integer, Integer)()) _backing = backing End Sub Public ReadOnly Property Current As (key As Integer, val As Integer) Implements IEnumerator(Of (key As Integer, val As Integer)).Current Get Return _backing(index) End Get End Property Public ReadOnly Property Current1 As Object Implements IEnumerator.Current Get Return Current End Get End Property Public Sub Dispose() Implements IDisposable.Dispose End Sub Public Function MoveNext() As Boolean index += 1 Return index &lt; _backing.Length End Function Public Sub Reset() Throw New NotSupportedException() End Sub Private Function IEnumerator_MoveNext() As Boolean Implements IEnumerator.MoveNext Return MoveNext() End Function Private Sub IEnumerator_Reset() Implements IEnumerator.Reset Throw New NotImplementedException() End Sub End Class Public Function GetEnumerator() As IEnumerator(Of (key As Integer, val As Integer)) Implements IEnumerable(Of (key As Integer, val As Integer)).GetEnumerator Return New Inner(_backing) End Function Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return New Inner(_backing) End Function End Structure </file> </compilation>, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, symbolValidator:=Sub(m) Dim c = m.GlobalNamespace.GetTypeMember("C") Assert.Equal(1, c.TypeParameters.Length) Dim param = c.TypeParameters(0) Assert.Equal(1, param.ConstraintTypes.Length) Dim constraint = Assert.IsAssignableFrom(Of NamedTypeSymbol)(param.ConstraintTypes(0)) Assert.True(constraint.IsGenericType) Assert.Equal(1, constraint.TypeArguments.Length) Dim typeArg As TypeSymbol = constraint.TypeArguments(0) Assert.True(typeArg.IsTupleType) Assert.Equal(2, typeArg.TupleElementTypes.Length) Assert.All(typeArg.TupleElementTypes, Sub(t) Assert.Equal(SpecialType.System_Int32, t.SpecialType)) Assert.False(typeArg.TupleElementNames.IsDefault) Assert.Equal(2, typeArg.TupleElementNames.Length) Assert.Equal({"key", "val"}, typeArg.TupleElementNames) Dim c2 = m.GlobalNamespace.GetTypeMember("C2") Assert.Equal(1, c2.TypeParameters.Length) param = c2.TypeParameters(0) Assert.Equal(1, param.ConstraintTypes.Length) constraint = Assert.IsAssignableFrom(Of NamedTypeSymbol)(param.ConstraintTypes(0)) Assert.True(constraint.IsGenericType) Assert.Equal(1, constraint.TypeArguments.Length) typeArg = constraint.TypeArguments(0) Assert.True(typeArg.IsTupleType) Assert.Equal(2, typeArg.TupleElementTypes.Length) Assert.All(typeArg.TupleElementTypes, Sub(t) Assert.Equal(SpecialType.System_Int32, t.SpecialType)) Assert.False(typeArg.TupleElementNames.IsDefault) Assert.Equal(2, typeArg.TupleElementNames.Length) Assert.Equal({"key", "val"}, typeArg.TupleElementNames) End Sub ) Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Dim c = New C(Of Test)(New Test()) Dim temp = c.Get.Get Console.WriteLine(temp) Console.WriteLine("key: " &amp; temp.key) Console.WriteLine("val: " &amp; temp.val) Dim c2 = New C2(Of Test2)(New Test2()) Dim temp2 = c2.Get.Get Console.WriteLine(temp2) Console.WriteLine("key: " &amp; temp2.key) Console.WriteLine("val: " &amp; temp2.val) Dim backing = {(1, 2), (3, 4), (5, 6)} Dim c3 = New C3(Of TestEnumerable)(New TestEnumerable(backing)) For Each kvp In c3.Get Console.WriteLine($"key: {kvp.key}, val: {kvp.val}") Next Dim c4 = New C(Of Test2)(New Test2()) Dim temp4 = c4.Get.Get Console.WriteLine(temp4) Console.WriteLine("key: " &amp; temp4.key) Console.WriteLine("val: " &amp; temp4.val) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs.Concat({comp.EmitToImageReference()}).ToArray(), expectedOutput:=<![CDATA[ (0, 0) key: 0 val: 0 (-1, -2) key: -1 val: -2 key: 1, val: 2 key: 3, val: 4 key: 5, val: 6 (-1, -2) key: -1 val: -2 ]]>) End Sub <Fact> Public Sub UnusedTuple() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C Sub M() ' Warnings Dim x2 As Integer Const x3 As Integer = 1 Const x4 As String = "hello" Dim x5 As (Integer, Integer) Dim x6 As (String, String) ' No warnings Dim y10 As Integer = 1 Dim y11 As String = "hello" Dim y12 As (Integer, Integer) = (1, 2) Dim y13 As (String, String) = ("hello", "world") Dim tuple As (String, String) = ("hello", "world") Dim y14 As (String, String) = tuple Dim y15 = (2, 3) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC42024: Unused local variable: 'x2'. Dim x2 As Integer ~~ BC42099: Unused local constant: 'x3'. Const x3 As Integer = 1 ~~ BC42099: Unused local constant: 'x4'. Const x4 As String = "hello" ~~ BC42024: Unused local variable: 'x5'. Dim x5 As (Integer, Integer) ~~ BC42024: Unused local variable: 'x6'. Dim x6 As (String, String) ~~ </errors>) End Sub <Fact> <WorkItem(15198, "https://github.com/dotnet/roslyn/issues/15198")> Public Sub TuplePropertyArgs001() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class C Shared Sub Main() dim inst = new C dim f As (Integer, Integer) = (inst.P1, inst.P1) System.Console.WriteLine(f) End Sub public readonly Property P1 as integer Get return 42 End Get end Property End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:="(42, 42)") End Sub <Fact> <WorkItem(15198, "https://github.com/dotnet/roslyn/issues/15198")> Public Sub TuplePropertyArgs002() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class C Shared Sub Main() dim inst = new C dim f As IComparable(of (Integer, Integer)) = (inst.P1, inst.P1) System.Console.WriteLine(f) End Sub public readonly Property P1 as integer Get return 42 End Get end Property End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:="(42, 42)") End Sub <Fact> <WorkItem(15198, "https://github.com/dotnet/roslyn/issues/15198")> Public Sub TuplePropertyArgs003() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class C Shared Sub Main() dim inst as Object = new C dim f As (Integer, Integer) = (inst.P1, inst.P1) System.Console.WriteLine(f) End Sub public readonly Property P1 as integer Get return 42 End Get end Property End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:="(42, 42)") End Sub <Fact> <WorkItem(14844, "https://github.com/dotnet/roslyn/issues/14844")> Public Sub InterfaceImplAttributesAreNotSharedAcrossTypeRefs() Dim src1 = <compilation> <file name="a.vb"> <![CDATA[ Public Interface I1(Of T) End Interface Public Interface I2 Inherits I1(Of (a As Integer, b As Integer)) End Interface Public Interface I3 Inherits I1(Of (c As Integer, d As Integer)) End Interface ]]> </file> </compilation> Dim src2 = <compilation> <file name="a.vb"> <![CDATA[ Class C1 Implements I2 Implements I1(Of (a As Integer, b As Integer)) End Class Class C2 Implements I3 Implements I1(Of (c As Integer, d As Integer)) End Class ]]> </file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(src1, references:=s_valueTupleRefs) AssertTheseDiagnostics(comp1) Dim comp2 = CreateCompilationWithMscorlib40(src2, references:={SystemRuntimeFacadeRef, ValueTupleRef, comp1.ToMetadataReference()}) AssertTheseDiagnostics(comp2) Dim comp3 = CreateCompilationWithMscorlib40(src2, references:={SystemRuntimeFacadeRef, ValueTupleRef, comp1.EmitToImageReference()}) AssertTheseDiagnostics(comp3) End Sub <Fact()> <WorkItem(14881, "https://github.com/dotnet/roslyn/issues/14881")> <WorkItem(15476, "https://github.com/dotnet/roslyn/issues/15476")> Public Sub TupleElementVsLocal() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim tuple As (Integer, elem2 As Integer) Dim elem2 As Integer tuple = (5, 6) tuple.elem2 = 23 elem2 = 10 Console.WriteLine(tuple.elem2) Console.WriteLine(elem2) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(id) id.Identifier.ValueText = "elem2").ToArray() Assert.Equal(4, nodes.Length) Assert.Equal("tuple.elem2 = 23", nodes(0).Parent.Parent.ToString()) Assert.Equal("(System.Int32, elem2 As System.Int32).elem2 As System.Int32", model.GetSymbolInfo(nodes(0)).Symbol.ToTestDisplayString()) Assert.Equal("elem2 = 10", nodes(1).Parent.ToString()) Assert.Equal("elem2 As System.Int32", model.GetSymbolInfo(nodes(1)).Symbol.ToTestDisplayString()) Assert.Equal("(tuple.elem2)", nodes(2).Parent.Parent.Parent.ToString()) Assert.Equal("(System.Int32, elem2 As System.Int32).elem2 As System.Int32", model.GetSymbolInfo(nodes(2)).Symbol.ToTestDisplayString()) Assert.Equal("(elem2)", nodes(3).Parent.Parent.ToString()) Assert.Equal("elem2 As System.Int32", model.GetSymbolInfo(nodes(3)).Symbol.ToTestDisplayString()) Dim type = tree.GetRoot().DescendantNodes().OfType(Of TupleTypeSyntax)().Single() Dim symbolInfo = model.GetSymbolInfo(type) Assert.Equal("(System.Int32, elem2 As System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Dim typeInfo = model.GetTypeInfo(type) Assert.Equal("(System.Int32, elem2 As System.Int32)", typeInfo.Type.ToTestDisplayString()) Assert.Same(symbolInfo.Symbol, typeInfo.Type) Assert.Equal(SyntaxKind.TypedTupleElement, type.Elements.First().Kind()) Assert.Equal("(System.Int32, elem2 As System.Int32).Item1 As System.Int32", model.GetDeclaredSymbol(type.Elements.First()).ToTestDisplayString()) Assert.Equal(SyntaxKind.NamedTupleElement, type.Elements.Last().Kind()) Assert.Equal("(System.Int32, elem2 As System.Int32).elem2 As System.Int32", model.GetDeclaredSymbol(type.Elements.Last()).ToTestDisplayString()) Assert.Equal("(System.Int32, elem2 As System.Int32).Item1 As System.Int32", model.GetDeclaredSymbol(DirectCast(type.Elements.First(), SyntaxNode)).ToTestDisplayString()) Assert.Equal("(System.Int32, elem2 As System.Int32).elem2 As System.Int32", model.GetDeclaredSymbol(DirectCast(type.Elements.Last(), SyntaxNode)).ToTestDisplayString()) End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub ImplementSameInterfaceViaBaseWithDifferentTupleNames() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Interface ITest(Of T) End Interface Class Base Implements ITest(Of (a As Integer, b As Integer)) End Class Class Derived Inherits Base Implements ITest(Of (notA As Integer, notB As Integer)) End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim derived = tree.GetRoot().DescendantNodes().OfType(Of ClassStatementSyntax)().ElementAt(1) Dim derivedSymbol = model.GetDeclaredSymbol(derived) Assert.Equal("Derived", derivedSymbol.ToTestDisplayString()) Assert.Equal(New String() { "ITest(Of (a As System.Int32, b As System.Int32))", "ITest(Of (notA As System.Int32, notB As System.Int32))"}, derivedSymbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString())) End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub ImplementSameInterfaceViaBase() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Interface ITest(Of T) End Interface Class Base Implements ITest(Of Integer) End Class Class Derived Inherits Base Implements ITest(Of Integer) End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim derived = tree.GetRoot().DescendantNodes().OfType(Of ClassStatementSyntax)().ElementAt(1) Dim derivedSymbol = model.GetDeclaredSymbol(derived) Assert.Equal("Derived", derivedSymbol.ToTestDisplayString()) Assert.Equal(New String() {"ITest(Of System.Int32)"}, derivedSymbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString())) End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub GenericImplementSameInterfaceViaBaseWithoutTuples() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Interface ITest(Of T) End Interface Class Base Implements ITest(Of Integer) End Class Class Derived(Of T) Inherits Base Implements ITest(Of T) End Class Module M Sub Main() Dim instance1 = New Derived(Of Integer) Dim instance2 = New Derived(Of String) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim derived = tree.GetRoot().DescendantNodes().OfType(Of ClassStatementSyntax)().ElementAt(1) Dim derivedSymbol = DirectCast(model.GetDeclaredSymbol(derived), NamedTypeSymbol) Assert.Equal("Derived(Of T)", derivedSymbol.ToTestDisplayString()) Assert.Equal(New String() {"ITest(Of System.Int32)", "ITest(Of T)"}, derivedSymbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString())) Dim instance1 = tree.GetRoot().DescendantNodes().OfType(Of VariableDeclaratorSyntax)().ElementAt(0).Names(0) Dim instance1Symbol = DirectCast(model.GetDeclaredSymbol(instance1), LocalSymbol).Type Assert.Equal("Derived(Of Integer)", instance1Symbol.ToString()) Assert.Equal(New String() {"ITest(Of System.Int32)"}, instance1Symbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString())) Dim instance2 = tree.GetRoot().DescendantNodes().OfType(Of VariableDeclaratorSyntax)().ElementAt(1).Names(0) Dim instance2Symbol = DirectCast(model.GetDeclaredSymbol(instance2), LocalSymbol).Type Assert.Equal("Derived(Of String)", instance2Symbol.ToString()) Assert.Equal(New String() {"ITest(Of System.Int32)", "ITest(Of System.String)"}, instance2Symbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString())) Assert.Empty(derivedSymbol.AsUnboundGenericType().AllInterfaces) End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub GenericImplementSameInterfaceViaBase() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Interface ITest(Of T) End Interface Class Base Implements ITest(Of (a As Integer, b As Integer)) End Class Class Derived(Of T) Inherits Base Implements ITest(Of T) End Class Module M Sub Main() Dim instance1 = New Derived(Of (notA As Integer, notB As Integer)) Dim instance2 = New Derived(Of (notA As String, notB As String)) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim derived = tree.GetRoot().DescendantNodes().OfType(Of ClassStatementSyntax)().ElementAt(1) Dim derivedSymbol = model.GetDeclaredSymbol(derived) Assert.Equal("Derived(Of T)", derivedSymbol.ToTestDisplayString()) Assert.Equal(New String() {"ITest(Of (a As System.Int32, b As System.Int32))", "ITest(Of T)"}, derivedSymbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString())) Dim instance1 = tree.GetRoot().DescendantNodes().OfType(Of VariableDeclaratorSyntax)().ElementAt(0).Names(0) Dim instance1Symbol = DirectCast(model.GetDeclaredSymbol(instance1), LocalSymbol).Type Assert.Equal("Derived(Of (notA As Integer, notB As Integer))", instance1Symbol.ToString()) Assert.Equal(New String() { "ITest(Of (a As System.Int32, b As System.Int32))", "ITest(Of (notA As System.Int32, notB As System.Int32))"}, instance1Symbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString())) Dim instance2 = tree.GetRoot().DescendantNodes().OfType(Of VariableDeclaratorSyntax)().ElementAt(1).Names(0) Dim instance2Symbol = DirectCast(model.GetDeclaredSymbol(instance2), LocalSymbol).Type Assert.Equal("Derived(Of (notA As String, notB As String))", instance2Symbol.ToString()) Assert.Equal(New String() { "ITest(Of (a As System.Int32, b As System.Int32))", "ITest(Of (notA As System.String, notB As System.String))"}, instance2Symbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString())) End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub GenericExplicitIEnumerableImplementationUsedWithDifferentTypesAndTupleNames() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections Imports System.Collections.Generic Class Base Implements IEnumerable(Of (a As Integer, b As Integer)) Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator Throw New Exception() End Function Function GetEnumerator2() As IEnumerator(Of (a As Integer, b As Integer)) Implements IEnumerable(Of (a As Integer, b As Integer)).GetEnumerator Throw New Exception() End Function End Class Class Derived(Of T) Inherits Base Implements IEnumerable(Of T) Public Dim state As T Function GetEnumerator3() As IEnumerator Implements IEnumerable.GetEnumerator Throw New Exception() End Function Function GetEnumerator4() As IEnumerator(Of T) Implements IEnumerable(Of T).GetEnumerator Return New DerivedEnumerator With {.state = state} End Function Public Class DerivedEnumerator Implements IEnumerator(Of T) Public Dim state As T Dim done As Boolean = False Function MoveNext() As Boolean Implements IEnumerator.MoveNext If done Then Return False Else done = True Return True End If End Function ReadOnly Property Current As T Implements IEnumerator(Of T).Current Get Return state End Get End Property ReadOnly Property Current2 As Object Implements IEnumerator.Current Get Throw New Exception() End Get End Property Public Sub Dispose() Implements IDisposable.Dispose End Sub Public Sub Reset() Implements IEnumerator.Reset End Sub End Class End Class Module M Sub Main() Dim collection = New Derived(Of (notA As String, notB As String)) With {.state = (42, 43)} For Each x In collection Console.Write(x.notA) Next End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) compilation.AssertTheseDiagnostics(<errors> BC32096: 'For Each' on type 'Derived(Of (notA As String, notB As String))' is ambiguous because the type implements multiple instantiations of 'System.Collections.Generic.IEnumerable(Of T)'. For Each x In collection ~~~~~~~~~~ </errors>) End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub GenericExplicitIEnumerableImplementationUsedWithDifferentTupleNames() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections Imports System.Collections.Generic Class Base Implements IEnumerable(Of (a As Integer, b As Integer)) Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator Throw New Exception() End Function Function GetEnumerator2() As IEnumerator(Of (a As Integer, b As Integer)) Implements IEnumerable(Of (a As Integer, b As Integer)).GetEnumerator Throw New Exception() End Function End Class Class Derived(Of T) Inherits Base Implements IEnumerable(Of T) Public Dim state As T Function GetEnumerator3() As IEnumerator Implements IEnumerable.GetEnumerator Throw New Exception() End Function Function GetEnumerator4() As IEnumerator(Of T) Implements IEnumerable(Of T).GetEnumerator Return New DerivedEnumerator With {.state = state} End Function Public Class DerivedEnumerator Implements IEnumerator(Of T) Public Dim state As T Dim done As Boolean = False Function MoveNext() As Boolean Implements IEnumerator.MoveNext If done Then Return False Else done = True Return True End If End Function ReadOnly Property Current As T Implements IEnumerator(Of T).Current Get Return state End Get End Property ReadOnly Property Current2 As Object Implements IEnumerator.Current Get Throw New Exception() End Get End Property Public Sub Dispose() Implements IDisposable.Dispose End Sub Public Sub Reset() Implements IEnumerator.Reset End Sub End Class End Class Module M Sub Main() Dim collection = New Derived(Of (notA As Integer, notB As Integer)) With {.state = (42, 43)} For Each x In collection Console.Write(x.notA) Next End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) compilation.AssertTheseDiagnostics() CompileAndVerify(compilation, expectedOutput:="42") End Sub <Fact()> <WorkItem(14843, "https://github.com/dotnet/roslyn/issues/14843")> Public Sub TupleNameDifferencesIgnoredInConstraintWhenNotIdentityConversion() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Interface I1(Of T) End Interface Class Base(Of U As I1(Of (a As Integer, b As Integer))) End Class Class Derived Inherits Base(Of I1(Of (notA As Integer, notB As Integer))) End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() End Sub <Fact()> <WorkItem(14843, "https://github.com/dotnet/roslyn/issues/14843")> Public Sub TupleNameDifferencesIgnoredInConstraintWhenNotIdentityConversion2() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Interface I1(Of T) End Interface Interface I2(Of T) Inherits I1(Of T) End Interface Class Base(Of U As I1(Of (a As Integer, b As Integer))) End Class Class Derived Inherits Base(Of I2(Of (notA As Integer, notB As Integer))) End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub CanReImplementInterfaceWithDifferentTupleNames() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Interface ITest(Of T) Function M() As T End Interface Class Base Implements ITest(Of (a As Integer, b As Integer)) Function M() As (a As Integer, b As Integer) Implements ITest(Of (a As Integer, b As Integer)).M Return (1, 2) End Function End Class Class Derived Inherits Base Implements ITest(Of (notA As Integer, notB As Integer)) Overloads Function M() As (notA As Integer, notB As Integer) Implements ITest(Of (notA As Integer, notB As Integer)).M Return (3, 4) End Function End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_01() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Interface ITest(Of T) Function M() As T End Interface Class Base Implements ITest(Of (a As Integer, b As Integer)) Function M() As (a As Integer, b As Integer) Implements ITest(Of (a As Integer, b As Integer)).M Return (1, 2) End Function End Class Class Derived1 Inherits Base Implements ITest(Of (notA As Integer, notB As Integer)) End Class Class Derived2 Inherits Base Implements ITest(Of (a As Integer, b As Integer)) End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics(<errors> BC30149: Class 'Derived1' must implement 'Function M() As (notA As Integer, notB As Integer)' for interface 'ITest(Of (notA As Integer, notB As Integer))'. Implements ITest(Of (notA As Integer, notB As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_02() Dim csSource = " public interface ITest<T> { T M(); } public class Base : ITest<(int a, int b)> { (int a, int b) ITest<(int a, int b)>.M() { return (1, 2); } // explicit implementation public virtual (int notA, int notB) M() { return (1, 2); } } " Dim csComp = CreateCSharpCompilation(csSource, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedAssemblies:=TargetFrameworkUtil.GetReferences(TargetFramework.StandardAndVBRuntime)) csComp.VerifyDiagnostics() Dim comp = CreateCompilation( <compilation> <file name="a.vb"><![CDATA[ Class Derived1 Inherits Base Implements ITest(Of (notA As Integer, notB As Integer)) End Class Class Derived2 Inherits Base Implements ITest(Of (a As Integer, b As Integer)) End Class ]]></file> </compilation>, references:={csComp.EmitToImageReference()}) comp.AssertTheseDiagnostics(<errors> BC30149: Class 'Derived1' must implement 'Function M() As (notA As Integer, notB As Integer)' for interface 'ITest(Of (notA As Integer, notB As Integer))'. Implements ITest(Of (notA As Integer, notB As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) Dim derived1 As INamedTypeSymbol = comp.GetTypeByMetadataName("Derived1") Assert.Equal("ITest(Of (notA As System.Int32, notB As System.Int32))", derived1.Interfaces(0).ToTestDisplayString()) Dim derived2 As INamedTypeSymbol = comp.GetTypeByMetadataName("Derived2") Assert.Equal("ITest(Of (a As System.Int32, b As System.Int32))", derived2.Interfaces(0).ToTestDisplayString()) Dim m = comp.GetTypeByMetadataName("Base").GetMembers("ITest<(System.Int32a,System.Int32b)>.M").Single() Dim mImplementations = DirectCast(m, IMethodSymbol).ExplicitInterfaceImplementations Assert.Equal(1, mImplementations.Length) Assert.Equal("Function ITest(Of (System.Int32, System.Int32)).M() As (System.Int32, System.Int32)", mImplementations(0).ToTestDisplayString()) Assert.Same(m, derived1.FindImplementationForInterfaceMember(DirectCast(derived1.Interfaces(0), TypeSymbol).GetMember("M"))) Assert.Same(m, derived1.FindImplementationForInterfaceMember(DirectCast(derived2.Interfaces(0), TypeSymbol).GetMember("M"))) Assert.Same(m, derived2.FindImplementationForInterfaceMember(DirectCast(derived1.Interfaces(0), TypeSymbol).GetMember("M"))) Assert.Same(m, derived2.FindImplementationForInterfaceMember(DirectCast(derived2.Interfaces(0), TypeSymbol).GetMember("M"))) End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_03() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Interface ITest(Of T) Function M() As T End Interface Class Base Implements ITest(Of (a As Integer, b As Integer)) End Class Class Derived1 Inherits Base Implements ITest(Of (notA As Integer, notB As Integer)) End Class Class Derived2 Inherits Base Implements ITest(Of (a As Integer, b As Integer)) End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics(<errors> BC30149: Class 'Base' must implement 'Function M() As (a As Integer, b As Integer)' for interface 'ITest(Of (a As Integer, b As Integer))'. Implements ITest(Of (a As Integer, b As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30149: Class 'Derived1' must implement 'Function M() As (notA As Integer, notB As Integer)' for interface 'ITest(Of (notA As Integer, notB As Integer))'. Implements ITest(Of (notA As Integer, notB As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_04() Dim compilation1 = CreateCompilation( <compilation> <file name="a.vb"><![CDATA[ Public Interface ITest(Of T) Function M() As T End Interface Public Class Base Implements ITest(Of (a As Integer, b As Integer)) End Class ]]></file> </compilation>) compilation1.AssertTheseDiagnostics(<errors> BC30149: Class 'Base' must implement 'Function M() As (a As Integer, b As Integer)' for interface 'ITest(Of (a As Integer, b As Integer))'. Implements ITest(Of (a As Integer, b As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) Dim compilation2 = CreateCompilation( <compilation> <file name="a.vb"><![CDATA[ Class Derived1 Inherits Base Implements ITest(Of (notA As Integer, notB As Integer)) End Class Class Derived2 Inherits Base Implements ITest(Of (a As Integer, b As Integer)) End Class ]]></file> </compilation>, references:={compilation1.ToMetadataReference()}) compilation2.AssertTheseDiagnostics(<errors> BC30149: Class 'Derived1' must implement 'Function M() As (notA As Integer, notB As Integer)' for interface 'ITest(Of (notA As Integer, notB As Integer))'. Implements ITest(Of (notA As Integer, notB As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_05() Dim csSource = " public interface ITest<T> { T M(); } public class Base : ITest<(int a, int b)> { public virtual (int a, int b) M() { return (1, 2); } } " Dim csComp = CreateCSharpCompilation(csSource, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedAssemblies:=TargetFrameworkUtil.GetReferences(TargetFramework.StandardAndVBRuntime)) csComp.VerifyDiagnostics() Dim comp = CreateCompilation( <compilation> <file name="a.vb"><![CDATA[ Class Derived1 Inherits Base Implements ITest(Of (notA As Integer, notB As Integer)) End Class Class Derived2 Inherits Base Implements ITest(Of (a As Integer, b As Integer)) End Class ]]></file> </compilation>, references:={csComp.EmitToImageReference()}) comp.AssertTheseDiagnostics(<errors> BC30149: Class 'Derived1' must implement 'Function M() As (notA As Integer, notB As Integer)' for interface 'ITest(Of (notA As Integer, notB As Integer))'. Implements ITest(Of (notA As Integer, notB As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) Dim derived1 As INamedTypeSymbol = comp.GetTypeByMetadataName("Derived1") Assert.Equal("ITest(Of (notA As System.Int32, notB As System.Int32))", derived1.Interfaces(0).ToTestDisplayString()) Dim derived2 As INamedTypeSymbol = comp.GetTypeByMetadataName("Derived2") Assert.Equal("ITest(Of (a As System.Int32, b As System.Int32))", derived2.Interfaces(0).ToTestDisplayString()) Dim m = comp.GetTypeByMetadataName("Base").GetMember("M") Dim mImplementations = DirectCast(m, IMethodSymbol).ExplicitInterfaceImplementations Assert.Equal(0, mImplementations.Length) Assert.Same(m, derived1.FindImplementationForInterfaceMember(DirectCast(derived1.Interfaces(0), TypeSymbol).GetMember("M"))) Assert.Same(m, derived1.FindImplementationForInterfaceMember(DirectCast(derived2.Interfaces(0), TypeSymbol).GetMember("M"))) Assert.Same(m, derived2.FindImplementationForInterfaceMember(DirectCast(derived1.Interfaces(0), TypeSymbol).GetMember("M"))) Assert.Same(m, derived2.FindImplementationForInterfaceMember(DirectCast(derived2.Interfaces(0), TypeSymbol).GetMember("M"))) End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub ReImplementationAndInference() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Interface ITest(Of T) Function M() As T End Interface Class Base Implements ITest(Of (a As Integer, b As Integer)) Function M() As (a As Integer, b As Integer) Implements ITest(Of (a As Integer, b As Integer)).M Return (1, 2) End Function End Class Class Derived Inherits Base Implements ITest(Of (notA As Integer, notB As Integer)) Overloads Function M() As (notA As Integer, notB As Integer) Implements ITest(Of (notA As Integer, notB As Integer)).M Return (3, 4) End Function End Class Class C Shared Sub Main() Dim b As Base = New Derived() Dim x = Test(b) ' tuple names from Base, implementation from Derived System.Console.WriteLine(x.a) End Sub Shared Function Test(Of T)(t1 As ITest(Of T)) As T Return t1.M() End Function End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics() CompileAndVerify(comp, expectedOutput:="3") Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(1).Names(0) Assert.Equal("x", x.Identifier.ToString()) Dim xSymbol = DirectCast(model.GetDeclaredSymbol(x), LocalSymbol).Type Assert.Equal("(a As System.Int32, b As System.Int32)", xSymbol.ToTestDisplayString()) End Sub <Fact()> <WorkItem(14091, "https://github.com/dotnet/roslyn/issues/14091")> Public Sub TupleTypeWithTooFewElements() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M(x As Integer, y As (), z As (a As Integer)) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics(<errors> BC30182: Type expected. Shared Sub M(x As Integer, y As (), z As (a As Integer)) ~ BC37259: Tuple must contain at least two elements. Shared Sub M(x As Integer, y As (), z As (a As Integer)) ~ BC37259: Tuple must contain at least two elements. Shared Sub M(x As Integer, y As (), z As (a As Integer)) ~ </errors>) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim y = nodes.OfType(Of TupleTypeSyntax)().ElementAt(0) Assert.Equal("()", y.ToString()) Dim yType = model.GetTypeInfo(y) Assert.Equal("(?, ?)", yType.Type.ToTestDisplayString()) Dim z = nodes.OfType(Of TupleTypeSyntax)().ElementAt(1) Assert.Equal("(a As Integer)", z.ToString()) Dim zType = model.GetTypeInfo(z) Assert.Equal("(a As System.Int32, ?)", zType.Type.ToTestDisplayString()) End Sub <Fact()> <WorkItem(14091, "https://github.com/dotnet/roslyn/issues/14091")> Public Sub TupleExpressionWithTooFewElements() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class C Dim x = (Alice:=1) End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics(<errors> BC37259: Tuple must contain at least two elements. Dim x = (Alice:=1) ~ </errors>) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim tuple = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(0) Assert.Equal("(Alice:=1)", tuple.ToString()) Dim tupleType = model.GetTypeInfo(tuple) Assert.Equal("(Alice As System.Int32, ?)", tupleType.Type.ToTestDisplayString()) End Sub <Fact> Public Sub GetWellKnownTypeWithAmbiguities() Const versionTemplate = "<Assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")>" Const corlib_vb = " Namespace System Public Class [Object] End Class Public Structure Void End Structure Public Class ValueType End Class Public Structure IntPtr End Structure Public Structure Int32 End Structure Public Class [String] End Class Public Class Attribute End Class End Namespace Namespace System.Reflection Public Class AssemblyVersionAttribute Inherits Attribute Public Sub New(version As String) End Sub End Class End Namespace " Const valuetuple_vb As String = " Namespace System Public Structure ValueTuple(Of T1, T2) Public Dim Item1 As T1 Public Dim Item2 As T2 Public Sub New(item1 As T1, item2 As T2) End Sub End Structure End Namespace " Dim corlibWithoutVT = CreateEmptyCompilation({String.Format(versionTemplate, "1") + corlib_vb}, options:=TestOptions.DebugDll, assemblyName:="corlib") corlibWithoutVT.AssertTheseDiagnostics() Dim corlibWithoutVTRef = corlibWithoutVT.EmitToImageReference() Dim corlibWithVT = CreateEmptyCompilation({String.Format(versionTemplate, "2") + corlib_vb + valuetuple_vb}, options:=TestOptions.DebugDll, assemblyName:="corlib") corlibWithVT.AssertTheseDiagnostics() Dim corlibWithVTRef = corlibWithVT.EmitToImageReference() Dim libWithVT = CreateEmptyCompilation(valuetuple_vb, references:={corlibWithoutVTRef}, options:=TestOptions.DebugDll) libWithVT.VerifyDiagnostics() Dim libWithVTRef = libWithVT.EmitToImageReference() Dim comp = VisualBasicCompilation.Create("test", references:={libWithVTRef, corlibWithVTRef}) Dim found = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2) Assert.False(found.IsErrorType()) Assert.Equal("corlib", found.ContainingAssembly.Name) Dim comp2 = comp.WithOptions(comp.Options.WithIgnoreCorLibraryDuplicatedTypes(True)) Dim tuple2 = comp2.GetWellKnownType(WellKnownType.System_ValueTuple_T2) Assert.False(tuple2.IsErrorType()) Assert.Equal(libWithVTRef.Display, tuple2.ContainingAssembly.MetadataName.ToString()) Dim comp3 = VisualBasicCompilation.Create("test", references:={corlibWithVTRef, libWithVTRef}). ' order reversed WithOptions(comp.Options.WithIgnoreCorLibraryDuplicatedTypes(True)) Dim tuple3 = comp3.GetWellKnownType(WellKnownType.System_ValueTuple_T2) Assert.False(tuple3.IsErrorType()) Assert.Equal(libWithVTRef.Display, tuple3.ContainingAssembly.MetadataName.ToString()) End Sub <Fact> Public Sub CheckedConversions() Dim source = <compilation> <file> Imports System Class C Shared Function F(t As (Integer, Integer)) As (Long, Byte) Return CType(t, (Long, Byte)) End Function Shared Sub Main() Try Dim t = F((-1, -1)) Console.WriteLine(t) Catch e As OverflowException Console.WriteLine("overflow") End Try End Sub End Class </file> </compilation> Dim verifier = CompileAndVerify( source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(-1, 255)]]>) verifier.VerifyIL("C.F", <![CDATA[ { // Code size 22 (0x16) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer) V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0008: conv.i8 IL_0009: ldloc.0 IL_000a: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_000f: conv.u1 IL_0010: newobj "Sub System.ValueTuple(Of Long, Byte)..ctor(Long, Byte)" IL_0015: ret } ]]>) verifier = CompileAndVerify( source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True), references:=s_valueTupleRefs, expectedOutput:=<![CDATA[overflow]]>) verifier.VerifyIL("C.F", <![CDATA[ { // Code size 22 (0x16) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer) V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0008: conv.i8 IL_0009: ldloc.0 IL_000a: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_000f: conv.ovf.u1 IL_0010: newobj "Sub System.ValueTuple(Of Long, Byte)..ctor(Long, Byte)" IL_0015: ret } ]]>) End Sub <Fact> <WorkItem(18738, "https://github.com/dotnet/roslyn/issues/18738")> Public Sub TypelessTupleWithNoImplicitConversion() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> option strict on Imports System Module C Sub M() Dim e As Integer? = 5 Dim x as (Integer, String) = (e, Nothing) ' No implicit conversion System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics(<errors> BC30512: Option Strict On disallows implicit conversions from 'Integer?' to 'Integer'. Dim x as (Integer, String) = (e, Nothing) ' No implicit conversion ~ </errors>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e, Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.NarrowingTuple, model.GetConversion(node).Kind) End Sub <Fact> <WorkItem(18738, "https://github.com/dotnet/roslyn/issues/18738")> Public Sub TypelessTupleWithNoImplicitConversion2() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> option strict on Imports System Module C Sub M() Dim e As Integer? = 5 Dim x as (Integer, String, Integer) = (e, Nothing) ' No conversion System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics(<errors> BC30311: Value of type '(e As Integer?, Object)' cannot be converted to '(Integer, String, Integer)'. Dim x as (Integer, String, Integer) = (e, Nothing) ' No conversion ~~~~~~~~~~~~ </errors>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e, Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Assert.Equal("(System.Int32, System.String, System.Int32)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.DelegateRelaxationLevelNone, model.GetConversion(node).Kind) End Sub <Fact> <WorkItem(18738, "https://github.com/dotnet/roslyn/issues/18738")> Public Sub TypedTupleWithNoImplicitConversion() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> option strict on Imports System Module C Sub M() Dim e As Integer? = 5 Dim x as (Integer, String, Integer) = (e, "") ' No conversion System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics(<errors> BC30311: Value of type '(e As Integer?, String)' cannot be converted to '(Integer, String, Integer)'. Dim x as (Integer, String, Integer) = (e, "") ' No conversion ~~~~~~~ </errors>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e, """")", node.ToString()) Assert.Equal("(e As System.Nullable(Of System.Int32), System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(System.Int32, System.String, System.Int32)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.DelegateRelaxationLevelNone, model.GetConversion(node).Kind) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> Public Sub MoreGenericTieBreaker_01() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Module Module1 Public Sub Main() Dim a As A(Of A(Of Integer)) = Nothing M1(a) ' ok, selects M1(Of T)(A(Of A(Of T)) a) Dim b = New ValueTuple(Of ValueTuple(Of Integer, Integer), Integer)() M2(b) ' ok, should select M2(Of T)(ValueTuple(Of ValueTuple(Of T, Integer), Integer) a) End Sub Public Sub M1(Of T)(a As A(Of T)) Console.Write(1) End Sub Public Sub M1(Of T)(a As A(Of A(Of T))) Console.Write(2) End Sub Public Sub M2(Of T)(a As ValueTuple(Of T, Integer)) Console.Write(3) End Sub Public Sub M2(Of T)(a As ValueTuple(Of ValueTuple(Of T, Integer), Integer)) Console.Write(4) End Sub End Module Public Class A(Of T) End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ 24 ]]>) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> Public Sub MoreGenericTieBreaker_01b() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Module Module1 Public Sub Main() Dim b = ((0, 0), 0) M2(b) ' ok, should select M2(Of T)(ValueTuple(Of ValueTuple(Of T, Integer), Integer) a) End Sub Public Sub M2(Of T)(a As (T, Integer)) Console.Write(3) End Sub Public Sub M2(Of T)(a As ((T, Integer), Integer)) Console.Write(4) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ 4 ]]>) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> <WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")> Public Sub MoreGenericTieBreaker_02a1() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports int = System.Int32 Module Module1 Public Sub Main() ' Dim b = (1, 2, 3, 4, 5, 6, 7, 8) Dim b = new ValueTuple(Of int, int, int, int, int, int, int, ValueTuple(Of int))(1, 2, 3, 4, 5, 6, 7, new ValueTuple(Of int)(8)) M1(b) M2(b) End Sub Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest as Structure)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest)) Console.Write(1) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, T8)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, ValueTuple(Of T8))) Console.Write(2) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest)) Console.Write(3) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ 12 ]]>) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> <WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")> Public Sub MoreGenericTieBreaker_02a2() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports int = System.Int32 Module Module1 Public Sub Main() ' Dim b = (1, 2, 3, 4, 5, 6, 7, 8) Dim b = new ValueTuple(Of int, int, int, int, int, int, int, ValueTuple(Of int))(1, 2, 3, 4, 5, 6, 7, new ValueTuple(Of int)(8)) M1(b) M2(b) End Sub Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest as Structure)(ByRef a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest)) Console.Write(1) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, T8)(ByRef a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, ValueTuple(Of T8))) Console.Write(2) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(ByRef a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest)) Console.Write(3) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ 12 ]]>) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> <WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")> Public Sub MoreGenericTieBreaker_02a3() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports int = System.Int32 Module Module1 Public Sub Main() Dim b As I(Of ValueTuple(Of int, int, int, int, int, int, int, ValueTuple(Of int))) = Nothing M1(b) M2(b) End Sub Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest as Structure)(a As I(Of ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest))) Console.Write(1) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, T8)(a As I(Of ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, ValueTuple(Of T8)))) Console.Write(2) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(a As I(Of ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest))) Console.Write(3) End Sub End Module Interface I(Of in T) End Interface </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ 12 ]]>) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> <WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")> Public Sub MoreGenericTieBreaker_02a4() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports int = System.Int32 Module Module1 Public Sub Main() Dim b As I(Of ValueTuple(Of int, int, int, int, int, int, int, ValueTuple(Of int))) = Nothing M1(b) M2(b) End Sub Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest as Structure)(a As I(Of ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest))) Console.Write(1) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, T8)(a As I(Of ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, ValueTuple(Of T8)))) Console.Write(2) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(a As I(Of ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest))) Console.Write(3) End Sub End Module Interface I(Of out T) End Interface </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ 12 ]]>) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> <WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")> Public Sub MoreGenericTieBreaker_02a5() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports int = System.Int32 Module Module1 Public Sub Main() M1((1, 2, 3, 4, 5, 6, 7, 8)) M2((1, 2, 3, 4, 5, 6, 7, 8)) End Sub Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest as Structure)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest)) Console.Write(1) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, T8)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, ValueTuple(Of T8))) Console.Write(2) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest)) Console.Write(3) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ 12 ]]>) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> <WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")> Public Sub MoreGenericTieBreaker_02a6() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports int = System.Int32 Module Module1 Public Sub Main() M2((Function() 1, Function() 2, Function() 3, Function() 4, Function() 5, Function() 6, Function() 7, Function() 8)) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, T8)(a As ValueTuple(Of Func(Of T1), Func(Of T2), Func(Of T3), Func(Of T4), Func(Of T5), Func(Of T6), Func(Of T7), ValueTuple(Of Func(Of T8)))) Console.Write(2) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(a As ValueTuple(Of Func(Of T1), Func(Of T2), Func(Of T3), Func(Of T4), Func(Of T5), Func(Of T6), Func(Of T7), TRest)) Console.Write(3) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ 2 ]]>) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> <WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")> Public Sub MoreGenericTieBreaker_02a7() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Imports int = System.Int32 Module Module1 Public Sub Main() M1((Function() 1, Function() 2, Function() 3, Function() 4, Function() 5, Function() 6, Function() 7, Function() 8)) End Sub Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest as Structure)(a As ValueTuple(Of Func(Of T1), Func(Of T2), Func(Of T3), Func(Of T4), Func(Of T5), Func(Of T6), Func(Of T7), TRest)) Console.Write(1) End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <expected> BC36645: Data type(s) of the type parameter(s) in method 'Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(a As ValueTuple(Of Func(Of T1), Func(Of T2), Func(Of T3), Func(Of T4), Func(Of T5), Func(Of T6), Func(Of T7), TRest))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. M1((Function() 1, Function() 2, Function() 3, Function() 4, Function() 5, Function() 6, Function() 7, Function() 8)) ~~ </expected> ) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> <WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")> Public Sub MoreGenericTieBreaker_02b() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports int = System.Int32 Module Module1 Public Sub Main() Dim b = (1, 2, 3, 4, 5, 6, 7, 8) M1(b) M2(b) End Sub Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest as Structure)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest)) Console.Write(1) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, T8)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, ValueTuple(Of T8))) Console.Write(2) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest)) Console.Write(3) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ 12 ]]>) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> Public Sub MoreGenericTieBreaker_03() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Module Module1 Public Sub Main() Dim b = ((1, 1), 2, 3, 4, 5, 6, 7, 8, 9, (10, 10), (11, 11)) M1(b) ' ok, should select M1(Of T, U, V)(a As ((T, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, (U, Integer), V)) End Sub Sub M1(Of T, U, V)(a As ((T, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, (U, Integer), V)) Console.Write(3) End Sub Sub M1(Of T, U, V)(a As (T, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, U, (V, Integer))) Console.Write(4) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ 3 ]]>) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> Public Sub MoreGenericTieBreaker_04() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Module Module1 Public Sub Main() Dim b = ((1, 1), 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, (20, 20)) M1(b) ' error: ambiguous End Sub Sub M1(Of T, U)(a As (T, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, (U, Integer))) Console.Write(3) End Sub Sub M1(Of T, U)(a As ((T, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, U)) Console.Write(4) End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:=s_valueTupleRefs) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_NoMostSpecificOverload2, "M1").WithArguments("M1", " 'Public Sub M1(Of (Integer, Integer), Integer)(a As ((Integer, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer)))': Not most specific. 'Public Sub M1(Of Integer, (Integer, Integer))(a As ((Integer, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer)))': Not most specific.").WithLocation(7, 9) ) End Sub <Fact> <WorkItem(21785, "https://github.com/dotnet/roslyn/issues/21785")> Public Sub TypelessTupleInArrayInitializer() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Module1 Private mTupleArray As (X As Integer, P As System.Func(Of Byte(), Integer))() = { (X:=0, P:=Nothing), (X:=0, P:=AddressOf MyFunction) } Sub Main() System.Console.Write(mTupleArray(1).P(Nothing)) End Sub Public Function MyFunction(ArgBytes As Byte()) As Integer Return 1 End Function End Module </file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertNoDiagnostics() CompileAndVerify(comp, expectedOutput:="1") Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(1) Assert.Equal("(X:=0, P:=AddressOf MyFunction)", node.ToString()) Dim tupleSymbol = model.GetTypeInfo(node) Assert.Null(tupleSymbol.Type) Assert.Equal("(X As System.Int32, P As System.Func(Of System.Byte(), System.Int32))", tupleSymbol.ConvertedType.ToTestDisplayString()) End Sub <Fact> <WorkItem(21785, "https://github.com/dotnet/roslyn/issues/21785")> Public Sub TypelessTupleInArrayInitializerWithInferenceFailure() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Module1 Private mTupleArray = { (X:=0, P:=AddressOf MyFunction) } Sub Main() System.Console.Write(mTupleArray(1).P(Nothing)) End Sub Public Function MyFunction(ArgBytes As Byte()) As Integer Return 1 End Function End Module </file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics(<errors> BC30491: Expression does not produce a value. Private mTupleArray = { (X:=0, P:=AddressOf MyFunction) } ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(0) Assert.Equal("(X:=0, P:=AddressOf MyFunction)", node.ToString()) Dim tupleSymbol = model.GetTypeInfo(node) Assert.Null(tupleSymbol.Type) Assert.Equal("System.Object", tupleSymbol.ConvertedType.ToTestDisplayString()) End Sub <Fact> <WorkItem(21785, "https://github.com/dotnet/roslyn/issues/21785")> Public Sub TypelessTupleInArrayInitializerWithInferenceSuccess() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim y As MyDelegate = AddressOf MyFunction Dim mTupleArray = { (X:=0, P:=y), (X:=0, P:=AddressOf MyFunction) } System.Console.Write(mTupleArray(1).P(Nothing)) End Sub Delegate Function MyDelegate(ArgBytes As Byte()) As Integer Public Function MyFunction(ArgBytes As Byte()) As Integer Return 1 End Function End Module </file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertNoDiagnostics() CompileAndVerify(comp, expectedOutput:="1") Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(1) Assert.Equal("(X:=0, P:=AddressOf MyFunction)", node.ToString()) Dim tupleSymbol = model.GetTypeInfo(node) Assert.Null(tupleSymbol.Type) Assert.Equal("(X As System.Int32, P As Module1.MyDelegate)", tupleSymbol.ConvertedType.ToTestDisplayString()) End Sub <Fact> <WorkItem(24781, "https://github.com/dotnet/roslyn/issues/24781")> Public Sub InferenceWithTuple() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Interface IAct(Of T) Function Act(Of TReturn)(fn As Func(Of T, TReturn)) As IResult(Of TReturn) End Interface Public Interface IResult(Of TReturn) End Interface Module Module1 Sub M(impl As IAct(Of (Integer, Integer))) Dim case3 = impl.Act(Function(a As (x As Integer, y As Integer)) a.x * a.y) End Sub End Module </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics() Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim actSyntax = nodes.OfType(Of InvocationExpressionSyntax)().Single() Assert.Equal("impl.Act(Function(a As (x As Integer, y As Integer)) a.x * a.y)", actSyntax.ToString()) Dim actSymbol = DirectCast(model.GetSymbolInfo(actSyntax).Symbol, IMethodSymbol) Assert.Equal("IResult(Of System.Int32)", actSymbol.ReturnType.ToTestDisplayString()) End Sub <Fact> <WorkItem(21727, "https://github.com/dotnet/roslyn/issues/21727")> Public Sub FailedDecodingOfTupleNamesWhenMissingValueTupleType() Dim vtLib = CreateEmptyCompilation(s_trivial2uple, references:={MscorlibRef}, assemblyName:="vt") Dim libComp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System.Collections.Generic Imports System.Collections Public Class ClassA Implements IEnumerable(Of (alice As Integer, bob As Integer)) Function GetGenericEnumerator() As IEnumerator(Of (alice As Integer, bob As Integer)) Implements IEnumerable(Of (alice As Integer, bob As Integer)).GetEnumerator Return Nothing End Function Function GetEnumerator() As IEnumerator Implements IEnumerable(Of (alice As Integer, bob As Integer)).GetEnumerator Return Nothing End Function End Class </file> </compilation>, additionalRefs:={vtLib.EmitToImageReference()}) libComp.VerifyDiagnostics() Dim source As Xml.Linq.XElement = <compilation> <file name="a.vb"> Class ClassB Sub M() Dim x = New ClassA() x.ToString() End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={libComp.EmitToImageReference()}) ' missing reference to vt comp.AssertNoDiagnostics() FailedDecodingOfTupleNamesWhenMissingValueTupleType_Verify(comp, successfulDecoding:=False) Dim compWithMetadataReference = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={libComp.ToMetadataReference()}) ' missing reference to vt compWithMetadataReference.AssertNoDiagnostics() FailedDecodingOfTupleNamesWhenMissingValueTupleType_Verify(compWithMetadataReference, successfulDecoding:=True) Dim fakeVtLib = CreateEmptyCompilation("", references:={MscorlibRef}, assemblyName:="vt") Dim compWithFakeVt = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={libComp.EmitToImageReference(), fakeVtLib.EmitToImageReference()}) ' reference to fake vt compWithFakeVt.AssertNoDiagnostics() FailedDecodingOfTupleNamesWhenMissingValueTupleType_Verify(compWithFakeVt, successfulDecoding:=False) Dim source2 As Xml.Linq.XElement = <compilation> <file name="a.vb"> Class ClassB Sub M() Dim x = New ClassA().GetGenericEnumerator() For Each i In New ClassA() System.Console.Write(i.alice) Next End Sub End Class </file> </compilation> Dim comp2 = CreateCompilationWithMscorlib40AndVBRuntime(source2, additionalRefs:={libComp.EmitToImageReference()}) ' missing reference to vt comp2.AssertTheseDiagnostics(<errors> BC30652: Reference required to assembly 'vt, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'ValueTuple(Of ,)'. Add one to your project. Dim x = New ClassA().GetGenericEnumerator() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) FailedDecodingOfTupleNamesWhenMissingValueTupleType_Verify(comp2, successfulDecoding:=False) Dim comp2WithFakeVt = CreateCompilationWithMscorlib40AndVBRuntime(source2, additionalRefs:={libComp.EmitToImageReference(), fakeVtLib.EmitToImageReference()}) ' reference to fake vt comp2WithFakeVt.AssertTheseDiagnostics(<errors> BC31091: Import of type 'ValueTuple(Of ,)' from assembly or module 'vt.dll' failed. Dim x = New ClassA().GetGenericEnumerator() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) FailedDecodingOfTupleNamesWhenMissingValueTupleType_Verify(comp2WithFakeVt, successfulDecoding:=False) End Sub Private Sub FailedDecodingOfTupleNamesWhenMissingValueTupleType_Verify(compilation As Compilation, successfulDecoding As Boolean) Dim classA = DirectCast(compilation.GetMember("ClassA"), NamedTypeSymbol) Dim iEnumerable = classA.Interfaces()(0) If successfulDecoding Then Assert.Equal("System.Collections.Generic.IEnumerable(Of (alice As System.Int32, bob As System.Int32))", iEnumerable.ToTestDisplayString()) Dim tuple = iEnumerable.TypeArguments()(0) Assert.Equal("(alice As System.Int32, bob As System.Int32)", tuple.ToTestDisplayString()) Assert.True(tuple.IsTupleType) Assert.True(tuple.TupleUnderlyingType.IsErrorType()) Else Assert.Equal("System.Collections.Generic.IEnumerable(Of System.ValueTuple(Of System.Int32, System.Int32)[missing])", iEnumerable.ToTestDisplayString()) Dim tuple = iEnumerable.TypeArguments()(0) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32)[missing]", tuple.ToTestDisplayString()) Assert.False(tuple.IsTupleType) End If End Sub <Fact> <WorkItem(21727, "https://github.com/dotnet/roslyn/issues/21727")> Public Sub FailedDecodingOfTupleNamesWhenMissingContainerType() Dim containerLib = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Container(Of T) Public Class Contained(Of U) End Class End Class </file> </compilation>) containerLib.VerifyDiagnostics() Dim libComp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System.Collections.Generic Imports System.Collections Public Class ClassA Implements IEnumerable(Of Container(Of (alice As Integer, bob As Integer)).Contained(Of (charlie As Integer, dylan as Integer))) Function GetGenericEnumerator() As IEnumerator(Of Container(Of (alice As Integer, bob As Integer)).Contained(Of (charlie As Integer, dylan as Integer))) _ Implements IEnumerable(Of Container(Of (alice As Integer, bob As Integer)).Contained(Of (charlie As Integer, dylan as Integer))).GetEnumerator Return Nothing End Function Function GetEnumerator() As IEnumerator Implements IEnumerable(Of Container(Of (alice As Integer, bob As Integer)).Contained(Of (charlie As Integer, dylan as Integer))).GetEnumerator Return Nothing End Function End Class </file> </compilation>, additionalRefs:={containerLib.EmitToImageReference(), ValueTupleRef, SystemRuntimeFacadeRef}) libComp.VerifyDiagnostics() Dim source As Xml.Linq.XElement = <compilation> <file name="a.vb"> Class ClassB Sub M() Dim x = New ClassA() x.ToString() End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={libComp.EmitToImageReference(), ValueTupleRef, SystemRuntimeFacadeRef}) ' missing reference to container comp.AssertNoDiagnostics() FailedDecodingOfTupleNamesWhenMissingContainerType_Verify(comp, decodingSuccessful:=False) Dim compWithMetadataReference = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={libComp.ToMetadataReference(), ValueTupleRef, SystemRuntimeFacadeRef}) ' missing reference to container compWithMetadataReference.AssertNoDiagnostics() FailedDecodingOfTupleNamesWhenMissingContainerType_Verify(compWithMetadataReference, decodingSuccessful:=True) Dim fakeContainerLib = CreateEmptyCompilation("", references:={MscorlibRef}, assemblyName:="vt") Dim compWithFakeVt = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={libComp.EmitToImageReference(), fakeContainerLib.EmitToImageReference(), ValueTupleRef, SystemRuntimeFacadeRef}) ' reference to fake container compWithFakeVt.AssertNoDiagnostics() FailedDecodingOfTupleNamesWhenMissingContainerType_Verify(compWithFakeVt, decodingSuccessful:=False) End Sub Private Sub FailedDecodingOfTupleNamesWhenMissingContainerType_Verify(compilation As Compilation, decodingSuccessful As Boolean) Dim classA = DirectCast(compilation.GetMember("ClassA"), NamedTypeSymbol) Dim iEnumerable = classA.Interfaces()(0) Dim tuple = DirectCast(iEnumerable.TypeArguments()(0), NamedTypeSymbol).TypeArguments()(0) If decodingSuccessful Then Assert.Equal("System.Collections.Generic.IEnumerable(Of Container(Of (alice As System.Int32, bob As System.Int32))[missing].Contained(Of (charlie As System.Int32, dylan As System.Int32))[missing])", iEnumerable.ToTestDisplayString()) Assert.Equal("(charlie As System.Int32, dylan As System.Int32)", tuple.ToTestDisplayString()) Assert.True(tuple.IsTupleType) Assert.False(tuple.TupleUnderlyingType.IsErrorType()) Else Assert.Equal("System.Collections.Generic.IEnumerable(Of Container(Of System.ValueTuple(Of System.Int32, System.Int32))[missing].Contained(Of System.ValueTuple(Of System.Int32, System.Int32))[missing])", iEnumerable.ToTestDisplayString()) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32)", tuple.ToTestDisplayString()) Assert.False(tuple.IsTupleType) End If End Sub <Theory> <InlineData(True)> <InlineData(False)> <WorkItem(40033, "https://github.com/dotnet/roslyn/issues/40033")> Public Sub SynthesizeTupleElementNamesAttributeBasedOnInterfacesToEmit_IndirectInterfaces(ByVal useImageReferences As Boolean) Dim getReference As Func(Of Compilation, MetadataReference) = Function(c) If(useImageReferences, c.EmitToImageReference(), c.ToMetadataReference()) Dim valueTuple_source = " Namespace System Public Structure ValueTuple(Of T1, T2) Public Dim Item1 As T1 Public Dim Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return ""{"" + Item1?.ToString() + "", "" + Item2?.ToString() + ""}"" End Function End Structure End Namespace " Dim valueTuple_comp = CreateCompilationWithMscorlib40(valueTuple_source) Dim tupleElementNamesAttribute_comp = CreateCompilationWithMscorlib40(s_tupleattributes) tupleElementNamesAttribute_comp.AssertNoDiagnostics() Dim lib1_source = " Imports System.Threading.Tasks Public Interface I2(Of T, TResult) Function ExecuteAsync(parameter As T) As Task(Of TResult) End Interface Public Interface I1(Of T) Inherits I2(Of T, (a As Object, b As Object)) End Interface " Dim lib1_comp = CreateCompilationWithMscorlib40(lib1_source, references:={getReference(valueTuple_comp), getReference(tupleElementNamesAttribute_comp)}) lib1_comp.AssertNoDiagnostics() Dim lib2_source = " Public interface I0 Inherits I1(Of string) End Interface " Dim lib2_comp = CreateCompilationWithMscorlib40(lib2_source, references:={getReference(lib1_comp), getReference(valueTuple_comp)}) ' Missing TupleElementNamesAttribute lib2_comp.AssertNoDiagnostics() lib2_comp.AssertTheseEmitDiagnostics() Dim imc1 = CType(lib2_comp.GlobalNamespace.GetMember("I0"), TypeSymbol) AssertEx.SetEqual({"I1(Of System.String)"}, imc1.InterfacesNoUseSiteDiagnostics().Select(Function(i) i.ToTestDisplayString())) AssertEx.SetEqual({"I1(Of System.String)", "I2(Of System.String, (a As System.Object, b As System.Object))"}, imc1.AllInterfacesNoUseSiteDiagnostics.Select(Function(i) i.ToTestDisplayString())) Dim client_source = " Public Class C Public Sub M(imc As I0) imc.ExecuteAsync("""") End Sub End Class " Dim client_comp = CreateCompilationWithMscorlib40(client_source, references:={getReference(lib1_comp), getReference(lib2_comp), getReference(valueTuple_comp)}) client_comp.AssertNoDiagnostics() Dim imc2 = CType(client_comp.GlobalNamespace.GetMember("I0"), TypeSymbol) AssertEx.SetEqual({"I1(Of System.String)"}, imc2.InterfacesNoUseSiteDiagnostics().Select(Function(i) i.ToTestDisplayString())) AssertEx.SetEqual({"I1(Of System.String)", "I2(Of System.String, (a As System.Object, b As System.Object))"}, imc2.AllInterfacesNoUseSiteDiagnostics.Select(Function(i) i.ToTestDisplayString())) End Sub <Fact, WorkItem(40033, "https://github.com/dotnet/roslyn/issues/40033")> Public Sub SynthesizeTupleElementNamesAttributeBasedOnInterfacesToEmit_BaseAndDirectInterface() Dim source = " Namespace System Public Structure ValueTuple(Of T1, T2) Public Dim Item1 As T1 Public Dim Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return ""{"" + Item1?.ToString() + "", "" + Item2?.ToString() + ""}"" End Function End Structure End Namespace Namespace System.Runtime.CompilerServices Public Class TupleElementNamesAttribute Inherits Attribute Public Sub New() ' Note: bad signature End Sub End Class End Namespace Public Interface I(Of T) End Interface Public Class Base(Of T) End Class Public Class C1 Implements I(Of (a As Object, b As Object)) End Class Public Class C2 Inherits Base(Of (a As Object, b As Object)) End Class " Dim comp = CreateCompilationWithMscorlib40(source) comp.AssertTheseEmitDiagnostics(<errors><![CDATA[ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Implements I(Of (a As Object, b As Object)) ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Inherits Base(Of (a As Object, b As Object)) ~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Theory> <InlineData(True)> <InlineData(False)> <WorkItem(40430, "https://github.com/dotnet/roslyn/issues/40430")> Public Sub MissingTypeArgumentInBase_ValueTuple(useImageReference As Boolean) Dim lib_vb = " Public Class ClassWithTwoTypeParameters(Of T1, T2) End Class Public Class SelfReferencingClassWithTuple Inherits ClassWithTwoTypeParameters(Of SelfReferencingClassWithTuple, (A As String, B As Integer)) Sub New() System.Console.Write(""ran"") End Sub End Class " Dim library = CreateCompilationWithMscorlib40(lib_vb, references:=s_valueTupleRefs) library.VerifyDiagnostics() Dim libraryRef = If(useImageReference, library.EmitToImageReference(), library.ToMetadataReference()) Dim source_vb = " Public Class TriggerStackOverflowException Public Shared Sub Method() Dim x = New SelfReferencingClassWithTuple() End Sub End Class " Dim comp = CreateCompilationWithMscorlib40(source_vb, references:={libraryRef}) comp.VerifyEmitDiagnostics() Dim executable_vb = " Public Class C Public Shared Sub Main() TriggerStackOverflowException.Method() End Sub End Class " Dim executableComp = CreateCompilationWithMscorlib40(executable_vb, references:={comp.EmitToImageReference(), libraryRef, SystemRuntimeFacadeRef, ValueTupleRef}, options:=TestOptions.DebugExe) CompileAndVerify(executableComp, expectedOutput:="ran") End Sub <Fact> <WorkItem(41699, "https://github.com/dotnet/roslyn/issues/41699")> Public Sub MissingBaseType_TupleTypeArgumentWithNames() Dim sourceA = "Public Class A(Of T) End Class" Dim comp = CreateCompilation(sourceA, assemblyName:="A") Dim refA = comp.EmitToImageReference() Dim sourceB = "Public Class B Inherits A(Of (X As Object, Y As B)) End Class" comp = CreateCompilation(sourceB, references:={refA}) Dim refB = comp.EmitToImageReference() Dim sourceC = "Module Program Sub Main() Dim b = New B() b.ToString() End Sub End Module" comp = CreateCompilation(sourceC, references:={refB}) comp.AssertTheseDiagnostics( "BC30456: 'ToString' is not a member of 'B'. b.ToString() ~~~~~~~~~~ BC30652: Reference required to assembly 'A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'A(Of )'. Add one to your project. b.ToString() ~~~~~~~~~~") End Sub <Fact> <WorkItem(41207, "https://github.com/dotnet/roslyn/issues/41207")> <WorkItem(1056281, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056281")> Public Sub CustomFields_01() Dim source0 = " Namespace System Public Structure ValueTuple(Of T1, T2) Public Shared F1 As Integer = 123 Public Dim Item1 As T1 Public Dim Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return F1.ToString() End Function End Structure End Namespace " Dim source1 = " class Program public Shared Sub Main() System.Console.WriteLine((1,2).ToString()) End Sub End Class " Dim source2 = " class Program public Shared Sub Main() System.Console.WriteLine(System.ValueTuple(Of Integer, Integer).F1) End Sub End Class " Dim verifyField = Sub(comp As VisualBasicCompilation) Dim field = comp.GetMember(Of FieldSymbol)("System.ValueTuple.F1") Assert.Null(field.TupleUnderlyingField) Dim toEmit = field.ContainingType.GetFieldsToEmit().Where(Function(f) f.Name = "F1").Single() Assert.Same(field, toEmit) End Sub Dim comp1 = CreateCompilation(source0 + source1, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe) CompileAndVerify(comp1, expectedOutput:="123") verifyField(comp1) Dim comp1Ref = {comp1.ToMetadataReference()} Dim comp1ImageRef = {comp1.EmitToImageReference()} Dim comp4 = CreateCompilation(source0 + source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe) CompileAndVerify(comp4, expectedOutput:="123") Dim comp5 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1Ref) CompileAndVerify(comp5, expectedOutput:="123") verifyField(comp5) Dim comp6 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1ImageRef) CompileAndVerify(comp6, expectedOutput:="123") verifyField(comp6) Dim comp7 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib46, options:=TestOptions.DebugExe, references:=comp1Ref) CompileAndVerify(comp7, expectedOutput:="123") verifyField(comp7) End Sub <Fact> <WorkItem(41207, "https://github.com/dotnet/roslyn/issues/41207")> <WorkItem(1056281, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056281")> Public Sub CustomFields_02() Dim source0 = " Namespace System Public Structure ValueTuple(Of T1, T2) Public Dim F1 As Integer Public Dim Item1 As T1 Public Dim Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 me.F1 = 123 End Sub Public Overrides Function ToString() As String Return F1.ToString() End Function End Structure End Namespace " Dim source1 = " class Program public Shared Sub Main() System.Console.WriteLine((1,2).ToString()) End Sub End Class " Dim source2 = " class Program public Shared Sub Main() System.Console.WriteLine((1,2).F1) End Sub End Class " Dim verifyField = Sub(comp As VisualBasicCompilation) Dim field = comp.GetMember(Of FieldSymbol)("System.ValueTuple.F1") Assert.Null(field.TupleUnderlyingField) Dim toEmit = field.ContainingType.GetFieldsToEmit().Where(Function(f) f.Name = "F1").Single() Assert.Same(field, toEmit) End Sub Dim comp1 = CreateCompilation(source0 + source1, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe) CompileAndVerify(comp1, expectedOutput:="123") verifyField(comp1) Dim comp1Ref = {comp1.ToMetadataReference()} Dim comp1ImageRef = {comp1.EmitToImageReference()} Dim comp4 = CreateCompilation(source0 + source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe) CompileAndVerify(comp4, expectedOutput:="123") Dim comp5 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1Ref) CompileAndVerify(comp5, expectedOutput:="123") verifyField(comp5) Dim comp6 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1ImageRef) CompileAndVerify(comp6, expectedOutput:="123") verifyField(comp6) Dim comp7 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib46, options:=TestOptions.DebugExe, references:=comp1Ref) CompileAndVerify(comp7, expectedOutput:="123") verifyField(comp7) End Sub <Fact> <WorkItem(43524, "https://github.com/dotnet/roslyn/issues/43524")> <WorkItem(1095184, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1095184")> Public Sub CustomFields_03() Dim source0 = " namespace System public structure ValueTuple public shared readonly F1 As Integer = 4 public Shared Function CombineHashCodes(h1 As Integer, h2 As Integer) As Integer return F1 + h1 + h2 End Function End Structure End Namespace " Dim source1 = " class Program shared sub Main() System.Console.WriteLine(System.ValueTuple.CombineHashCodes(2, 3)) End Sub End Class " Dim source2 = " class Program public shared Sub Main() System.Console.WriteLine(System.ValueTuple.F1 + 2 + 3) End Sub End Class " Dim verifyField = Sub(comp As VisualBasicCompilation) Dim field = comp.GetMember(Of FieldSymbol)("System.ValueTuple.F1") Assert.Null(field.TupleUnderlyingField) Dim toEmit = field.ContainingType.GetFieldsToEmit().Single() Assert.Same(field, toEmit) End Sub Dim comp1 = CreateCompilation(source0 + source1, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe) CompileAndVerify(comp1, expectedOutput:="9") verifyField(comp1) Dim comp1Ref = {comp1.ToMetadataReference()} Dim comp1ImageRef = {comp1.EmitToImageReference()} Dim comp4 = CreateCompilation(source0 + source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe) CompileAndVerify(comp4, expectedOutput:="9") Dim comp5 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1Ref) CompileAndVerify(comp5, expectedOutput:="9") verifyField(comp5) Dim comp6 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1ImageRef) CompileAndVerify(comp6, expectedOutput:="9") verifyField(comp6) Dim comp7 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib46, options:=TestOptions.DebugExe, references:=comp1Ref) CompileAndVerify(comp7, expectedOutput:="9") verifyField(comp7) End Sub <Fact> <WorkItem(43524, "https://github.com/dotnet/roslyn/issues/43524")> <WorkItem(1095184, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1095184")> Public Sub CustomFields_04() Dim source0 = " namespace System public structure ValueTuple public F1 as Integer public Function CombineHashCodes(h1 as Integer, h2 as Integer) as Integer return F1 + h1 + h2 End Function End Structure End Namespace " Dim source1 = " class Program shared sub Main() Dim tuple as System.ValueTuple = Nothing tuple.F1 = 4 System.Console.WriteLine(tuple.CombineHashCodes(2, 3)) End Sub End Class " Dim source2 = " class Program public shared Sub Main() Dim tuple as System.ValueTuple = Nothing tuple.F1 = 4 System.Console.WriteLine(tuple.F1 + 2 + 3) End Sub End Class " Dim verifyField = Sub(comp As VisualBasicCompilation) Dim field = comp.GetMember(Of FieldSymbol)("System.ValueTuple.F1") Assert.Null(field.TupleUnderlyingField) Dim toEmit = field.ContainingType.GetFieldsToEmit().Single() Assert.Same(field, toEmit) End Sub Dim comp1 = CreateCompilation(source0 + source1, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe) CompileAndVerify(comp1, expectedOutput:="9") verifyField(comp1) Dim comp1Ref = {comp1.ToMetadataReference()} Dim comp1ImageRef = {comp1.EmitToImageReference()} Dim comp4 = CreateCompilation(source0 + source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe) CompileAndVerify(comp4, expectedOutput:="9") Dim comp5 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1Ref) CompileAndVerify(comp5, expectedOutput:="9") verifyField(comp5) Dim comp6 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1ImageRef) CompileAndVerify(comp6, expectedOutput:="9") verifyField(comp6) Dim comp7 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib46, options:=TestOptions.DebugExe, references:=comp1Ref) CompileAndVerify(comp7, expectedOutput:="9") verifyField(comp7) End Sub <Fact> <WorkItem(41702, "https://github.com/dotnet/roslyn/issues/41702")> Public Sub TupleUnderlyingType_FromCSharp() Dim source = "#pragma warning disable 169 class Program { static System.ValueTuple F0; static (int, int) F1; static (int A, int B) F2; static (object, object, object, object, object, object, object, object) F3; static (object, object B, object, object D, object, object F, object, object H) F4; }" Dim comp = CreateCSharpCompilation(source, referencedAssemblies:=TargetFrameworkUtil.GetReferences(TargetFramework.Standard)) comp.VerifyDiagnostics() Dim containingType = comp.GlobalNamespace.GetTypeMembers("Program").Single() VerifyTypeFromCSharp(DirectCast(DirectCast(containingType.GetMembers("F0").Single(), IFieldSymbol).Type, INamedTypeSymbol), TupleUnderlyingTypeValue.Nothing, "System.ValueTuple", "()") VerifyTypeFromCSharp(DirectCast(DirectCast(containingType.GetMembers("F1").Single(), IFieldSymbol).Type, INamedTypeSymbol), TupleUnderlyingTypeValue.Nothing, "(System.Int32, System.Int32)", "(System.Int32, System.Int32)") VerifyTypeFromCSharp(DirectCast(DirectCast(containingType.GetMembers("F2").Single(), IFieldSymbol).Type, INamedTypeSymbol), TupleUnderlyingTypeValue.Distinct, "(System.Int32 A, System.Int32 B)", "(A As System.Int32, B As System.Int32)") VerifyTypeFromCSharp(DirectCast(DirectCast(containingType.GetMembers("F3").Single(), IFieldSymbol).Type, INamedTypeSymbol), TupleUnderlyingTypeValue.Nothing, "(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", "(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)") VerifyTypeFromCSharp(DirectCast(DirectCast(containingType.GetMembers("F4").Single(), IFieldSymbol).Type, INamedTypeSymbol), TupleUnderlyingTypeValue.Distinct, "(System.Object, System.Object B, System.Object, System.Object D, System.Object, System.Object F, System.Object, System.Object H)", "(System.Object, B As System.Object, System.Object, D As System.Object, System.Object, F As System.Object, System.Object, H As System.Object)") End Sub <Fact> <WorkItem(41702, "https://github.com/dotnet/roslyn/issues/41702")> Public Sub TupleUnderlyingType_FromVisualBasic() Dim source = "Class Program Private F0 As System.ValueTuple Private F1 As (Integer, Integer) Private F2 As (A As Integer, B As Integer) Private F3 As (Object, Object, Object, Object, Object, Object, Object, Object) Private F4 As (Object, B As Object, Object, D As Object, Object, F As Object, Object, H As Object) End Class" Dim comp = CreateCompilation(source) comp.AssertNoDiagnostics() Dim containingType = comp.GlobalNamespace.GetTypeMembers("Program").Single() VerifyTypeFromVisualBasic(DirectCast(DirectCast(containingType.GetMembers("F0").Single(), FieldSymbol).Type, NamedTypeSymbol), TupleUnderlyingTypeValue.Nothing, "System.ValueTuple", "System.ValueTuple") VerifyTypeFromVisualBasic(DirectCast(DirectCast(containingType.GetMembers("F1").Single(), FieldSymbol).Type, NamedTypeSymbol), TupleUnderlyingTypeValue.Distinct, "(System.Int32, System.Int32)", "(System.Int32, System.Int32)") VerifyTypeFromVisualBasic(DirectCast(DirectCast(containingType.GetMembers("F2").Single(), FieldSymbol).Type, NamedTypeSymbol), TupleUnderlyingTypeValue.Distinct, "(System.Int32 A, System.Int32 B)", "(A As System.Int32, B As System.Int32)") VerifyTypeFromVisualBasic(DirectCast(DirectCast(containingType.GetMembers("F3").Single(), FieldSymbol).Type, NamedTypeSymbol), TupleUnderlyingTypeValue.Distinct, "(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", "(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)") VerifyTypeFromVisualBasic(DirectCast(DirectCast(containingType.GetMembers("F4").Single(), FieldSymbol).Type, NamedTypeSymbol), TupleUnderlyingTypeValue.Distinct, "(System.Object, System.Object B, System.Object, System.Object D, System.Object, System.Object F, System.Object, System.Object H)", "(System.Object, B As System.Object, System.Object, D As System.Object, System.Object, F As System.Object, System.Object, H As System.Object)") End Sub Private Enum TupleUnderlyingTypeValue [Nothing] Distinct Same End Enum Private Shared Sub VerifyTypeFromCSharp(type As INamedTypeSymbol, expectedValue As TupleUnderlyingTypeValue, expectedCSharp As String, expectedVisualBasic As String) VerifyDisplay(type, expectedCSharp, expectedVisualBasic) VerifyPublicType(type, expectedValue) VerifyPublicType(type.OriginalDefinition, TupleUnderlyingTypeValue.Nothing) End Sub Private Shared Sub VerifyTypeFromVisualBasic(type As NamedTypeSymbol, expectedValue As TupleUnderlyingTypeValue, expectedCSharp As String, expectedVisualBasic As String) VerifyDisplay(type, expectedCSharp, expectedVisualBasic) VerifyInternalType(type, expectedValue) VerifyPublicType(type, expectedValue) type = type.OriginalDefinition VerifyInternalType(type, expectedValue) VerifyPublicType(type, expectedValue) End Sub Private Shared Sub VerifyDisplay(type As INamedTypeSymbol, expectedCSharp As String, expectedVisualBasic As String) Assert.Equal(expectedCSharp, CSharp.SymbolDisplay.ToDisplayString(type, SymbolDisplayFormat.TestFormat)) Assert.Equal(expectedVisualBasic, VisualBasic.SymbolDisplay.ToDisplayString(type, SymbolDisplayFormat.TestFormat)) End Sub Private Shared Sub VerifyInternalType(type As NamedTypeSymbol, expectedValue As TupleUnderlyingTypeValue) Dim underlyingType = type.TupleUnderlyingType Select Case expectedValue Case TupleUnderlyingTypeValue.Nothing Assert.Null(underlyingType) Case TupleUnderlyingTypeValue.Distinct Assert.NotEqual(type, underlyingType) Assert.NotEqual(underlyingType, type) Assert.True(type.Equals(underlyingType, TypeCompareKind.AllIgnoreOptions)) Assert.True(underlyingType.Equals(type, TypeCompareKind.AllIgnoreOptions)) Assert.False(type.Equals(underlyingType, TypeCompareKind.ConsiderEverything)) Assert.False(underlyingType.Equals(type, TypeCompareKind.ConsiderEverything)) Assert.True(DirectCast(type, Symbol).Equals(underlyingType, TypeCompareKind.AllIgnoreOptions)) Assert.True(DirectCast(underlyingType, Symbol).Equals(type, TypeCompareKind.AllIgnoreOptions)) Assert.False(DirectCast(type, Symbol).Equals(underlyingType, TypeCompareKind.ConsiderEverything)) Assert.False(DirectCast(underlyingType, Symbol).Equals(type, TypeCompareKind.ConsiderEverything)) VerifyPublicType(underlyingType, expectedValue:=TupleUnderlyingTypeValue.Nothing) Case Else Throw ExceptionUtilities.UnexpectedValue(expectedValue) End Select End Sub Private Shared Sub VerifyPublicType(type As INamedTypeSymbol, expectedValue As TupleUnderlyingTypeValue) Dim underlyingType = type.TupleUnderlyingType Select Case expectedValue Case TupleUnderlyingTypeValue.Nothing Assert.Null(underlyingType) Case TupleUnderlyingTypeValue.Distinct Assert.NotEqual(type, underlyingType) Assert.False(type.Equals(underlyingType, SymbolEqualityComparer.Default)) Assert.False(type.Equals(underlyingType, SymbolEqualityComparer.ConsiderEverything)) VerifyPublicType(underlyingType, expectedValue:=TupleUnderlyingTypeValue.Nothing) Case Else Throw ExceptionUtilities.UnexpectedValue(expectedValue) End Select End Sub <Fact> <WorkItem(27322, "https://github.com/dotnet/roslyn/issues/27322")> Public Sub Issue27322() Dim source0 = " Imports System Imports System.Collections.Generic Imports System.Linq.Expressions Module Module1 Sub Main() Dim tupleA = (1, 3) Dim tupleB = (1, ""123"".Length) Dim ok1 As Expression(Of Func(Of Integer)) = Function() tupleA.Item1 Dim ok2 As Expression(Of Func(Of Integer)) = Function() tupleA.GetHashCode() Dim ok3 As Expression(Of Func(Of Tuple(Of Integer, Integer))) = Function() tupleA.ToTuple() Dim ok4 As Expression(Of Func(Of Boolean)) = Function() Equals(tupleA, tupleB) Dim ok5 As Expression(Of Func(Of Integer)) = Function() Comparer(Of (Integer, Integer)).Default.Compare(tupleA, tupleB) ok1.Compile()() ok2.Compile()() ok3.Compile()() ok4.Compile()() ok5.Compile()() Dim err1 As Expression(Of Func(Of Boolean)) = Function() tupleA.Equals(tupleB) Dim err2 As Expression(Of Func(Of Integer)) = Function() tupleA.CompareTo(tupleB) err1.Compile()() err2.Compile()() System.Console.WriteLine(""Done"") End Sub End Module " Dim comp1 = CreateCompilation(source0, options:=TestOptions.DebugExe) CompileAndVerify(comp1, expectedOutput:="Done") End Sub <Fact> <WorkItem(24517, "https://github.com/dotnet/roslyn/issues/24517")> Public Sub Issue24517() Dim source0 = " Imports System Imports System.Collections.Generic Imports System.Linq.Expressions Module Module1 Sub Main() Dim e1 As Expression(Of Func(Of ValueTuple(Of Integer, Integer))) = Function() new ValueTuple(Of Integer, Integer)(1, 2) Dim e2 As Expression(Of Func(Of KeyValuePair(Of Integer, Integer))) = Function() new KeyValuePair(Of Integer, Integer)(1, 2) e1.Compile()() e2.Compile()() System.Console.WriteLine(""Done"") End Sub End Module " Dim comp1 = CreateCompilation(source0, options:=TestOptions.DebugExe) CompileAndVerify(comp1, expectedOutput:="Done") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Text 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.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Imports Roslyn.Test.Utilities.TestMetadata Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests <CompilerTrait(CompilerFeature.Tuples)> Public Class CodeGenTuples Inherits BasicTestBase ReadOnly s_valueTupleRefs As MetadataReference() = New MetadataReference() {ValueTupleRef, SystemRuntimeFacadeRef} ReadOnly s_valueTupleRefsAndDefault As MetadataReference() = New MetadataReference() {ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef, SystemRef, SystemCoreRef, MsvbRef} ReadOnly s_trivial2uple As String = " Namespace System Public Structure ValueTuple(Of T1, T2) Public Dim Item1 As T1 Public Dim Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return ""{"" + Item1?.ToString() + "", "" + Item2?.ToString() + ""}"" End Function End Structure End Namespace namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Field Or AttributeTargets.Parameter Or AttributeTargets.Property Or AttributeTargets.ReturnValue Or AttributeTargets.Class Or AttributeTargets.Struct )> public class TupleElementNamesAttribute : Inherits Attribute public Sub New(transformNames As String()) End Sub End Class End Namespace " ReadOnly s_tupleattributes As String = " namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Field Or AttributeTargets.Parameter Or AttributeTargets.Property Or AttributeTargets.ReturnValue Or AttributeTargets.Class Or AttributeTargets.Struct )> public class TupleElementNamesAttribute : Inherits Attribute public Sub New(transformNames As String()) End Sub End Class End Namespace " ReadOnly s_trivial3uple As String = " Namespace System Public Structure ValueTuple(Of T1, T2, T3) Public Dim Item1 As T1 Public Dim Item2 As T2 Public Dim Item3 As T3 Public Sub New(item1 As T1, item2 As T2, item3 As T3) me.Item1 = item1 me.Item2 = item2 me.Item3 = item3 End Sub End Structure End Namespace " ReadOnly s_trivialRemainingTuples As String = " Namespace System Public Structure ValueTuple(Of T1, T2, T3, T4) Public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4) End Sub End Structure Public Structure ValueTuple(Of T1, T2, T3, T4, T5) Public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5) End Sub End Structure Public Structure ValueTuple(Of T1, T2, T3, T4, T5, T6) Public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6) End Sub End Structure Public Structure ValueTuple(Of T1, T2, T3, T4, T5, T6, T7) Public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6, item7 As T7) End Sub End Structure Public Structure ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest) Public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6, item7 As T7, rest As TRest) End Sub End Structure End Namespace " <Fact> Public Sub TupleNamesInArrayInAttribute() Dim comp = CreateCompilation( <compilation> <file name="a.vb"><![CDATA[ Imports System <My(New (String, bob As String)() { })> Public Class MyAttribute Inherits System.Attribute Public Sub New(x As (alice As String, String)()) End Sub End Class ]]></file> </compilation>) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30045: Attribute constructor has a parameter of type '(alice As String, String)()', which is not an integral, floating-point or Enum type or one of Object, Char, String, Boolean, System.Type or 1-dimensional array of these types. <My(New (String, bob As String)() { })> ~~ ]]></errors>) End Sub <Fact> Public Sub TupleTypeBinding() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim t as (Integer, Integer) console.writeline(t) End Sub End Module Namespace System Structure ValueTuple(Of T1, T2) Public Overrides Function ToString() As String Return "hello" End Function End Structure End Namespace </file> </compilation>, expectedOutput:=<![CDATA[ hello ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 .locals init (System.ValueTuple(Of Integer, Integer) V_0) //t IL_0000: ldloc.0 IL_0001: box "System.ValueTuple(Of Integer, Integer)" IL_0006: call "Sub System.Console.WriteLine(Object)" IL_000b: ret } ]]>) End Sub <Fact> Public Sub TupleTypeBindingTypeChar() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> option strict on Imports System Module C Sub Main() Dim t as (A%, B$) = Nothing console.writeline(t.GetType()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.ValueTuple`2[System.Int32,System.String] ]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 25 (0x19) .maxstack 1 .locals init (System.ValueTuple(Of Integer, String) V_0) //t IL_0000: ldloca.s V_0 IL_0002: initobj "System.ValueTuple(Of Integer, String)" IL_0008: ldloc.0 IL_0009: box "System.ValueTuple(Of Integer, String)" IL_000e: call "Function Object.GetType() As System.Type" IL_0013: call "Sub System.Console.WriteLine(Object)" IL_0018: ret } ]]>) End Sub <Fact> Public Sub TupleTypeBindingTypeChar1() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> option strict off Imports System Module C Sub Main() Dim t as (A%, B$) = Nothing console.writeline(t.GetType()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.ValueTuple`2[System.Int32,System.String] ]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 25 (0x19) .maxstack 1 .locals init (System.ValueTuple(Of Integer, String) V_0) //t IL_0000: ldloca.s V_0 IL_0002: initobj "System.ValueTuple(Of Integer, String)" IL_0008: ldloc.0 IL_0009: box "System.ValueTuple(Of Integer, String)" IL_000e: call "Function Object.GetType() As System.Type" IL_0013: call "Sub System.Console.WriteLine(Object)" IL_0018: ret } ]]>) End Sub <Fact> Public Sub TupleTypeBindingTypeCharErr() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim t as (A% As String, B$ As String, C As String$) = nothing console.writeline(t.A.Length) 'A should not take the type from % in this case Dim t1 as (String$, String%) = nothing console.writeline(t1.GetType()) Dim B = 1 Dim t2 = (A% := "qq", B$) console.writeline(t2.A.Length) 'A should not take the type from % in this case Dim t3 As (V1(), V2%()) = Nothing console.writeline(t3.Item1.Length) End Sub Async Sub T() Dim t4 as (Integer% As String, Await As String, Function$) = nothing console.writeline(t4.Integer.Length) console.writeline(t4.Await.Length) console.writeline(t4.Function.Length) Dim t5 as (Function As String, Sub, Junk1 As Junk2 Recovery, Junk4 Junk5) = nothing console.writeline(t4.Function.Length) End Sub class V2 end class End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30302: Type character '%' cannot be used in a declaration with an explicit type. Dim t as (A% As String, B$ As String, C As String$) = nothing ~~ BC30302: Type character '$' cannot be used in a declaration with an explicit type. Dim t as (A% As String, B$ As String, C As String$) = nothing ~~ BC30468: Type declaration characters are not valid in this context. Dim t as (A% As String, B$ As String, C As String$) = nothing ~~~~~~~ BC37262: Tuple element names must be unique. Dim t1 as (String$, String%) = nothing ~~~~~~~ BC37270: Type characters cannot be used in tuple literals. Dim t2 = (A% := "qq", B$) ~~ BC30277: Type character '$' does not match declared data type 'Integer'. Dim t2 = (A% := "qq", B$) ~~ BC30002: Type 'V1' is not defined. Dim t3 As (V1(), V2%()) = Nothing ~~ BC32017: Comma, ')', or a valid expression continuation expected. Dim t3 As (V1(), V2%()) = Nothing ~ BC42356: This async method lacks 'Await' operators and so 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 Sub T() ~ BC30302: Type character '%' cannot be used in a declaration with an explicit type. Dim t4 as (Integer% As String, Await As String, Function$) = nothing ~~~~~~~~ BC30183: Keyword is not valid as an identifier. Dim t4 as (Integer% As String, Await As String, Function$) = nothing ~~~~~ BC30180: Keyword does not name a type. Dim t5 as (Function As String, Sub, Junk1 As Junk2 Recovery, Junk4 Junk5) = nothing ~ BC30180: Keyword does not name a type. Dim t5 as (Function As String, Sub, Junk1 As Junk2 Recovery, Junk4 Junk5) = nothing ~ BC30002: Type 'Junk2' is not defined. Dim t5 as (Function As String, Sub, Junk1 As Junk2 Recovery, Junk4 Junk5) = nothing ~~~~~ BC32017: Comma, ')', or a valid expression continuation expected. Dim t5 as (Function As String, Sub, Junk1 As Junk2 Recovery, Junk4 Junk5) = nothing ~~~~~~~~ BC30002: Type 'Junk4' is not defined. Dim t5 as (Function As String, Sub, Junk1 As Junk2 Recovery, Junk4 Junk5) = nothing ~~~~~ BC32017: Comma, ')', or a valid expression continuation expected. Dim t5 as (Function As String, Sub, Junk1 As Junk2 Recovery, Junk4 Junk5) = nothing ~~~~~ </errors>) End Sub <Fact> Public Sub TupleTypeBindingNoTuple() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim t as (Integer, Integer) console.writeline(t) console.writeline(t.Item1) Dim t1 as (A As Integer, B As Integer) console.writeline(t1) console.writeline(t1.Item1) console.writeline(t1.A) End Sub End Module ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported. Dim t as (Integer, Integer) ~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported. Dim t1 as (A As Integer, B As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Dim t1 as (A As Integer, B As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleDefaultType001() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim t = (Nothing, Nothing) console.writeline(t) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (, ) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 18 (0x12) .maxstack 2 IL_0000: ldnull IL_0001: ldnull IL_0002: newobj "Sub System.ValueTuple(Of Object, Object)..ctor(Object, Object)" IL_0007: box "System.ValueTuple(Of Object, Object)" IL_000c: call "Sub System.Console.WriteLine(Object)" IL_0011: ret } ]]>) End Sub <Fact()> Public Sub TupleDefaultType001err() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim t = (Nothing, Nothing) console.writeline(t) End Sub End Module ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported. Dim t = (Nothing, Nothing) ~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub TupleDefaultType002() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim t1 = ({Nothing}, {Nothing}) console.writeline(t1.GetType()) Dim t2 = {(Nothing, Nothing)} console.writeline(t2.GetType()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.ValueTuple`2[System.Object[],System.Object[]] System.ValueTuple`2[System.Object,System.Object][] ]]>) End Sub <Fact()> Public Sub TupleDefaultType003() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim t3 = Function(){(Nothing, Nothing)} console.writeline(t3.GetType()) Dim t4 = {Function()(Nothing, Nothing)} console.writeline(t4.GetType()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ VB$AnonymousDelegate_0`1[System.ValueTuple`2[System.Object,System.Object][]] VB$AnonymousDelegate_0`1[System.ValueTuple`2[System.Object,System.Object]][] ]]>) End Sub <Fact()> Public Sub TupleDefaultType004() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Test(({Nothing}, {{Nothing}})) Test((Function(x as integer)x, Function(x as Long)x)) End Sub function Test(of T, U)(x as (T, U)) as (U, T) System.Console.WriteLine(GetType(T)) System.Console.WriteLine(GetType(U)) System.Console.WriteLine() return (x.Item2, x.Item1) End Function End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.Object[] System.Object[,] VB$AnonymousDelegate_0`2[System.Int32,System.Int32] VB$AnonymousDelegate_0`2[System.Int64,System.Int64] ]]>) End Sub <Fact()> Public Sub TupleDefaultType005() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Test((Function(x as integer)Function()x, Function(x as Long){({Nothing}, {Nothing})})) End Sub function Test(of T, U)(x as (T, U)) as (U, T) System.Console.WriteLine(GetType(T)) System.Console.WriteLine(GetType(U)) System.Console.WriteLine() return (x.Item2, x.Item1) End Function End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ VB$AnonymousDelegate_0`2[System.Int32,VB$AnonymousDelegate_1`1[System.Int32]] VB$AnonymousDelegate_0`2[System.Int64,System.ValueTuple`2[System.Object[],System.Object[]][]] ]]>) End Sub <Fact()> Public Sub TupleDefaultType006() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Test((Nothing, Nothing), "q") Test((Nothing, "q"), Nothing) Test1("q", (Nothing, Nothing)) Test1(Nothing, ("q", Nothing)) End Sub function Test(of T)(x as (T, T), y as T) as T System.Console.WriteLine(GetType(T)) return y End Function function Test1(of T)(x as T, y as (T, T)) as T System.Console.WriteLine(GetType(T)) return x End Function End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.String System.String System.String System.String ]]>) End Sub <Fact()> Public Sub TupleDefaultType006err() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Test1((Nothing, Nothing), Nothing) Test2(Nothing, (Nothing, Nothing)) End Sub function Test1(of T)(x as (T, T), y as T) as T System.Console.WriteLine(GetType(T)) return y End Function function Test2(of T)(x as T, y as (T, T)) as T System.Console.WriteLine(GetType(T)) return x End Function End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC36645: Data type(s) of the type parameter(s) in method 'Public Function Test1(Of T)(x As (T, T), y As T) As T' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. Test1((Nothing, Nothing), Nothing) ~~~~~ BC36645: Data type(s) of the type parameter(s) in method 'Public Function Test2(Of T)(x As T, y As (T, T)) As T' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. Test2(Nothing, (Nothing, Nothing)) ~~~~~ </errors>) End Sub <Fact()> Public Sub TupleDefaultType007() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim valid As (A as Action, B as Action) = (AddressOf Main, AddressOf Main) Test2(valid) Test2((AddressOf Main, Sub() Main)) End Sub function Test2(of T)(x as (T, T)) as (T, T) System.Console.WriteLine(GetType(T)) return x End Function End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.Action VB$AnonymousDelegate_0 ]]>) End Sub <Fact()> Public Sub TupleDefaultType007err() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x = (AddressOf Main, AddressOf Main) Dim x1 = (Function() Main, Function() Main) Dim x2 = (AddressOf Mai, Function() Mai) Dim x3 = (A := AddressOf Main, B := (D := AddressOf Main, C := AddressOf Main)) Test1((AddressOf Main, Sub() Main)) Test1((AddressOf Main, Function() Main)) Test2((AddressOf Main, Function() Main)) End Sub function Test1(of T)(x as T) as T System.Console.WriteLine(GetType(T)) return x End Function function Test2(of T)(x as (T, T)) as (T, T) System.Console.WriteLine(GetType(T)) return x End Function End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30491: Expression does not produce a value. Dim x = (AddressOf Main, AddressOf Main) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30491: Expression does not produce a value. Dim x1 = (Function() Main, Function() Main) ~~~~ BC30491: Expression does not produce a value. Dim x1 = (Function() Main, Function() Main) ~~~~ BC30451: 'Mai' is not declared. It may be inaccessible due to its protection level. Dim x2 = (AddressOf Mai, Function() Mai) ~~~ BC30491: Expression does not produce a value. Dim x3 = (A := AddressOf Main, B := (D := AddressOf Main, C := AddressOf Main)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC36645: Data type(s) of the type parameter(s) in method 'Public Function Test1(Of T)(x As T) As T' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. Test1((AddressOf Main, Sub() Main)) ~~~~~ BC36645: Data type(s) of the type parameter(s) in method 'Public Function Test1(Of T)(x As T) As T' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. Test1((AddressOf Main, Function() Main)) ~~~~~ BC36645: Data type(s) of the type parameter(s) in method 'Public Function Test2(Of T)(x As (T, T)) As (T, T)' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. Test2((AddressOf Main, Function() Main)) ~~~~~ </errors>) End Sub <Fact()> Public Sub DataFlow() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() dim initialized as Object = Nothing dim baseline_literal = (initialized, initialized) dim uninitialized as Object dim literal = (uninitialized, uninitialized) dim uninitialized1 as Exception dim identity_literal as (Alice As Exception, Bob As Exception) = (uninitialized1, uninitialized1) dim uninitialized2 as Exception dim converted_literal as (Object, Object) = (uninitialized2, uninitialized2) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC42104: Variable 'uninitialized' is used before it has been assigned a value. A null reference exception could result at runtime. dim literal = (uninitialized, uninitialized) ~~~~~~~~~~~~~ BC42104: Variable 'uninitialized1' is used before it has been assigned a value. A null reference exception could result at runtime. dim identity_literal as (Alice As Exception, Bob As Exception) = (uninitialized1, uninitialized1) ~~~~~~~~~~~~~~ BC42104: Variable 'uninitialized2' is used before it has been assigned a value. A null reference exception could result at runtime. dim converted_literal as (Object, Object) = (uninitialized2, uninitialized2) ~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleFieldBinding() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim t as (Integer, Integer) t.Item1 = 42 t.Item2 = t.Item1 console.writeline(t.Item2) End Sub End Module Namespace System Structure ValueTuple(Of T1, T2) Public Item1 As T1 Public Item2 As T2 End Structure End Namespace </file> </compilation>, expectedOutput:=<![CDATA[ 42 ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 34 (0x22) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer) V_0) //t IL_0000: ldloca.s V_0 IL_0002: ldc.i4.s 42 IL_0004: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0009: ldloca.s V_0 IL_000b: ldloc.0 IL_000c: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0011: stfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0016: ldloc.0 IL_0017: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_001c: call "Sub System.Console.WriteLine(Integer)" IL_0021: ret } ]]>) End Sub <Fact> Public Sub TupleFieldBinding01() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim vt as ValueTuple(Of Integer, Integer) = M1(2,3) console.writeline(vt.Item2) End Sub Function M1(x As Integer, y As Integer) As ValueTuple(Of Integer, Integer) Return New ValueTuple(Of Integer, Integer)(x, y) End Function End Module </file> </compilation>, expectedOutput:=<![CDATA[ 3 ]]>, references:=s_valueTupleRefs) verifier.VerifyIL("C.M1", <![CDATA[ { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0007: ret } ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 18 (0x12) .maxstack 2 IL_0000: ldc.i4.2 IL_0001: ldc.i4.3 IL_0002: call "Function C.M1(Integer, Integer) As (Integer, Integer)" IL_0007: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_000c: call "Sub System.Console.WriteLine(Integer)" IL_0011: ret } ]]>) End Sub <Fact> Public Sub TupleFieldBindingLong() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim t as (Integer, Integer, Integer, integer, integer, integer, integer, integer, integer, Integer, Integer, String, integer, integer, integer, integer, String, integer) t.Item17 = "hello" t.Item12 = t.Item17 console.writeline(t.Item12) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ hello ]]>, references:=s_valueTupleRefs) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 67 (0x43) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)) V_0) //t IL_0000: ldloca.s V_0 IL_0002: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)).Rest As (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)" IL_0007: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, String, Integer, Integer, (Integer, Integer, String, Integer)).Rest As (Integer, Integer, String, Integer)" IL_000c: ldstr "hello" IL_0011: stfld "System.ValueTuple(Of Integer, Integer, String, Integer).Item3 As String" IL_0016: ldloca.s V_0 IL_0018: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)).Rest As (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)" IL_001d: ldloc.0 IL_001e: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)).Rest As (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)" IL_0023: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, String, Integer, Integer, (Integer, Integer, String, Integer)).Rest As (Integer, Integer, String, Integer)" IL_0028: ldfld "System.ValueTuple(Of Integer, Integer, String, Integer).Item3 As String" IL_002d: stfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, String, Integer, Integer, (Integer, Integer, String, Integer)).Item5 As String" IL_0032: ldloc.0 IL_0033: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)).Rest As (Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer, String, Integer)" IL_0038: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, String, Integer, Integer, (Integer, Integer, String, Integer)).Item5 As String" IL_003d: call "Sub System.Console.WriteLine(String)" IL_0042: ret } ]]>) End Sub <Fact> Public Sub TupleNamedFieldBinding() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim t As (a As Integer, b As Integer) t.a = 42 t.b = t.a Console.WriteLine(t.b) End Sub End Module Namespace System Structure ValueTuple(Of T1, T2) Public Item1 As T1 Public Item2 As T2 End Structure End Namespace namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Field Or AttributeTargets.Parameter Or AttributeTargets.Property Or AttributeTargets.ReturnValue Or AttributeTargets.Class Or AttributeTargets.Struct )> public class TupleElementNamesAttribute : Inherits Attribute public Sub New(transformNames As String()) End Sub End Class End Namespace </file> </compilation>, expectedOutput:=<![CDATA[ 42 ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 34 (0x22) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer) V_0) //t IL_0000: ldloca.s V_0 IL_0002: ldc.i4.s 42 IL_0004: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0009: ldloca.s V_0 IL_000b: ldloc.0 IL_000c: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0011: stfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0016: ldloc.0 IL_0017: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_001c: call "Sub System.Console.WriteLine(Integer)" IL_0021: ret } ]]>) End Sub <Fact> Public Sub TupleDefaultFieldBinding() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Dim t As (Integer, Integer) = nothing t.Item1 = 42 t.Item2 = t.Item1 Console.WriteLine(t.Item2) Dim t1 = (A:=1, B:=123) Console.WriteLine(t1.B) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 42 123 ]]>, references:=s_valueTupleRefs) verifier.VerifyIL("Module1.Main", <![CDATA[ { // Code size 60 (0x3c) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer) V_0) //t IL_0000: ldloca.s V_0 IL_0002: initobj "System.ValueTuple(Of Integer, Integer)" IL_0008: ldloca.s V_0 IL_000a: ldc.i4.s 42 IL_000c: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0011: ldloca.s V_0 IL_0013: ldloc.0 IL_0014: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0019: stfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_001e: ldloc.0 IL_001f: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0024: call "Sub System.Console.WriteLine(Integer)" IL_0029: ldc.i4.1 IL_002a: ldc.i4.s 123 IL_002c: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0031: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0036: call "Sub System.Console.WriteLine(Integer)" IL_003b: ret } ]]>) End Sub <Fact> Public Sub TupleNamedFieldBindingLong() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim t as (a1 as Integer, a2 as Integer, a3 as Integer, a4 as integer, a5 as integer, a6 as integer, a7 as integer, a8 as integer, a9 as integer, a10 as Integer, a11 as Integer, a12 as Integer, a13 as integer, a14 as integer, a15 as integer, a16 as integer, a17 as integer, a18 as integer) t.a17 = 42 t.a12 = t.a17 console.writeline(t.a12) TestArray() TestNullable() End Sub Sub TestArray() Dim t = New (a1 as Integer, a2 as Integer, a3 as Integer, a4 as integer, a5 as integer, a6 as integer, a7 as integer, a8 as integer, a9 as integer, a10 as Integer, a11 as Integer, a12 as Integer, a13 as integer, a14 as integer, a15 as integer, a16 as integer, a17 as integer, a18 as integer)() {Nothing} t(0).a17 = 42 t(0).a12 = t(0).a17 console.writeline(t(0).a12) End Sub Sub TestNullable() Dim t as New (a1 as Integer, a2 as Integer, a3 as Integer, a4 as integer, a5 as integer, a6 as integer, a7 as integer, a8 as integer, a9 as integer, a10 as Integer, a11 as Integer, a12 as Integer, a13 as integer, a14 as integer, a15 as integer, a16 as integer, a17 as integer, a18 as integer)? console.writeline(t.HasValue) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 42 42 False ]]>, references:=s_valueTupleRefs) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 74 (0x4a) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)) V_0) //t IL_0000: ldloca.s V_0 IL_0002: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)" IL_0007: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer)" IL_000c: ldc.i4.s 42 IL_000e: stfld "System.ValueTuple(Of Integer, Integer, Integer, Integer).Item3 As Integer" IL_0013: ldloca.s V_0 IL_0015: ldflda "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)" IL_001a: ldloc.0 IL_001b: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)" IL_0020: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer)" IL_0025: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer).Item3 As Integer" IL_002a: stfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer)).Item5 As Integer" IL_002f: ldloc.0 IL_0030: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)).Rest As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)" IL_0035: ldfld "System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer, Integer, Integer)).Item5 As Integer" IL_003a: call "Sub System.Console.WriteLine(Integer)" IL_003f: call "Sub C.TestArray()" IL_0044: call "Sub C.TestNullable()" IL_0049: ret } ]]>) End Sub <Fact> Public Sub TupleNewLongErr() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim t = New (a1 as Integer, a2 as Integer, a3 as Integer, a4 as integer, a5 as integer, a6 as integer, a7 as integer, a8 as integer, a9 as integer, a10 as Integer, a11 as Integer, a12 as String, a13 as integer, a14 as integer, a15 as integer, a16 as integer, a17 as integer, a18 as integer) console.writeline(t.a12.Length) Dim t1 As New (a1 as Integer, a2 as Integer, a3 as Integer, a4 as integer, a5 as integer, a6 as integer, a7 as integer, a8 as integer, a9 as integer, a10 as Integer, a11 as Integer, a12 as String, a13 as integer, a14 as integer, a15 as integer, a16 as integer, a17 as integer, a18 as integer) console.writeline(t1.a12.Length) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) ' should not complain about missing constructor comp.AssertTheseDiagnostics( <errors> BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead. Dim t = New (a1 as Integer, a2 as Integer, a3 as Integer, a4 as integer, ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead. Dim t1 As New (a1 as Integer, a2 as Integer, a3 as Integer, a4 as integer, ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleDisallowedWithNew() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C Dim t1 = New (a1 as Integer, a2 as Integer)() Dim t2 As New (a1 as Integer, a2 as Integer) Sub M() Dim t1 = New (a1 as Integer, a2 as Integer)() Dim t2 As New (a1 as Integer, a2 as Integer) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead. Dim t1 = New (a1 as Integer, a2 as Integer)() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead. Dim t2 As New (a1 as Integer, a2 as Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead. Dim t1 = New (a1 as Integer, a2 as Integer)() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead. Dim t2 As New (a1 as Integer, a2 as Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub ParseNewTuple() Dim comp1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class A Sub Main() Dim x = New (A, A) Dim y = New (A, A)() Dim z = New (x As Integer, A) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp1.AssertTheseDiagnostics(<errors> BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead. Dim x = New (A, A) ~~~~~~ BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead. Dim y = New (A, A)() ~~~~~~ BC37280: 'New' cannot be used with tuple type. Use a tuple literal expression instead. Dim z = New (x As Integer, A) ~~~~~~~~~~~~~~~~~ </errors>) Dim comp2 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Module1 Public Function Bar() As (Alice As (Alice As Integer, Bob As Integer)(), Bob As Integer) ' this is actually ok, since it is an array Return (New(Integer, Integer)() {(4, 5)}, 5) End Function End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp2.AssertNoDiagnostics() End Sub <Fact> Public Sub TupleLiteralBinding() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim t as (Integer, Integer) = (1, 2) console.writeline(t) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ (1, 2) ]]>, references:=s_valueTupleRefs) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 18 (0x12) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0007: box "System.ValueTuple(Of Integer, Integer)" IL_000c: call "Sub System.Console.WriteLine(Object)" IL_0011: ret } ]]>) End Sub <Fact> Public Sub TupleLiteralBindingNamed() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim t = (A := 1, B := "hello") console.writeline(t.B) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ hello ]]>, references:=s_valueTupleRefs) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 22 (0x16) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: ldstr "hello" IL_0006: newobj "Sub System.ValueTuple(Of Integer, String)..ctor(Integer, String)" IL_000b: ldfld "System.ValueTuple(Of Integer, String).Item2 As String" IL_0010: call "Sub System.Console.WriteLine(String)" IL_0015: ret } ]]>) End Sub <Fact> Public Sub TupleLiteralSample() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Threading.Tasks Module Module1 Sub Main() Dim t As (Integer, Integer) = Nothing t.Item1 = 42 t.Item2 = t.Item1 Console.WriteLine(t.Item2) Dim t1 = (A:=1, B:=123) Console.WriteLine(t1.B) Dim numbers = {1, 2, 3, 4} Dim t2 = Tally(numbers).Result System.Console.WriteLine($"Sum: {t2.Sum}, Count: {t2.Count}") End Sub Public Async Function Tally(values As IEnumerable(Of Integer)) As Task(Of (Sum As Integer, Count As Integer)) Dim s = 0, c = 0 For Each n In values s += n c += 1 Next 'Await Task.Yield() Return (Sum:=s, Count:=c) End Function End Module Namespace System Structure ValueTuple(Of T1, T2) Public Item1 As T1 Public Item2 As T2 Sub New(item1 as T1, item2 as T2) Me.Item1 = item1 Me.Item2 = item2 End Sub End Structure End Namespace namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Field Or AttributeTargets.Parameter Or AttributeTargets.Property Or AttributeTargets.ReturnValue Or AttributeTargets.Class Or AttributeTargets.Struct )> public class TupleElementNamesAttribute : Inherits Attribute public Sub New(transformNames As String()) End Sub End Class End Namespace </file> </compilation>, useLatestFramework:=True, expectedOutput:="42 123 Sum: 10, Count: 4") End Sub <Fact> <WorkItem(18762, "https://github.com/dotnet/roslyn/issues/18762")> Public Sub UnnamedTempShouldNotCrashPdbEncoding() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Threading.Tasks Module Module1 Private Async Function DoAllWorkAsync() As Task(Of (FirstValue As String, SecondValue As String)) Return (Nothing, Nothing) End Function End Module </file> </compilation>, references:={ValueTupleRef, SystemRuntimeFacadeRef}, useLatestFramework:=True, options:=TestOptions.DebugDll) End Sub <Fact> Public Sub Overloading001() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module m1 Sub Test(x as (a as integer, b as Integer)) End Sub Sub Test(x as (c as integer, d as Integer)) End Sub End module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37271: 'Public Sub Test(x As (a As Integer, b As Integer))' has multiple definitions with identical signatures with different tuple element names, including 'Public Sub Test(x As (c As Integer, d As Integer))'. Sub Test(x as (a as integer, b as Integer)) ~~~~ </errors>) End Sub <Fact> Public Sub Overloading002() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module m1 Sub Test(x as (integer,Integer)) End Sub Sub Test(x as (a as integer, b as Integer)) End Sub End module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37271: 'Public Sub Test(x As (Integer, Integer))' has multiple definitions with identical signatures with different tuple element names, including 'Public Sub Test(x As (a As Integer, b As Integer))'. Sub Test(x as (integer,Integer)) ~~~~ </errors>) End Sub <Fact> Public Sub SimpleTupleTargetTyped001() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x as (String, String) = (Nothing, Nothing) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (, ) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 28 (0x1c) .maxstack 3 .locals init (System.ValueTuple(Of String, String) V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldnull IL_0003: ldnull IL_0004: call "Sub System.ValueTuple(Of String, String)..ctor(String, String)" IL_0009: ldloca.s V_0 IL_000b: constrained. "System.ValueTuple(Of String, String)" IL_0011: callvirt "Function Object.ToString() As String" IL_0016: call "Sub System.Console.WriteLine(String)" IL_001b: ret } ]]>) Dim comp = verifier.Compilation Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(Nothing, Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Assert.Equal("(System.String, System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(node).Kind) End Sub <Fact> Public Sub SimpleTupleTargetTyped001Err() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x as (A as String, B as String) = (C:=Nothing, D:=Nothing, E:=Nothing) System.Console.WriteLine(x.ToString()) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30311: Value of type '(C As Object, D As Object, E As Object)' cannot be converted to '(A As String, B As String)'. Dim x as (A as String, B as String) = (C:=Nothing, D:=Nothing, E:=Nothing) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub SimpleTupleTargetTyped002() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x as (Func(Of integer), Func(of String)) = (Function() 42, Function() "hi") System.Console.WriteLine((x.Item1(), x.Item2()).ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (42, hi) ]]>) End Sub <Fact> Public Sub SimpleTupleTargetTyped002a() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x as (Func(Of integer), Func(of String)) = (Function() 42, Function() Nothing) System.Console.WriteLine((x.Item1(), x.Item2()).ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (42, ) ]]>) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub SimpleTupleTargetTyped003() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x = CType((Nothing, 1),(String, Byte)) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (, 1) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 28 (0x1c) .maxstack 3 .locals init (System.ValueTuple(Of String, Byte) V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldnull IL_0003: ldc.i4.1 IL_0004: call "Sub System.ValueTuple(Of String, Byte)..ctor(String, Byte)" IL_0009: ldloca.s V_0 IL_000b: constrained. "System.ValueTuple(Of String, Byte)" IL_0011: callvirt "Function Object.ToString() As String" IL_0016: call "Sub System.Console.WriteLine(String)" IL_001b: ret } ]]>) Dim compilation = verifier.Compilation Dim tree = compilation.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of CTypeExpressionSyntax)().Single() Assert.Equal("CType((Nothing, 1),(String, Byte))", node.ToString()) compilation.VerifyOperationTree(node, expectedOperationTree:= <![CDATA[ IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.String, System.Byte)) (Syntax: 'CType((Noth ... ing, Byte))') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.String, System.Byte)) (Syntax: '(Nothing, 1)') NaturalType: null Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ]]>.Value) End Sub <Fact> Public Sub SimpleTupleTargetTyped004() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x = DirectCast((Nothing, 1),(String, String)) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (, 1) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 33 (0x21) .maxstack 3 .locals init (System.ValueTuple(Of String, String) V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldnull IL_0003: ldc.i4.1 IL_0004: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String" IL_0009: call "Sub System.ValueTuple(Of String, String)..ctor(String, String)" IL_000e: ldloca.s V_0 IL_0010: constrained. "System.ValueTuple(Of String, String)" IL_0016: callvirt "Function Object.ToString() As String" IL_001b: call "Sub System.Console.WriteLine(String)" IL_0020: ret } ]]>) End Sub <Fact> Public Sub SimpleTupleTargetTyped005() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim i as integer = 100 Dim x = CType((Nothing, i),(String, byte)) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (, 100) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 32 (0x20) .maxstack 3 .locals init (Integer V_0, //i System.ValueTuple(Of String, Byte) V_1) //x IL_0000: ldc.i4.s 100 IL_0002: stloc.0 IL_0003: ldloca.s V_1 IL_0005: ldnull IL_0006: ldloc.0 IL_0007: conv.ovf.u1 IL_0008: call "Sub System.ValueTuple(Of String, Byte)..ctor(String, Byte)" IL_000d: ldloca.s V_1 IL_000f: constrained. "System.ValueTuple(Of String, Byte)" IL_0015: callvirt "Function Object.ToString() As String" IL_001a: call "Sub System.Console.WriteLine(String)" IL_001f: ret } ]]>) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub SimpleTupleTargetTyped006() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim i as integer = 100 Dim x = DirectCast((Nothing, i),(String, byte)) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (, 100) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 32 (0x20) .maxstack 3 .locals init (Integer V_0, //i System.ValueTuple(Of String, Byte) V_1) //x IL_0000: ldc.i4.s 100 IL_0002: stloc.0 IL_0003: ldloca.s V_1 IL_0005: ldnull IL_0006: ldloc.0 IL_0007: conv.ovf.u1 IL_0008: call "Sub System.ValueTuple(Of String, Byte)..ctor(String, Byte)" IL_000d: ldloca.s V_1 IL_000f: constrained. "System.ValueTuple(Of String, Byte)" IL_0015: callvirt "Function Object.ToString() As String" IL_001a: call "Sub System.Console.WriteLine(String)" IL_001f: ret } ]]>) Dim compilation = verifier.Compilation Dim tree = compilation.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of DirectCastExpressionSyntax)().Single() Assert.Equal("DirectCast((Nothing, i),(String, byte))", node.ToString()) compilation.VerifyOperationTree(node, expectedOperationTree:= <![CDATA[ IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.String, System.Byte)) (Syntax: 'DirectCast( ... ing, byte))') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.String, i As System.Byte)) (Syntax: '(Nothing, i)') NaturalType: null Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') ]]>.Value) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub SimpleTupleTargetTyped007() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim i as integer = 100 Dim x = TryCast((Nothing, i),(String, byte)) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (, 100) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 32 (0x20) .maxstack 3 .locals init (Integer V_0, //i System.ValueTuple(Of String, Byte) V_1) //x IL_0000: ldc.i4.s 100 IL_0002: stloc.0 IL_0003: ldloca.s V_1 IL_0005: ldnull IL_0006: ldloc.0 IL_0007: conv.ovf.u1 IL_0008: call "Sub System.ValueTuple(Of String, Byte)..ctor(String, Byte)" IL_000d: ldloca.s V_1 IL_000f: constrained. "System.ValueTuple(Of String, Byte)" IL_0015: callvirt "Function Object.ToString() As String" IL_001a: call "Sub System.Console.WriteLine(String)" IL_001f: ret } ]]>) Dim compilation = verifier.Compilation Dim tree = compilation.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of TryCastExpressionSyntax)().Single() Assert.Equal("TryCast((Nothing, i),(String, byte))", node.ToString()) compilation.VerifyOperationTree(node, expectedOperationTree:= <![CDATA[ IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.String, System.Byte)) (Syntax: 'TryCast((No ... ing, byte))') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.String, i As System.Byte)) (Syntax: '(Nothing, i)') NaturalType: null Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') ]]>.Value) Dim model = compilation.GetSemanticModel(tree) Dim typeInfo = model.GetTypeInfo(node.Expression) Assert.Null(typeInfo.Type) Assert.Equal("(System.String, i As System.Byte)", typeInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(node.Expression).Kind) End Sub <Fact> Public Sub TupleConversionWidening() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim i as (x as byte, y as byte) = (a:=100, b:=100) Dim x as (integer, double) = i System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (100, 100) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 48 (0x30) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Double) V_0, //x System.ValueTuple(Of Byte, Byte) V_1) IL_0000: ldc.i4.s 100 IL_0002: ldc.i4.s 100 IL_0004: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)" IL_0009: stloc.1 IL_000a: ldloc.1 IL_000b: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_0010: ldloc.1 IL_0011: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_0016: conv.r8 IL_0017: newobj "Sub System.ValueTuple(Of Integer, Double)..ctor(Integer, Double)" IL_001c: stloc.0 IL_001d: ldloca.s V_0 IL_001f: constrained. "System.ValueTuple(Of Integer, Double)" IL_0025: callvirt "Function Object.ToString() As String" IL_002a: call "Sub System.Console.WriteLine(String)" IL_002f: ret } ]]>) Dim comp = verifier.Compilation Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(a:=100, b:=100)", node.ToString()) Assert.Equal("(a As Integer, b As Integer)", model.GetTypeInfo(node).Type.ToDisplayString()) Assert.Equal("(x As System.Byte, y As System.Byte)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) End Sub <Fact> Public Sub TupleConversionNarrowing() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim i as (Integer, String) = (100, 100) Dim x as (Byte, Byte) = i System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (100, 100) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 58 (0x3a) .maxstack 2 .locals init (System.ValueTuple(Of Byte, Byte) V_0, //x System.ValueTuple(Of Integer, String) V_1) IL_0000: ldc.i4.s 100 IL_0002: ldc.i4.s 100 IL_0004: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String" IL_0009: newobj "Sub System.ValueTuple(Of Integer, String)..ctor(Integer, String)" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldfld "System.ValueTuple(Of Integer, String).Item1 As Integer" IL_0015: conv.ovf.u1 IL_0016: ldloc.1 IL_0017: ldfld "System.ValueTuple(Of Integer, String).Item2 As String" IL_001c: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToByte(String) As Byte" IL_0021: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)" IL_0026: stloc.0 IL_0027: ldloca.s V_0 IL_0029: constrained. "System.ValueTuple(Of Byte, Byte)" IL_002f: callvirt "Function Object.ToString() As String" IL_0034: call "Sub System.Console.WriteLine(String)" IL_0039: ret } ]]>) Dim comp = verifier.Compilation Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(100, 100)", node.ToString()) Assert.Equal("(Integer, Integer)", model.GetTypeInfo(node).Type.ToDisplayString()) Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.NarrowingTuple, model.GetConversion(node).Kind) End Sub <Fact> Public Sub TupleConversionNarrowingUnchecked() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim i as (Integer, String) = (100, 100) Dim x as (Byte, Byte) = i System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), expectedOutput:=<![CDATA[ (100, 100) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 58 (0x3a) .maxstack 2 .locals init (System.ValueTuple(Of Byte, Byte) V_0, //x System.ValueTuple(Of Integer, String) V_1) IL_0000: ldc.i4.s 100 IL_0002: ldc.i4.s 100 IL_0004: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String" IL_0009: newobj "Sub System.ValueTuple(Of Integer, String)..ctor(Integer, String)" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldfld "System.ValueTuple(Of Integer, String).Item1 As Integer" IL_0015: conv.u1 IL_0016: ldloc.1 IL_0017: ldfld "System.ValueTuple(Of Integer, String).Item2 As String" IL_001c: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToByte(String) As Byte" IL_0021: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)" IL_0026: stloc.0 IL_0027: ldloca.s V_0 IL_0029: constrained. "System.ValueTuple(Of Byte, Byte)" IL_002f: callvirt "Function Object.ToString() As String" IL_0034: call "Sub System.Console.WriteLine(String)" IL_0039: ret } ]]>) End Sub <Fact> Public Sub TupleConversionObject() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim i as (object, object) = (1, (2,3)) Dim x as (integer, (integer, integer)) = ctype(i, (integer, (integer, integer))) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (1, (2, 3)) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 86 (0x56) .maxstack 3 .locals init (System.ValueTuple(Of Integer, (Integer, Integer)) V_0, //x System.ValueTuple(Of Object, Object) V_1, System.ValueTuple(Of Integer, Integer) V_2) IL_0000: ldc.i4.1 IL_0001: box "Integer" IL_0006: ldc.i4.2 IL_0007: ldc.i4.3 IL_0008: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_000d: box "System.ValueTuple(Of Integer, Integer)" IL_0012: newobj "Sub System.ValueTuple(Of Object, Object)..ctor(Object, Object)" IL_0017: stloc.1 IL_0018: ldloc.1 IL_0019: ldfld "System.ValueTuple(Of Object, Object).Item1 As Object" IL_001e: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_0023: ldloc.1 IL_0024: ldfld "System.ValueTuple(Of Object, Object).Item2 As Object" IL_0029: dup IL_002a: brtrue.s IL_0038 IL_002c: pop IL_002d: ldloca.s V_2 IL_002f: initobj "System.ValueTuple(Of Integer, Integer)" IL_0035: ldloc.2 IL_0036: br.s IL_003d IL_0038: unbox.any "System.ValueTuple(Of Integer, Integer)" IL_003d: newobj "Sub System.ValueTuple(Of Integer, (Integer, Integer))..ctor(Integer, (Integer, Integer))" IL_0042: stloc.0 IL_0043: ldloca.s V_0 IL_0045: constrained. "System.ValueTuple(Of Integer, (Integer, Integer))" IL_004b: callvirt "Function Object.ToString() As String" IL_0050: call "Sub System.Console.WriteLine(String)" IL_0055: ret } ]]>) End Sub <Fact> Public Sub TupleConversionOverloadResolution() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim b as (byte, byte) = (100, 100) Test(b) Dim i as (integer, integer) = b Test(i) Dim l as (Long, integer) = b Test(l) End Sub Sub Test(x as (integer, integer)) System.Console.Writeline("integer") End SUb Sub Test(x as (Long, Long)) System.Console.Writeline("long") End SUb End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ integer integer long ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 101 (0x65) .maxstack 3 .locals init (System.ValueTuple(Of Byte, Byte) V_0, System.ValueTuple(Of Long, Integer) V_1) IL_0000: ldc.i4.s 100 IL_0002: ldc.i4.s 100 IL_0004: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)" IL_0009: dup IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_0011: ldloc.0 IL_0012: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_0017: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_001c: call "Sub C.Test((Integer, Integer))" IL_0021: dup IL_0022: stloc.0 IL_0023: ldloc.0 IL_0024: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_0029: ldloc.0 IL_002a: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_002f: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0034: call "Sub C.Test((Integer, Integer))" IL_0039: stloc.0 IL_003a: ldloc.0 IL_003b: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_0040: conv.u8 IL_0041: ldloc.0 IL_0042: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_0047: newobj "Sub System.ValueTuple(Of Long, Integer)..ctor(Long, Integer)" IL_004c: stloc.1 IL_004d: ldloc.1 IL_004e: ldfld "System.ValueTuple(Of Long, Integer).Item1 As Long" IL_0053: ldloc.1 IL_0054: ldfld "System.ValueTuple(Of Long, Integer).Item2 As Integer" IL_0059: conv.i8 IL_005a: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)" IL_005f: call "Sub C.Test((Long, Long))" IL_0064: ret } ]]>) End Sub <Fact> Public Sub TupleConversionNullable001() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim i as (x as byte, y as byte)? = (a:=100, b:=100) Dim x as (integer, double) = CType(i, (integer, double)) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (100, 100) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 62 (0x3e) .maxstack 3 .locals init ((x As Byte, y As Byte)? V_0, //i System.ValueTuple(Of Integer, Double) V_1, //x System.ValueTuple(Of Byte, Byte) V_2) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.s 100 IL_0004: ldc.i4.s 100 IL_0006: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)" IL_000b: call "Sub (x As Byte, y As Byte)?..ctor((x As Byte, y As Byte))" IL_0010: ldloca.s V_0 IL_0012: call "Function (x As Byte, y As Byte)?.get_Value() As (x As Byte, y As Byte)" IL_0017: stloc.2 IL_0018: ldloc.2 IL_0019: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_001e: ldloc.2 IL_001f: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_0024: conv.r8 IL_0025: newobj "Sub System.ValueTuple(Of Integer, Double)..ctor(Integer, Double)" IL_002a: stloc.1 IL_002b: ldloca.s V_1 IL_002d: constrained. "System.ValueTuple(Of Integer, Double)" IL_0033: callvirt "Function Object.ToString() As String" IL_0038: call "Sub System.Console.WriteLine(String)" IL_003d: ret } ]]>) End Sub <Fact> Public Sub TupleConversionNullable002() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim i as (x as byte, y as byte) = (a:=100, b:=100) Dim x as (integer, double)? = CType(i, (integer, double)) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (100, 100) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 57 (0x39) .maxstack 3 .locals init (System.ValueTuple(Of Byte, Byte) V_0, //i (Integer, Double)? V_1, //x System.ValueTuple(Of Byte, Byte) V_2) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.s 100 IL_0004: ldc.i4.s 100 IL_0006: call "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)" IL_000b: ldloca.s V_1 IL_000d: ldloc.0 IL_000e: stloc.2 IL_000f: ldloc.2 IL_0010: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_0015: ldloc.2 IL_0016: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_001b: conv.r8 IL_001c: newobj "Sub System.ValueTuple(Of Integer, Double)..ctor(Integer, Double)" IL_0021: call "Sub (Integer, Double)?..ctor((Integer, Double))" IL_0026: ldloca.s V_1 IL_0028: constrained. "(Integer, Double)?" IL_002e: callvirt "Function Object.ToString() As String" IL_0033: call "Sub System.Console.WriteLine(String)" IL_0038: ret } ]]>) End Sub <Fact> Public Sub TupleConversionNullable003() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim i as (x as byte, y as byte)? = (a:=100, b:=100) Dim x = CType(i, (integer, double)?) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (100, 100) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 87 (0x57) .maxstack 3 .locals init ((x As Byte, y As Byte)? V_0, //i (Integer, Double)? V_1, //x (Integer, Double)? V_2, System.ValueTuple(Of Byte, Byte) V_3) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.s 100 IL_0004: ldc.i4.s 100 IL_0006: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)" IL_000b: call "Sub (x As Byte, y As Byte)?..ctor((x As Byte, y As Byte))" IL_0010: ldloca.s V_0 IL_0012: call "Function (x As Byte, y As Byte)?.get_HasValue() As Boolean" IL_0017: brtrue.s IL_0024 IL_0019: ldloca.s V_2 IL_001b: initobj "(Integer, Double)?" IL_0021: ldloc.2 IL_0022: br.s IL_0043 IL_0024: ldloca.s V_0 IL_0026: call "Function (x As Byte, y As Byte)?.GetValueOrDefault() As (x As Byte, y As Byte)" IL_002b: stloc.3 IL_002c: ldloc.3 IL_002d: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_0032: ldloc.3 IL_0033: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_0038: conv.r8 IL_0039: newobj "Sub System.ValueTuple(Of Integer, Double)..ctor(Integer, Double)" IL_003e: newobj "Sub (Integer, Double)?..ctor((Integer, Double))" IL_0043: stloc.1 IL_0044: ldloca.s V_1 IL_0046: constrained. "(Integer, Double)?" IL_004c: callvirt "Function Object.ToString() As String" IL_0051: call "Sub System.Console.WriteLine(String)" IL_0056: ret } ]]>) End Sub <Fact> Public Sub TupleConversionNullable004() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim i as ValueTuple(of byte, byte)? = (a:=100, b:=100) Dim x = CType(i, ValueTuple(of integer, double)?) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (100, 100) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 87 (0x57) .maxstack 3 .locals init ((Byte, Byte)? V_0, //i (Integer, Double)? V_1, //x (Integer, Double)? V_2, System.ValueTuple(Of Byte, Byte) V_3) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.s 100 IL_0004: ldc.i4.s 100 IL_0006: newobj "Sub System.ValueTuple(Of Byte, Byte)..ctor(Byte, Byte)" IL_000b: call "Sub (Byte, Byte)?..ctor((Byte, Byte))" IL_0010: ldloca.s V_0 IL_0012: call "Function (Byte, Byte)?.get_HasValue() As Boolean" IL_0017: brtrue.s IL_0024 IL_0019: ldloca.s V_2 IL_001b: initobj "(Integer, Double)?" IL_0021: ldloc.2 IL_0022: br.s IL_0043 IL_0024: ldloca.s V_0 IL_0026: call "Function (Byte, Byte)?.GetValueOrDefault() As (Byte, Byte)" IL_002b: stloc.3 IL_002c: ldloc.3 IL_002d: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_0032: ldloc.3 IL_0033: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_0038: conv.r8 IL_0039: newobj "Sub System.ValueTuple(Of Integer, Double)..ctor(Integer, Double)" IL_003e: newobj "Sub (Integer, Double)?..ctor((Integer, Double))" IL_0043: stloc.1 IL_0044: ldloca.s V_1 IL_0046: constrained. "(Integer, Double)?" IL_004c: callvirt "Function Object.ToString() As String" IL_0051: call "Sub System.Console.WriteLine(String)" IL_0056: ret } ]]>) End Sub <Fact> Public Sub ImplicitConversions02() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x = (a:=1, b:=1) Dim y As C1 = x x = y System.Console.WriteLine(x) x = CType(CType(x, C1), (integer, integer)) System.Console.WriteLine(x) End Sub End Module Class C1 Public Shared Widening Operator CType(arg as (long, long)) as C1 return new C1() End Operator Public Shared Widening Operator CType(arg as C1) as (c As Byte, d as Byte) return (2, 2) End Operator End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (2, 2) (2, 2) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 125 (0x7d) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer) V_0, System.ValueTuple(Of Byte, Byte) V_1) IL_0000: ldc.i4.1 IL_0001: ldc.i4.1 IL_0002: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_000e: conv.i8 IL_000f: ldloc.0 IL_0010: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0015: conv.i8 IL_0016: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)" IL_001b: call "Function C1.op_Implicit((Long, Long)) As C1" IL_0020: call "Function C1.op_Implicit(C1) As (c As Byte, d As Byte)" IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_002c: ldloc.1 IL_002d: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_0032: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0037: dup IL_0038: box "System.ValueTuple(Of Integer, Integer)" IL_003d: call "Sub System.Console.WriteLine(Object)" IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0049: conv.i8 IL_004a: ldloc.0 IL_004b: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0050: conv.i8 IL_0051: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)" IL_0056: call "Function C1.op_Implicit((Long, Long)) As C1" IL_005b: call "Function C1.op_Implicit(C1) As (c As Byte, d As Byte)" IL_0060: stloc.1 IL_0061: ldloc.1 IL_0062: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_0067: ldloc.1 IL_0068: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_006d: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0072: box "System.ValueTuple(Of Integer, Integer)" IL_0077: call "Sub System.Console.WriteLine(Object)" IL_007c: ret } ]]>) End Sub <Fact> Public Sub ExplicitConversions02() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x = (a:=1, b:=1) Dim y As C1 = CType(x, C1) x = CTYpe(y, (integer, integer)) System.Console.WriteLine(x) x = CType(CType(x, C1), (integer, integer)) System.Console.WriteLine(x) End Sub End Module Class C1 Public Shared Narrowing Operator CType(arg as (long, long)) as C1 return new C1() End Operator Public Shared Narrowing Operator CType(arg as C1) as (c As Byte, d as Byte) return (2, 2) End Operator End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (2, 2) (2, 2) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 125 (0x7d) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer) V_0, System.ValueTuple(Of Byte, Byte) V_1) IL_0000: ldc.i4.1 IL_0001: ldc.i4.1 IL_0002: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_000e: conv.i8 IL_000f: ldloc.0 IL_0010: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0015: conv.i8 IL_0016: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)" IL_001b: call "Function C1.op_Explicit((Long, Long)) As C1" IL_0020: call "Function C1.op_Explicit(C1) As (c As Byte, d As Byte)" IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_002c: ldloc.1 IL_002d: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_0032: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0037: dup IL_0038: box "System.ValueTuple(Of Integer, Integer)" IL_003d: call "Sub System.Console.WriteLine(Object)" IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0049: conv.i8 IL_004a: ldloc.0 IL_004b: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0050: conv.i8 IL_0051: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)" IL_0056: call "Function C1.op_Explicit((Long, Long)) As C1" IL_005b: call "Function C1.op_Explicit(C1) As (c As Byte, d As Byte)" IL_0060: stloc.1 IL_0061: ldloc.1 IL_0062: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_0067: ldloc.1 IL_0068: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_006d: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0072: box "System.ValueTuple(Of Integer, Integer)" IL_0077: call "Sub System.Console.WriteLine(Object)" IL_007c: ret } ]]>) End Sub <Fact> Public Sub ImplicitConversions03() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x = (a:=1, b:=1) Dim y As C1 = x Dim x1 as (integer, integer)? = y System.Console.WriteLine(x1) x1 = CType(CType(x, C1), (integer, integer)?) System.Console.WriteLine(x1) End Sub End Module Class C1 Public Shared Widening Operator CType(arg as (long, long)) as C1 return new C1() End Operator Public Shared Widening Operator CType(arg as C1) as (c As Byte, d as Byte) return (2, 2) End Operator End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (2, 2) (2, 2) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 140 (0x8c) .maxstack 3 .locals init (System.ValueTuple(Of Integer, Integer) V_0, //x C1 V_1, //y System.ValueTuple(Of Integer, Integer) V_2, System.ValueTuple(Of Byte, Byte) V_3) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.1 IL_0004: call "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0009: ldloc.0 IL_000a: stloc.2 IL_000b: ldloc.2 IL_000c: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0011: conv.i8 IL_0012: ldloc.2 IL_0013: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0018: conv.i8 IL_0019: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)" IL_001e: call "Function C1.op_Implicit((Long, Long)) As C1" IL_0023: stloc.1 IL_0024: ldloc.1 IL_0025: call "Function C1.op_Implicit(C1) As (c As Byte, d As Byte)" IL_002a: stloc.3 IL_002b: ldloc.3 IL_002c: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_0031: ldloc.3 IL_0032: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_0037: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_003c: newobj "Sub (Integer, Integer)?..ctor((Integer, Integer))" IL_0041: box "(Integer, Integer)?" IL_0046: call "Sub System.Console.WriteLine(Object)" IL_004b: ldloc.0 IL_004c: stloc.2 IL_004d: ldloc.2 IL_004e: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0053: conv.i8 IL_0054: ldloc.2 IL_0055: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_005a: conv.i8 IL_005b: newobj "Sub System.ValueTuple(Of Long, Long)..ctor(Long, Long)" IL_0060: call "Function C1.op_Implicit((Long, Long)) As C1" IL_0065: call "Function C1.op_Implicit(C1) As (c As Byte, d As Byte)" IL_006a: stloc.3 IL_006b: ldloc.3 IL_006c: ldfld "System.ValueTuple(Of Byte, Byte).Item1 As Byte" IL_0071: ldloc.3 IL_0072: ldfld "System.ValueTuple(Of Byte, Byte).Item2 As Byte" IL_0077: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_007c: newobj "Sub (Integer, Integer)?..ctor((Integer, Integer))" IL_0081: box "(Integer, Integer)?" IL_0086: call "Sub System.Console.WriteLine(Object)" IL_008b: ret } ]]>) End Sub <Fact> Public Sub ImplicitConversions04() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x = (1, (1, (1, (1, (1, (1, 1)))))) Dim y as C1 = x Dim x2 as (integer, integer) = y System.Console.WriteLine(x2) Dim x3 as (integer, (integer, integer)) = y System.Console.WriteLine(x3) Dim x12 as (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, Integer))))))))))) = y System.Console.WriteLine(x12) End Sub End Module Class C1 Private x as Byte Public Shared Widening Operator CType(arg as (long, C1)) as C1 Dim result = new C1() result.x = arg.Item2.x return result End Operator Public Shared Widening Operator CType(arg as (long, long)) as C1 Dim result = new C1() result.x = CByte(arg.Item2) return result End Operator Public Shared Widening Operator CType(arg as C1) as (c As Byte, d as C1) Dim t = arg.x arg.x += 1 return (CByte(t), arg) End Operator Public Shared Widening Operator CType(arg as C1) as (c As Byte, d as Byte) Dim t1 = arg.x arg.x += 1 Dim t2 = arg.x arg.x += 1 return (CByte(t1), CByte(t2)) End Operator End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (1, 2) (3, (4, 5)) (6, (7, (8, (9, (10, (11, (12, (13, (14, (15, (16, 17))))))))))) ]]>) End Sub <Fact> Public Sub ExplicitConversions04() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x = (1, (1, (1, (1, (1, (1, 1)))))) Dim y as C1 = x Dim x2 as (integer, integer) = y System.Console.WriteLine(x2) Dim x3 as (integer, (integer, integer)) = y System.Console.WriteLine(x3) Dim x12 as (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, (Integer, Integer))))))))))) = y System.Console.WriteLine(x12) End Sub End Module Class C1 Private x as Byte Public Shared Narrowing Operator CType(arg as (long, C1)) as C1 Dim result = new C1() result.x = arg.Item2.x return result End Operator Public Shared Narrowing Operator CType(arg as (long, long)) as C1 Dim result = new C1() result.x = CByte(arg.Item2) return result End Operator Public Shared Narrowing Operator CType(arg as C1) as (c As Byte, d as C1) Dim t = arg.x arg.x += 1 return (CByte(t), arg) End Operator Public Shared Narrowing Operator CType(arg as C1) as (c As Byte, d as Byte) Dim t1 = arg.x arg.x += 1 Dim t2 = arg.x arg.x += 1 return (CByte(t1), CByte(t2)) End Operator End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (1, 2) (3, (4, 5)) (6, (7, (8, (9, (10, (11, (12, (13, (14, (15, (16, 17))))))))))) ]]>) End Sub <Fact> Public Sub NarrowingFromNumericConstant_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class C Shared Sub Main() Dim x1 As Byte = 300 Dim x2 As Byte() = { 300 } Dim x3 As (Byte, Byte) = (300, 300) Dim x4 As Byte? = 300 Dim x5 As Byte?() = { 300 } Dim x6 As (Byte?, Byte?) = (300, 300) Dim x7 As (Byte, Byte)? = (300, 300) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected></expected>) End Sub <Fact> Public Sub NarrowingFromNumericConstant_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Public Class C Shared Sub M1 (x as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M1 (x as Short) System.Console.WriteLine("Short") End Sub Shared Sub M2 (x as Byte(), y as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M2 (x as Byte(), y as Short) System.Console.WriteLine("Short") End Sub Shared Sub M3 (x as (Byte, Byte)) System.Console.WriteLine("Byte") End Sub Shared Sub M3 (x as (Short, Short)) System.Console.WriteLine("Short") End Sub Shared Sub M4 (x as (Byte, Byte), y as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M4 (x as (Byte, Byte), y as Short) System.Console.WriteLine("Short") End Sub Shared Sub M5 (x as Byte?) System.Console.WriteLine("Byte") End Sub Shared Sub M5 (x as Short?) System.Console.WriteLine("Short") End Sub Shared Sub M6 (x as (Byte?, Byte?)) System.Console.WriteLine("Byte") End Sub Shared Sub M6 (x as (Short?, Short?)) System.Console.WriteLine("Short") End Sub Shared Sub M7 (x as (Byte, Byte)?) System.Console.WriteLine("Byte") End Sub Shared Sub M7 (x as (Short, Short)?) System.Console.WriteLine("Short") End Sub Shared Sub M8 (x as (Byte, Byte)?, y as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M8 (x as (Byte, Byte)?, y as Short) System.Console.WriteLine("Short") End Sub Shared Sub Main() M1(70000) M2({ 300 }, 70000) M3((70000, 70000)) M4((300, 300), 70000) M5(70000) M6((70000, 70000)) M7((70000, 70000)) M8((300, 300), 70000) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected></expected>) CompileAndVerify(comp, expectedOutput:= "Byte Byte Byte Byte Byte Byte Byte Byte") End Sub <Fact> Public Sub NarrowingFromNumericConstant_03() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class C Shared Sub M1 (x as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M1 (x as Short) System.Console.WriteLine("Short") End Sub Shared Sub M2 (x as Byte(), y as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M2 (x as Byte(), y as Short) System.Console.WriteLine("Short") End Sub Shared Sub M3 (x as (Byte, Byte)) System.Console.WriteLine("Byte") End Sub Shared Sub M3 (x as (Short, Short)) System.Console.WriteLine("Short") End Sub Shared Sub M4 (x as (Byte, Byte), y as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M4 (x as (Byte, Byte), y as Short) System.Console.WriteLine("Short") End Sub Shared Sub M5 (x as Byte?) System.Console.WriteLine("Byte") End Sub Shared Sub M5 (x as Short?) System.Console.WriteLine("Short") End Sub Shared Sub M6 (x as (Byte?, Byte?)) System.Console.WriteLine("Byte") End Sub Shared Sub M6 (x as (Short?, Short?)) System.Console.WriteLine("Short") End Sub Shared Sub M7 (x as (Byte, Byte)?) System.Console.WriteLine("Byte") End Sub Shared Sub M7 (x as (Short, Short)?) System.Console.WriteLine("Short") End Sub Shared Sub M8 (x as (Byte, Byte)?, y as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M8 (x as (Byte, Byte)?, y as Short) System.Console.WriteLine("Short") End Sub Shared Sub Main() M1(70000) M2({ 300 }, 70000) M3((70000, 70000)) M4((300, 300), 70000) M5(70000) M6((70000, 70000)) M7((70000, 70000)) M8((300, 300), 70000) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected></expected>) CompileAndVerify(comp, expectedOutput:= "Byte Byte Byte Byte Byte Byte Byte Byte") End Sub <Fact> Public Sub NarrowingFromNumericConstant_04() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Public Class C Shared Sub M1 (x as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M1 (x as Integer) System.Console.WriteLine("Integer") End Sub Shared Sub M2 (x as Byte?) System.Console.WriteLine("Byte") End Sub Shared Sub M2 (x as Integer?) System.Console.WriteLine("Integer") End Sub Shared Sub M3 (x as Byte()) System.Console.WriteLine("Byte") End Sub Shared Sub M3 (x as Integer()) System.Console.WriteLine("Integer") End Sub Shared Sub M4 (x as (Byte, Byte)) System.Console.WriteLine("Byte") End Sub Shared Sub M4 (x as (Integer, Integer)) System.Console.WriteLine("Integer") End Sub Shared Sub M5 (x as (Byte?, Byte?)) System.Console.WriteLine("Byte") End Sub Shared Sub M5 (x as (Integer?, Integer?)) System.Console.WriteLine("Integer") End Sub Shared Sub M6 (x as (Byte, Byte)?) System.Console.WriteLine("Byte") End Sub Shared Sub M6 (x as (Integer, Integer)?) System.Console.WriteLine("Integer") End Sub Shared Sub M7 (x as (Byte, Byte)()) System.Console.WriteLine("Byte") End Sub Shared Sub M7 (x as (Integer, Integer)()) System.Console.WriteLine("Integer") End Sub Shared Sub Main() M1(1) M2(1) M3({1}) M4((1, 1)) M5((1, 1)) M6((1, 1)) M7({(1, 1)}) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(True), additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected></expected>) CompileAndVerify(comp, expectedOutput:= "Integer Integer Integer Integer Integer Integer Integer") End Sub <Fact> Public Sub NarrowingFromNumericConstant_05() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Public Class C Shared Sub M1 (x as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M1 (x as Long) System.Console.WriteLine("Long") End Sub Shared Sub M2 (x as Byte?) System.Console.WriteLine("Byte") End Sub Shared Sub M2 (x as Long?) System.Console.WriteLine("Long") End Sub Shared Sub M3 (x as Byte()) System.Console.WriteLine("Byte") End Sub Shared Sub M3 (x as Long()) System.Console.WriteLine("Long") End Sub Shared Sub M4 (x as (Byte, Byte)) System.Console.WriteLine("Byte") End Sub Shared Sub M4 (x as (Long, Long)) System.Console.WriteLine("Long") End Sub Shared Sub M5 (x as (Byte?, Byte?)) System.Console.WriteLine("Byte") End Sub Shared Sub M5 (x as (Long?, Long?)) System.Console.WriteLine("Long") End Sub Shared Sub M6 (x as (Byte, Byte)?) System.Console.WriteLine("Byte") End Sub Shared Sub M6 (x as (Long, Long)?) System.Console.WriteLine("Long") End Sub Shared Sub M7 (x as (Byte, Byte)()) System.Console.WriteLine("Byte") End Sub Shared Sub M7 (x as (Long, Long)()) System.Console.WriteLine("Long") End Sub Shared Sub Main() M1(1) M2(1) M3({1}) M4((1, 1)) M5((1, 1)) M6((1, 1)) M7({(1, 1)}) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(True), additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected></expected>) CompileAndVerify(comp, expectedOutput:= "Long Long Long Long Long Long Long") End Sub <Fact> <WorkItem(14473, "https://github.com/dotnet/roslyn/issues/14473")> Public Sub NarrowingFromNumericConstant_06() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class C Shared Sub M2 (x as Byte?) System.Console.WriteLine("Byte") End Sub Shared Sub M3 (x as Byte()) System.Console.WriteLine("Byte") End Sub Shared Sub M5 (x as (Byte?, Byte?)) System.Console.WriteLine("Byte") End Sub Shared Sub M6 (x as Byte?()) System.Console.WriteLine("Byte") End Sub Shared Sub M7 (x as (Byte, Byte)()) System.Console.WriteLine("Byte") End Sub Shared Sub Main() Dim a as Byte? = 1 Dim b as Byte() = {1} Dim c as (Byte?, Byte?) = (1, 1) Dim d as Byte?() = {1} Dim e as (Byte, Byte)() = {(1, 1)} M2(1) M3({1}) M5((1, 1)) M6({1}) M7({(1, 1)}) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(True), additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected></expected>) CompileAndVerify(comp, expectedOutput:= "Byte Byte Byte Byte Byte") End Sub <Fact> <WorkItem(14473, "https://github.com/dotnet/roslyn/issues/14473")> Public Sub NarrowingFromNumericConstant_07() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class C Shared Sub M1 (x as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M2 (x as Byte(), y as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M3 (x as (Byte, Byte)) System.Console.WriteLine("Byte") End Sub Shared Sub M4 (x as (Byte, Byte), y as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub M5 (x as Byte?) System.Console.WriteLine("Byte") End Sub Shared Sub M6 (x as (Byte?, Byte?)) System.Console.WriteLine("Byte") End Sub Shared Sub M7 (x as (Byte, Byte)?) System.Console.WriteLine("Byte") End Sub Shared Sub M8 (x as (Byte, Byte)?, y as Byte) System.Console.WriteLine("Byte") End Sub Shared Sub Main() M1(300) M2({ 300 }, 300) M3((300, 300)) M4((300, 300), 300) M5(70000) M6((70000, 70000)) M7((70000, 70000)) M8((300, 300), 300) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected></expected>) CompileAndVerify(comp, expectedOutput:= "Byte Byte Byte Byte Byte Byte Byte Byte") End Sub <Fact> Public Sub NarrowingFromNumericConstant_08() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Public Class C Shared Sub Main() Dim x00 As (Integer, Integer) = (1, 1) Dim x01 As (Byte, Integer) = (1, 1) Dim x02 As (Integer, Byte) = (1, 1) Dim x03 As (Byte, Long) = (1, 1) Dim x04 As (Long, Byte) = (1, 1) Dim x05 As (Byte, Integer) = (300, 1) Dim x06 As (Integer, Byte) = (1, 300) Dim x07 As (Byte, Long) = (300, 1) Dim x08 As (Long, Byte) = (1, 300) Dim x09 As (Long, Long) = (1, 300) Dim x10 As (Byte, Byte) = (1, 300) Dim x11 As (Byte, Byte) = (300, 1) Dim one As Integer = 1 Dim x12 As (Byte, Byte, Byte) = (one, 300, 1) Dim x13 As (Byte, Byte, Byte) = (300, one, 1) Dim x14 As (Byte, Byte, Byte) = (300, 1, one) Dim x15 As (Byte, Byte) = (one, one) Dim x16 As (Integer, (Byte, Integer)) = (1, (1, 1)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected></expected>) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ToArray() AssertConversions(model, nodes(0), ConversionKind.Identity, ConversionKind.Identity, ConversionKind.Identity) AssertConversions(model, nodes(1), ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.Identity) AssertConversions(model, nodes(2), ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.Identity, ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant) AssertConversions(model, nodes(3), ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.WideningNumeric) AssertConversions(model, nodes(4), ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.WideningNumeric, ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant) AssertConversions(model, nodes(5), ConversionKind.NarrowingTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.Identity) AssertConversions(model, nodes(6), ConversionKind.NarrowingTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.Identity, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant) AssertConversions(model, nodes(7), ConversionKind.NarrowingTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.WideningNumeric) AssertConversions(model, nodes(8), ConversionKind.NarrowingTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.WideningNumeric, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant) AssertConversions(model, nodes(9), ConversionKind.WideningTuple, ConversionKind.WideningNumeric, ConversionKind.WideningNumeric) AssertConversions(model, nodes(10), ConversionKind.NarrowingTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant) AssertConversions(model, nodes(11), ConversionKind.NarrowingTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant) AssertConversions(model, nodes(12), ConversionKind.NarrowingTuple, ConversionKind.NarrowingNumeric, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant) AssertConversions(model, nodes(13), ConversionKind.NarrowingTuple, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.NarrowingNumeric, ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant) AssertConversions(model, nodes(14), ConversionKind.NarrowingTuple, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.NarrowingNumeric) AssertConversions(model, nodes(15), ConversionKind.NarrowingTuple, ConversionKind.NarrowingNumeric, ConversionKind.NarrowingNumeric) AssertConversions(model, nodes(16), ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, ConversionKind.Identity, ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant) End Sub Private Shared Sub AssertConversions(model As SemanticModel, literal As TupleExpressionSyntax, aggregate As ConversionKind, ParamArray parts As ConversionKind()) If parts.Length > 0 Then Assert.Equal(literal.Arguments.Count, parts.Length) For i As Integer = 0 To parts.Length - 1 Assert.Equal(parts(i), model.GetConversion(literal.Arguments(i).Expression).Kind) Next End If Assert.Equal(aggregate, model.GetConversion(literal).Kind) End Sub <Fact> Public Sub Narrowing_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class C Shared Sub M2 (x as Byte?) System.Console.WriteLine("Byte") End Sub Shared Sub M5 (x as (Byte?, Byte?)) System.Console.WriteLine("Byte") End Sub Shared Sub Main() Dim x as integer = 1 Dim a as Byte? = x Dim b as (Byte?, Byte?) = (x, x) M2(x) M5((x, x)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(True), additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected> BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'. Dim a as Byte? = x ~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'. Dim b as (Byte?, Byte?) = (x, x) ~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'. Dim b as (Byte?, Byte?) = (x, x) ~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'. M2(x) ~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'. M5((x, x)) ~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Byte?'. M5((x, x)) ~ </expected>) End Sub <Fact> Public Sub Narrowing_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class C Shared Sub Main() Dim x as integer = 1 Dim x1 = CType(x, Byte) Dim x2 = CType(x, Byte?) Dim x3 = CType((x, x), (Byte, Integer)) Dim x4 = CType((x, x), (Byte?, Integer?)) Dim x5 = CType((x, x), (Byte, Integer)?) Dim x6 = CType((x, x), (Byte?, Integer?)?) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp) End Sub <Fact> Public Sub Narrowing_03() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class C Shared Sub Main() Dim x as (Integer, Integer) = (1, 1) Dim x3 = CType(x, (Byte, Integer)) Dim x4 = CType(x, (Byte?, Integer?)) Dim x5 = CType(x, (Byte, Integer)?) Dim x6 = CType(x, (Byte?, Integer?)?) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp) End Sub <Fact> Public Sub Narrowing_04() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class C Shared Sub Main() Dim x as (Integer, Integer) = (1, 1) Dim x3 as (Byte, Integer) = x Dim x4 as (Byte?, Integer?) = x Dim x5 as (Byte, Integer)? = x Dim x6 as (Byte?, Integer?)?= x End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected> BC30512: Option Strict On disallows implicit conversions from '(Integer, Integer)' to '(Byte, Integer)'. Dim x3 as (Byte, Integer) = x ~ BC30512: Option Strict On disallows implicit conversions from '(Integer, Integer)' to '(Byte?, Integer?)'. Dim x4 as (Byte?, Integer?) = x ~ BC30512: Option Strict On disallows implicit conversions from '(Integer, Integer)' to '(Byte, Integer)?'. Dim x5 as (Byte, Integer)? = x ~ BC30512: Option Strict On disallows implicit conversions from '(Integer, Integer)' to '(Byte?, Integer?)?'. Dim x6 as (Byte?, Integer?)?= x ~ </expected>) End Sub <Fact> Public Sub OverloadResolution_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class C Shared Sub M1 (x as Short) System.Console.WriteLine("Short") End Sub Shared Sub M1 (x as Integer) System.Console.WriteLine("Integer") End Sub Shared Sub M2 (x as Short?) System.Console.WriteLine("Short") End Sub Shared Sub M2 (x as Integer?) System.Console.WriteLine("Integer") End Sub Shared Sub M3 (x as (Short, Short)) System.Console.WriteLine("Short") End Sub Shared Sub M3(x as (Integer, Integer)) System.Console.WriteLine("Integer") End Sub Shared Sub M4 (x as (Short?, Short?)) System.Console.WriteLine("Short") End Sub Shared Sub M4(x as (Integer?, Integer?)) System.Console.WriteLine("Integer") End Sub Shared Sub M5 (x as (Short, Short)?) System.Console.WriteLine("Short") End Sub Shared Sub M5(x as (Integer, Integer)?) System.Console.WriteLine("Integer") End Sub Shared Sub Main() Dim x as Byte = 1 M1(x) M2(x) M3((x, x)) M4((x, x)) M5((x, x)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected></expected>) CompileAndVerify(comp, expectedOutput:= "Short Short Short Short Short") End Sub <Fact> Public Sub FailedDueToNumericOverflow_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Public Class C Shared Sub Main() Dim x1 As Byte = 300 Dim x2 as (Integer, Byte) = (300, 300) Dim x3 As Byte? = 300 Dim x4 as (Integer?, Byte?) = (300, 300) Dim x5 as (Integer, Byte)? = (300, 300) Dim x6 as (Integer?, Byte?)? = (300, 300) System.Console.WriteLine(x1) System.Console.WriteLine(x2) System.Console.WriteLine(x3) System.Console.WriteLine(x4) System.Console.WriteLine(x5) System.Console.WriteLine(x6) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected></expected>) CompileAndVerify(comp, expectedOutput:= "44 (300, 44) 44 (300, 44) (300, 44) (300, 44)") comp = comp.WithOptions(comp.Options.WithOverflowChecks(True)) AssertTheseDiagnostics(comp, <expected> BC30439: Constant expression not representable in type 'Byte'. Dim x1 As Byte = 300 ~~~ BC30439: Constant expression not representable in type 'Byte'. Dim x2 as (Integer, Byte) = (300, 300) ~~~ BC30439: Constant expression not representable in type 'Byte?'. Dim x3 As Byte? = 300 ~~~ BC30439: Constant expression not representable in type 'Byte?'. Dim x4 as (Integer?, Byte?) = (300, 300) ~~~ BC30439: Constant expression not representable in type 'Byte'. Dim x5 as (Integer, Byte)? = (300, 300) ~~~ BC30439: Constant expression not representable in type 'Byte?'. Dim x6 as (Integer?, Byte?)? = (300, 300) ~~~ </expected>) End Sub <Fact> Public Sub MethodTypeInference001() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() System.Console.WriteLine(Test((1,"q"))) End Sub Function Test(of T1, T2)(x as (T1, T2)) as (T1, T2) Console.WriteLine(Gettype(T1)) Console.WriteLine(Gettype(T2)) return x End Function End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.Int32 System.String (1, q) ]]>) End Sub <Fact> Public Sub MethodTypeInference002() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim v = (new Object(),"q") Test(v) System.Console.WriteLine(v) End Sub Function Test(of T)(x as (T, T)) as (T, T) Console.WriteLine(Gettype(T)) return x End Function End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.Object (System.Object, q) ]]>) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 51 (0x33) .maxstack 3 .locals init (System.ValueTuple(Of Object, String) V_0) IL_0000: newobj "Sub Object..ctor()" IL_0005: ldstr "q" IL_000a: newobj "Sub System.ValueTuple(Of Object, String)..ctor(Object, String)" IL_000f: dup IL_0010: stloc.0 IL_0011: ldloc.0 IL_0012: ldfld "System.ValueTuple(Of Object, String).Item1 As Object" IL_0017: ldloc.0 IL_0018: ldfld "System.ValueTuple(Of Object, String).Item2 As String" IL_001d: newobj "Sub System.ValueTuple(Of Object, Object)..ctor(Object, Object)" IL_0022: call "Function C.Test(Of Object)((Object, Object)) As (Object, Object)" IL_0027: pop IL_0028: box "System.ValueTuple(Of Object, String)" IL_002d: call "Sub System.Console.WriteLine(Object)" IL_0032: ret } ]]>) End Sub <Fact> Public Sub MethodTypeInference002Err() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim v = (new Object(),"q") Test(v) System.Console.WriteLine(v) TestRef(v) System.Console.WriteLine(v) End Sub Function Test(of T)(x as (T, T)) as (T, T) Console.WriteLine(Gettype(T)) return x End Function Function TestRef(of T)(ByRef x as (T, T)) as (T, T) Console.WriteLine(Gettype(T)) x.Item1 = x.Item2 return x End Function End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC36651: Data type(s) of the type parameter(s) in method 'Public Function TestRef(Of T)(ByRef x As (T, T)) As (T, T)' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error. TestRef(v) ~~~~~~~ </errors>) End Sub <Fact> Public Sub MethodTypeInference003() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() System.Console.WriteLine(Test((Nothing,"q"))) System.Console.WriteLine(Test(("q", Nothing))) System.Console.WriteLine(Test1((Nothing, Nothing), (Nothing,"q"))) System.Console.WriteLine(Test1(("q", Nothing), (Nothing, Nothing))) End Sub Function Test(of T)(x as (T, T)) as (T, T) Console.WriteLine(Gettype(T)) return x End Function Function Test1(of T)(x as (T, T), y as (T, T)) as (T, T) Console.WriteLine(Gettype(T)) return x End Function End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.String (, q) System.String (q, ) System.String (, ) System.String (q, ) ]]>) End Sub <Fact> Public Sub MethodTypeInference004() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim q = "q" Dim a As Object = "a" System.Console.WriteLine(Test((q, a))) System.Console.WriteLine(q) System.Console.WriteLine(a) System.Console.WriteLine(Test((Ps, Po))) System.Console.WriteLine(q) System.Console.WriteLine(a) End Sub Function Test(Of T)(ByRef x As (T, T)) As (T, T) Console.WriteLine(GetType(T)) x.Item1 = x.Item2 Return x End Function Public Property Ps As String Get Return "q" End Get Set(value As String) System.Console.WriteLine("written1 !!!") End Set End Property Public Property Po As Object Get Return "a" End Get Set(value As Object) System.Console.WriteLine("written2 !!!") End Set End Property End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.Object (a, a) q a System.Object (a, a) q a ]]>) End Sub <Fact> Public Sub MethodTypeInference004a() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() System.Console.WriteLine(Test((new Object(),"q"))) System.Console.WriteLine(Test1((new Object(),"q"))) End Sub Function Test(of T)(x as (T, T)) as (T, T) Console.WriteLine(Gettype(T)) return x End Function Function Test1(of T)(x as T) as T Console.WriteLine(Gettype(T)) return x End Function End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.Object (System.Object, q) System.ValueTuple`2[System.Object,System.String] (System.Object, q) ]]>) End Sub <Fact> Public Sub MethodTypeInference004Err() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim q = "q" Dim a as object = "a" Dim t = (q, a) System.Console.WriteLine(Test(t)) System.Console.WriteLine(q) System.Console.WriteLine(a) End Sub Function Test(of T)(byref x as (T, T)) as (T, T) Console.WriteLine(Gettype(T)) x.Item1 = x.Item2 return x End Function End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC36651: Data type(s) of the type parameter(s) in method 'Public Function Test(Of T)(ByRef x As (T, T)) As (T, T)' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error. System.Console.WriteLine(Test(t)) ~~~~ </errors>) End Sub <Fact> Public Sub MethodTypeInference005() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Module1 Sub Main() Dim ie As IEnumerable(Of String) = {1, 2} Dim t = (ie, ie) Test(t, New Object) Test((ie, ie), New Object) End Sub Sub Test(Of T)(a1 As (IEnumerable(Of T), IEnumerable(Of T)), a2 As T) System.Console.WriteLine(GetType(T)) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.Object System.Object ]]>) End Sub <Fact> Public Sub MethodTypeInference006() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Module1 Sub Main() Dim ie As IEnumerable(Of Integer) = {1, 2} Dim t = (ie, ie) Test(t) Test((1, 1)) End Sub Sub Test(Of T)(f1 As IComparable(Of (T, T))) System.Console.WriteLine(GetType(T)) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.Collections.Generic.IEnumerable`1[System.Int32] System.Int32 ]]>) End Sub <Fact> Public Sub MethodTypeInference007() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Module1 Sub Main() Dim ie As IEnumerable(Of Integer) = {1, 2} Dim t = (ie, ie) Test(t) Test((1, 1)) End Sub Sub Test(Of T)(f1 As IComparable(Of (T, T))) System.Console.WriteLine(GetType(T)) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.Collections.Generic.IEnumerable`1[System.Int32] System.Int32 ]]>) End Sub <Fact> Public Sub MethodTypeInference008() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Module1 Sub Main() Dim t = (1, 1L) ' these are valid Test1(t) Test1((1, 1L)) End Sub Sub Test1(Of T)(f1 As (T, T)) System.Console.WriteLine(GetType(T)) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.Int64 System.Int64 ]]>) End Sub <Fact> Public Sub MethodTypeInference008Err() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Module Module1 Sub Main() Dim t = (1, 1L) ' these are valid Test1(t) Test1((1, 1L)) ' these are not Test2(t) Test2((1, 1L)) End Sub Sub Test1(Of T)(f1 As (T, T)) System.Console.WriteLine(GetType(T)) End Sub Sub Test2(Of T)(f1 As IComparable(Of (T, T))) System.Console.WriteLine(GetType(T)) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC36657: Data type(s) of the type parameter(s) in method 'Public Sub Test2(Of T)(f1 As IComparable(Of (T, T)))' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error. Test2(t) ~~~~~ BC36657: Data type(s) of the type parameter(s) in method 'Public Sub Test2(Of T)(f1 As IComparable(Of (T, T)))' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error. Test2((1, 1L)) ~~~~~ </errors>) End Sub <Fact> Public Sub Inference04() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Test( Function(x)x.y ) Test( Function(x)x.bob ) End Sub Sub Test(of T)(x as Func(of (x as Byte, y As Byte), T)) System.Console.WriteLine("first") System.Console.WriteLine(x((2,3)).ToString()) End Sub Sub Test(of T)(x as Func(of (alice as integer, bob as integer), T)) System.Console.WriteLine("second") System.Console.WriteLine(x((4,5)).ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ first 3 second 5 ]]>) End Sub <Fact> Public Sub Inference07() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Test(Function(x)(x, x), Function(t)1) Test1(Function(x)(x, x), Function(t)1) Test2((a:= 1, b:= 2), Function(t)(t.a, t.b)) End Sub Sub Test(Of U)(f1 as Func(of Integer, ValueTuple(Of U, U)), f2 as Func(Of ValueTuple(Of U, U), Integer)) System.Console.WriteLine(f2(f1(1))) End Sub Sub Test1(of U)(f1 As Func(of integer, (U, U)), f2 as Func(Of (U, U), integer)) System.Console.WriteLine(f2(f1(1))) End Sub Sub Test2(of U, T)(f1 as U , f2 As Func(Of U, (x as T, y As T))) System.Console.WriteLine(f2(f1).y) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ 1 1 2 ]]>) End Sub <Fact> Public Sub InferenceChain001() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Test(Function(x As (Integer, Integer)) (x, x), Function(t) (t, t)) End Sub Sub Test(Of T, U, V)(f1 As Func(Of (T,T), (U,U)), f2 As Func(Of (U,U), (V,V))) System.Console.WriteLine(f2(f1(Nothing))) System.Console.WriteLine(GetType(T)) System.Console.WriteLine(GetType(U)) System.Console.WriteLine(GetType(V)) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (((0, 0), (0, 0)), ((0, 0), (0, 0))) System.Int32 System.ValueTuple`2[System.Int32,System.Int32] System.ValueTuple`2[System.ValueTuple`2[System.Int32,System.Int32],System.ValueTuple`2[System.Int32,System.Int32]] ]]>) End Sub <Fact> Public Sub InferenceChain002() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Test(Function(x As (Integer, Object)) (x, x), Function(t) (t, t)) End Sub Sub Test(Of T, U, V)(ByRef f1 As Func(Of (T, T), (U, U)), ByRef f2 As Func(Of (U, U), (V, V))) System.Console.WriteLine(f2(f1(Nothing))) System.Console.WriteLine(GetType(T)) System.Console.WriteLine(GetType(U)) System.Console.WriteLine(GetType(V)) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (((0, ), (0, )), ((0, ), (0, ))) System.Object System.ValueTuple`2[System.Int32,System.Object] System.ValueTuple`2[System.ValueTuple`2[System.Int32,System.Object],System.ValueTuple`2[System.Int32,System.Object]] ]]>) End Sub <Fact> Public Sub SimpleTupleNested() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = (1, (2, (3, 4)).ToString()) System.Console.Write(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(1, (2, (3, 4)))]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("Module1.Main", <![CDATA[ { // Code size 54 (0x36) .maxstack 5 .locals init (System.ValueTuple(Of Integer, String) V_0, //x System.ValueTuple(Of Integer, (Integer, Integer)) V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: ldc.i4.3 IL_0005: ldc.i4.4 IL_0006: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_000b: newobj "Sub System.ValueTuple(Of Integer, (Integer, Integer))..ctor(Integer, (Integer, Integer))" IL_0010: stloc.1 IL_0011: ldloca.s V_1 IL_0013: constrained. "System.ValueTuple(Of Integer, (Integer, Integer))" IL_0019: callvirt "Function Object.ToString() As String" IL_001e: call "Sub System.ValueTuple(Of Integer, String)..ctor(Integer, String)" IL_0023: ldloca.s V_0 IL_0025: constrained. "System.ValueTuple(Of Integer, String)" IL_002b: callvirt "Function Object.ToString() As String" IL_0030: call "Sub System.Console.Write(String)" IL_0035: ret } ]]>) End Sub <Fact> Public Sub TupleUnderlyingItemAccess() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = (1, 2) System.Console.WriteLine(x.Item2.ToString()) x.Item1 = 40 System.Console.WriteLine(x.Item1 + x.Item2) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[2 42]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("Module1.Main", <![CDATA[ { // Code size 54 (0x36) .maxstack 3 .locals init (System.ValueTuple(Of Integer, Integer) V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: call "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0009: ldloca.s V_0 IL_000b: ldflda "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0010: call "Function Integer.ToString() As String" IL_0015: call "Sub System.Console.WriteLine(String)" IL_001a: ldloca.s V_0 IL_001c: ldc.i4.s 40 IL_001e: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0023: ldloc.0 IL_0024: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0029: ldloc.0 IL_002a: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_002f: add.ovf IL_0030: call "Sub System.Console.WriteLine(Integer)" IL_0035: ret } ]]>) End Sub <Fact> Public Sub TupleUnderlyingItemAccess01() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = (A:=1, B:=2) System.Console.WriteLine(x.Item2.ToString()) x.Item1 = 40 System.Console.WriteLine(x.Item1 + x.Item2) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[2 42]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("Module1.Main", <![CDATA[ { // Code size 54 (0x36) .maxstack 3 .locals init (System.ValueTuple(Of Integer, Integer) V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: call "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0009: ldloca.s V_0 IL_000b: ldflda "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0010: call "Function Integer.ToString() As String" IL_0015: call "Sub System.Console.WriteLine(String)" IL_001a: ldloca.s V_0 IL_001c: ldc.i4.s 40 IL_001e: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0023: ldloc.0 IL_0024: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0029: ldloc.0 IL_002a: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_002f: add.ovf IL_0030: call "Sub System.Console.WriteLine(Integer)" IL_0035: ret } ]]>) End Sub <Fact> Public Sub TupleItemAccess() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = (A:=1, B:=2) System.Console.WriteLine(x.Item2.ToString()) x.A = 40 System.Console.WriteLine(x.A + x.B) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[2 42]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("Module1.Main", <![CDATA[ { // Code size 54 (0x36) .maxstack 3 .locals init (System.ValueTuple(Of Integer, Integer) V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: call "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0009: ldloca.s V_0 IL_000b: ldflda "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0010: call "Function Integer.ToString() As String" IL_0015: call "Sub System.Console.WriteLine(String)" IL_001a: ldloca.s V_0 IL_001c: ldc.i4.s 40 IL_001e: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0023: ldloc.0 IL_0024: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0029: ldloc.0 IL_002a: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_002f: add.ovf IL_0030: call "Sub System.Console.WriteLine(Integer)" IL_0035: ret } ]]>) End Sub <Fact> Public Sub TupleItemAccess01() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x = (A:=1, B:=(C:=2, D:= 3)) System.Console.WriteLine(x.B.C.ToString()) x.B.D = 39 System.Console.WriteLine(x.A + x.B.C + x.B.D) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[2 42]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("Module1.Main", <![CDATA[ { // Code size 87 (0x57) .maxstack 4 .locals init (System.ValueTuple(Of Integer, (C As Integer, D As Integer)) V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldc.i4.2 IL_0004: ldc.i4.3 IL_0005: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_000a: call "Sub System.ValueTuple(Of Integer, (C As Integer, D As Integer))..ctor(Integer, (C As Integer, D As Integer))" IL_000f: ldloca.s V_0 IL_0011: ldflda "System.ValueTuple(Of Integer, (C As Integer, D As Integer)).Item2 As (C As Integer, D As Integer)" IL_0016: ldflda "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_001b: call "Function Integer.ToString() As String" IL_0020: call "Sub System.Console.WriteLine(String)" IL_0025: ldloca.s V_0 IL_0027: ldflda "System.ValueTuple(Of Integer, (C As Integer, D As Integer)).Item2 As (C As Integer, D As Integer)" IL_002c: ldc.i4.s 39 IL_002e: stfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0033: ldloc.0 IL_0034: ldfld "System.ValueTuple(Of Integer, (C As Integer, D As Integer)).Item1 As Integer" IL_0039: ldloc.0 IL_003a: ldfld "System.ValueTuple(Of Integer, (C As Integer, D As Integer)).Item2 As (C As Integer, D As Integer)" IL_003f: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0044: add.ovf IL_0045: ldloc.0 IL_0046: ldfld "System.ValueTuple(Of Integer, (C As Integer, D As Integer)).Item2 As (C As Integer, D As Integer)" IL_004b: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_0050: add.ovf IL_0051: call "Sub System.Console.WriteLine(Integer)" IL_0056: ret } ]]>) End Sub <Fact> Public Sub TupleTypeDeclaration() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As (Integer, String, Integer) = (1, "hello", 2) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(1, hello, 2)]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("Module1.Main", <![CDATA[ { // Code size 33 (0x21) .maxstack 4 .locals init (System.ValueTuple(Of Integer, String, Integer) V_0) //x IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldstr "hello" IL_0008: ldc.i4.2 IL_0009: call "Sub System.ValueTuple(Of Integer, String, Integer)..ctor(Integer, String, Integer)" IL_000e: ldloca.s V_0 IL_0010: constrained. "System.ValueTuple(Of Integer, String, Integer)" IL_0016: callvirt "Function Object.ToString() As String" IL_001b: call "Sub System.Console.WriteLine(String)" IL_0020: ret } ]]>) End Sub <Fact> Public Sub TupleTypeMismatch_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x As (Integer, String) = (1, "hello", 2) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30311: Value of type '(Integer, String, Integer)' cannot be converted to '(Integer, String)'. Dim x As (Integer, String) = (1, "hello", 2) ~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleTypeMismatch_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x As (Integer, String) = (1, Nothing, 2) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30311: Value of type '(Integer, Object, Integer)' cannot be converted to '(Integer, String)'. Dim x As (Integer, String) = (1, Nothing, 2) ~~~~~~~~~~~~~~~ </errors>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub LongTupleTypeMismatch() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = ("Alice", 2, 3, 4, 5, 6, 7, 8) Dim y As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = (1, 2, 3, 4, 5, 6, 7, 8) End Sub End Module ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC37267: Predefined type 'ValueTuple(Of )' is not defined or imported. Dim x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = ("Alice", 2, 3, 4, 5, 6, 7, 8) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of ,,,,,,,)' is not defined or imported. Dim x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = ("Alice", 2, 3, 4, 5, 6, 7, 8) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of )' is not defined or imported. Dim x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = ("Alice", 2, 3, 4, 5, 6, 7, 8) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of ,,,,,,,)' is not defined or imported. Dim x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = ("Alice", 2, 3, 4, 5, 6, 7, 8) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of )' is not defined or imported. Dim y As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = (1, 2, 3, 4, 5, 6, 7, 8) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of ,,,,,,,)' is not defined or imported. Dim y As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = (1, 2, 3, 4, 5, 6, 7, 8) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of )' is not defined or imported. Dim y As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = (1, 2, 3, 4, 5, 6, 7, 8) ~~~~~~~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of ,,,,,,,)' is not defined or imported. Dim y As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = (1, 2, 3, 4, 5, 6, 7, 8) ~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleTypeWithLateDiscoveredName() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x As (Integer, A As String) = (1, "hello", C:=2) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30311: Value of type '(Integer, String, C As Integer)' cannot be converted to '(Integer, A As String)'. Dim x As (Integer, A As String) = (1, "hello", C:=2) ~~~~~~~~~~~~~~~~~~ </errors>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(1, ""hello"", C:=2)", node.ToString()) Assert.Equal("(System.Int32, System.String, C As System.Int32)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Dim xSymbol = DirectCast(model.GetDeclaredSymbol(x), LocalSymbol).Type Assert.Equal("(System.Int32, A As System.String)", xSymbol.ToTestDisplayString()) Assert.True(xSymbol.IsTupleType) Assert.False(DirectCast(xSymbol, INamedTypeSymbol).IsSerializable) Assert.Equal({"System.Int32", "System.String"}, xSymbol.TupleElementTypes.SelectAsArray(Function(t) t.ToTestDisplayString())) Assert.Equal({Nothing, "A"}, xSymbol.TupleElementNames) End Sub <Fact> Public Sub TupleTypeDeclarationWithNames() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As (A As Integer, B As String) = (1, "hello") System.Console.WriteLine(x.A.ToString()) System.Console.WriteLine(x.B.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1 hello]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleDictionary01() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Collections.Generic Class C Shared Sub Main() Dim k = (1, 2) Dim v = (A:=1, B:=(C:=2, D:=(E:=3, F:=4))) Dim d = Test(k, v) System.Console.Write(d((1, 2)).B.D.Item2) End Sub Shared Function Test(Of K, V)(key As K, value As V) As Dictionary(Of K, V) Dim d = new Dictionary(Of K, V)() d(key) = value return d End Function End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[4]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 67 (0x43) .maxstack 6 .locals init (System.ValueTuple(Of Integer, (C As Integer, D As (E As Integer, F As Integer))) V_0) //v IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0007: ldloca.s V_0 IL_0009: ldc.i4.1 IL_000a: ldc.i4.2 IL_000b: ldc.i4.3 IL_000c: ldc.i4.4 IL_000d: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0012: newobj "Sub System.ValueTuple(Of Integer, (E As Integer, F As Integer))..ctor(Integer, (E As Integer, F As Integer))" IL_0017: call "Sub System.ValueTuple(Of Integer, (C As Integer, D As (E As Integer, F As Integer)))..ctor(Integer, (C As Integer, D As (E As Integer, F As Integer)))" IL_001c: ldloc.0 IL_001d: call "Function C.Test(Of (Integer, Integer), (A As Integer, B As (C As Integer, D As (E As Integer, F As Integer))))((Integer, Integer), (A As Integer, B As (C As Integer, D As (E As Integer, F As Integer)))) As System.Collections.Generic.Dictionary(Of (Integer, Integer), (A As Integer, B As (C As Integer, D As (E As Integer, F As Integer))))" IL_0022: ldc.i4.1 IL_0023: ldc.i4.2 IL_0024: newobj "Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)" IL_0029: callvirt "Function System.Collections.Generic.Dictionary(Of (Integer, Integer), (A As Integer, B As (C As Integer, D As (E As Integer, F As Integer)))).get_Item((Integer, Integer)) As (A As Integer, B As (C As Integer, D As (E As Integer, F As Integer)))" IL_002e: ldfld "System.ValueTuple(Of Integer, (C As Integer, D As (E As Integer, F As Integer))).Item2 As (C As Integer, D As (E As Integer, F As Integer))" IL_0033: ldfld "System.ValueTuple(Of Integer, (E As Integer, F As Integer)).Item2 As (E As Integer, F As Integer)" IL_0038: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_003d: call "Sub System.Console.Write(Integer)" IL_0042: ret } ]]>) End Sub <Fact> Public Sub TupleLambdaCapture01() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() System.Console.Write(Test(42)) End Sub Public Shared Function Test(Of T)(a As T) As T Dim x = (f1:=a, f2:=a) Dim f As System.Func(Of T) = Function() x.f2 return f() End Function End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("C._Closure$__2-0(Of $CLS0)._Lambda$__0()", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda "C._Closure$__2-0(Of $CLS0).$VB$Local_x As (f1 As $CLS0, f2 As $CLS0)" IL_0006: ldfld "System.ValueTuple(Of $CLS0, $CLS0).Item2 As $CLS0" IL_000b: ret } ]]>) End Sub <Fact> Public Sub TupleLambdaCapture02() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() System.Console.Write(Test(42)) End Sub Shared Function Test(Of T)(a As T) As String Dim x = (f1:=a, f2:=a) Dim f As System.Func(Of String) = Function() x.ToString() Return f() End Function End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(42, 42)]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("C._Closure$__2-0(Of $CLS0)._Lambda$__0()", <![CDATA[ { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda "C._Closure$__2-0(Of $CLS0).$VB$Local_x As (f1 As $CLS0, f2 As $CLS0)" IL_0006: constrained. "System.ValueTuple(Of $CLS0, $CLS0)" IL_000c: callvirt "Function Object.ToString() As String" IL_0011: ret } ]]>) End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/13298")> Public Sub TupleLambdaCapture03() ' This test crashes in TypeSubstitution Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() System.Console.Write(Test(42)) End Sub Shared Function Test(Of T)(a As T) As T Dim x = (f1:=a, f2:=b) Dim f As System.Func(Of T) = Function() x.Test(a) Return f() End Function End Class Namespace System Public Structure ValueTuple(Of T1, T2) Public Item1 As T1 Public Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}" End Function Public Function Test(Of U)(val As U) As U Return val End Function End Structure End Namespace </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("Module1.Main", <![CDATA[ ]]>) End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/pull/13209")> Public Sub TupleLambdaCapture04() ' this test crashes in TypeSubstitution Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() System.Console.Write(Test(42)) End Sub Shared Function Test(Of T)(a As T) As T Dim x = (f1:=1, f2:=2) Dim f As System.Func(Of T) = Function() x.Test(a) Return f() End Function End Class Namespace System Public Structure ValueTuple(Of T1, T2) Public Item1 As T1 Public Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}" End Function Public Function Test(Of U)(val As U) As U Return val End Function End Structure End Namespace </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("Module1.Main", <![CDATA[ ]]>) End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/pull/13209")> Public Sub TupleLambdaCapture05() ' this test crashes in TypeSubstitution Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() System.Console.Write(Test(42)) End Sub Shared Function Test(Of T)(a As T) As T Dim x = (f1:=a, f2:=a) Dim f As System.Func(Of T) = Function() x.P1 Return f() End Function End Class Namespace System Public Structure ValueTuple(Of T1, T2) Public Item1 As T1 Public Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}" End Function Public ReadOnly Property P1 As T1 Get Return Item1 End Get End Property End Structure End Namespace </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("Module1.Main", <![CDATA[ ]]>) End Sub <Fact> Public Sub TupleAsyncCapture01() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Threading.Tasks Class C Shared Sub Main() Console.Write(Test(42).Result) End Sub Shared Async Function Test(Of T)(a As T) As Task(Of T) Dim x = (f1:=a, f2:=a) Await Task.Yield() Return x.f1 End Function End Class </file> </compilation>, references:={ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef_v46}, expectedOutput:=<![CDATA[42]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("C.VB$StateMachine_2_Test(Of SM$T).MoveNext()", <![CDATA[ { // Code size 204 (0xcc) .maxstack 3 .locals init (SM$T V_0, Integer V_1, System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2, System.Runtime.CompilerServices.YieldAwaitable V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer" IL_0006: stloc.1 .try { IL_0007: ldloc.1 IL_0008: brfalse.s IL_0058 IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$VB$Local_a As SM$T" IL_0011: ldarg.0 IL_0012: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$VB$Local_a As SM$T" IL_0017: newobj "Sub System.ValueTuple(Of SM$T, SM$T)..ctor(SM$T, SM$T)" IL_001c: stfld "C.VB$StateMachine_2_Test(Of SM$T).$VB$ResumableLocal_x$0 As (f1 As SM$T, f2 As SM$T)" IL_0021: call "Function System.Threading.Tasks.Task.Yield() As System.Runtime.CompilerServices.YieldAwaitable" IL_0026: stloc.3 IL_0027: ldloca.s V_3 IL_0029: call "Function System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter() As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_002e: stloc.2 IL_002f: ldloca.s V_2 IL_0031: call "Function System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.get_IsCompleted() As Boolean" IL_0036: brtrue.s IL_0074 IL_0038: ldarg.0 IL_0039: ldc.i4.0 IL_003a: dup IL_003b: stloc.1 IL_003c: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer" IL_0041: ldarg.0 IL_0042: ldloc.2 IL_0043: stfld "C.VB$StateMachine_2_Test(Of SM$T).$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0048: ldarg.0 IL_0049: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of SM$T)" IL_004e: ldloca.s V_2 IL_0050: ldarg.0 IL_0051: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of SM$T).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.VB$StateMachine_2_Test(Of SM$T))(ByRef System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ByRef C.VB$StateMachine_2_Test(Of SM$T))" IL_0056: leave.s IL_00cb IL_0058: ldarg.0 IL_0059: ldc.i4.m1 IL_005a: dup IL_005b: stloc.1 IL_005c: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer" IL_0061: ldarg.0 IL_0062: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0067: stloc.2 IL_0068: ldarg.0 IL_0069: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_006e: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0074: ldloca.s V_2 IL_0076: call "Sub System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()" IL_007b: ldloca.s V_2 IL_007d: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0083: ldarg.0 IL_0084: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$VB$ResumableLocal_x$0 As (f1 As SM$T, f2 As SM$T)" IL_0089: ldfld "System.ValueTuple(Of SM$T, SM$T).Item1 As SM$T" IL_008e: stloc.0 IL_008f: leave.s IL_00b5 } catch System.Exception { IL_0091: dup IL_0092: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)" IL_0097: stloc.s V_4 IL_0099: ldarg.0 IL_009a: ldc.i4.s -2 IL_009c: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer" IL_00a1: ldarg.0 IL_00a2: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of SM$T)" IL_00a7: ldloc.s V_4 IL_00a9: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of SM$T).SetException(System.Exception)" IL_00ae: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_00b3: leave.s IL_00cb } IL_00b5: ldarg.0 IL_00b6: ldc.i4.s -2 IL_00b8: dup IL_00b9: stloc.1 IL_00ba: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer" IL_00bf: ldarg.0 IL_00c0: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of SM$T)" IL_00c5: ldloc.0 IL_00c6: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of SM$T).SetResult(SM$T)" IL_00cb: ret } ]]>) End Sub <Fact> Public Sub TupleAsyncCapture02() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Threading.Tasks Class C Shared Sub Main() Console.Write(Test(42).Result) End Sub Shared Async Function Test(Of T)(a As T) As Task(Of String) Dim x = (f1:=a, f2:=a) Await Task.Yield() Return x.ToString() End Function End Class </file> </compilation>, references:={ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef_v46}, expectedOutput:=<![CDATA[(42, 42)]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("C.VB$StateMachine_2_Test(Of SM$T).MoveNext()", <![CDATA[ { // Code size 210 (0xd2) .maxstack 3 .locals init (String V_0, Integer V_1, System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2, System.Runtime.CompilerServices.YieldAwaitable V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer" IL_0006: stloc.1 .try { IL_0007: ldloc.1 IL_0008: brfalse.s IL_0058 IL_000a: ldarg.0 IL_000b: ldarg.0 IL_000c: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$VB$Local_a As SM$T" IL_0011: ldarg.0 IL_0012: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$VB$Local_a As SM$T" IL_0017: newobj "Sub System.ValueTuple(Of SM$T, SM$T)..ctor(SM$T, SM$T)" IL_001c: stfld "C.VB$StateMachine_2_Test(Of SM$T).$VB$ResumableLocal_x$0 As (f1 As SM$T, f2 As SM$T)" IL_0021: call "Function System.Threading.Tasks.Task.Yield() As System.Runtime.CompilerServices.YieldAwaitable" IL_0026: stloc.3 IL_0027: ldloca.s V_3 IL_0029: call "Function System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter() As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_002e: stloc.2 IL_002f: ldloca.s V_2 IL_0031: call "Function System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.get_IsCompleted() As Boolean" IL_0036: brtrue.s IL_0074 IL_0038: ldarg.0 IL_0039: ldc.i4.0 IL_003a: dup IL_003b: stloc.1 IL_003c: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer" IL_0041: ldarg.0 IL_0042: ldloc.2 IL_0043: stfld "C.VB$StateMachine_2_Test(Of SM$T).$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0048: ldarg.0 IL_0049: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)" IL_004e: ldloca.s V_2 IL_0050: ldarg.0 IL_0051: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.VB$StateMachine_2_Test(Of SM$T))(ByRef System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ByRef C.VB$StateMachine_2_Test(Of SM$T))" IL_0056: leave.s IL_00d1 IL_0058: ldarg.0 IL_0059: ldc.i4.m1 IL_005a: dup IL_005b: stloc.1 IL_005c: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer" IL_0061: ldarg.0 IL_0062: ldfld "C.VB$StateMachine_2_Test(Of SM$T).$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0067: stloc.2 IL_0068: ldarg.0 IL_0069: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_006e: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0074: ldloca.s V_2 IL_0076: call "Sub System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()" IL_007b: ldloca.s V_2 IL_007d: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0083: ldarg.0 IL_0084: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$VB$ResumableLocal_x$0 As (f1 As SM$T, f2 As SM$T)" IL_0089: constrained. "System.ValueTuple(Of SM$T, SM$T)" IL_008f: callvirt "Function Object.ToString() As String" IL_0094: stloc.0 IL_0095: leave.s IL_00bb } catch System.Exception { IL_0097: dup IL_0098: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)" IL_009d: stloc.s V_4 IL_009f: ldarg.0 IL_00a0: ldc.i4.s -2 IL_00a2: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer" IL_00a7: ldarg.0 IL_00a8: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)" IL_00ad: ldloc.s V_4 IL_00af: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).SetException(System.Exception)" IL_00b4: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_00b9: leave.s IL_00d1 } IL_00bb: ldarg.0 IL_00bc: ldc.i4.s -2 IL_00be: dup IL_00bf: stloc.1 IL_00c0: stfld "C.VB$StateMachine_2_Test(Of SM$T).$State As Integer" IL_00c5: ldarg.0 IL_00c6: ldflda "C.VB$StateMachine_2_Test(Of SM$T).$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)" IL_00cb: ldloc.0 IL_00cc: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).SetResult(String)" IL_00d1: ret } ]]>) End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/pull/13209")> Public Sub TupleAsyncCapture03() ' this test crashes in TypeSubstitution Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Threading.Tasks Class C Shared Sub Main() Console.Write(Test(42).Result) End Sub Shared Async Function Test(Of T)(a As T) As Task(Of String) Dim x = (f1:=a, f2:=a) Await Task.Yield() Return x.Test(a) End Function End Class Namespace System Public Structure ValueTuple(Of T1, T2) Public Item1 As T1 Public Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}" End Function Public Function Test(Of U)(val As U) As U Return val End Function End Structure End Namespace </file> </compilation>, references:={MscorlibRef_v46}, expectedOutput:=<![CDATA[42]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("C.VB$StateMachine_2_Test(Of SM$T).MoveNext()", <![CDATA[ ]]>) End Sub <Fact> Public Sub LongTupleWithSubstitution() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Threading.Tasks Class C Shared Sub Main() Console.Write(Test(42).Result) End Sub Shared Async Function Test(Of T)(a As T) As Task(Of T) Dim x = (f1:=1, f2:=2, f3:=3, f4:=4, f5:=5, f6:=6, f7:=7, f8:=a) Await Task.Yield() Return x.f8 End Function End Class </file> </compilation>, references:={ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef_v46}, expectedOutput:=<![CDATA[42]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleUsageWithoutTupleLibrary() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x As (Integer, String) = (1, "hello") End Sub End Module ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported. Dim x As (Integer, String) = (1, "hello") ~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported. Dim x As (Integer, String) = (1, "hello") ~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleUsageWithMissingTupleMembers() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x As (Integer, String) = (1, 2) End Sub End Module Namespace System Public Structure ValueTuple(Of T1, T2) End Structure End Namespace ]]></file> </compilation>) comp.AssertTheseEmitDiagnostics( <errors> BC35000: Requested operation is not available because the runtime library function 'ValueTuple..ctor' is not defined. Dim x As (Integer, String) = (1, 2) ~~~~~~ </errors>) End Sub <Fact> Public Sub TupleWithDuplicateNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x As (a As Integer, a As String) = (b:=1, b:="hello", b:=2) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37262: Tuple element names must be unique. Dim x As (a As Integer, a As String) = (b:=1, b:="hello", b:=2) ~ BC37262: Tuple element names must be unique. Dim x As (a As Integer, a As String) = (b:=1, b:="hello", b:=2) ~ BC37262: Tuple element names must be unique. Dim x As (a As Integer, a As String) = (b:=1, b:="hello", b:=2) ~ </errors>) End Sub <Fact> Public Sub TupleWithDuplicateReservedNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x As (Item1 As Integer, Item1 As String) = (Item1:=1, Item1:="hello") Dim y As (Item2 As Integer, Item2 As String) = (Item2:=1, Item2:="hello") End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37261: Tuple element name 'Item1' is only allowed at position 1. Dim x As (Item1 As Integer, Item1 As String) = (Item1:=1, Item1:="hello") ~~~~~ BC37261: Tuple element name 'Item1' is only allowed at position 1. Dim x As (Item1 As Integer, Item1 As String) = (Item1:=1, Item1:="hello") ~~~~~ BC37261: Tuple element name 'Item2' is only allowed at position 2. Dim y As (Item2 As Integer, Item2 As String) = (Item2:=1, Item2:="hello") ~~~~~ BC37261: Tuple element name 'Item2' is only allowed at position 2. Dim y As (Item2 As Integer, Item2 As String) = (Item2:=1, Item2:="hello") ~~~~~ </errors>) End Sub <Fact> Public Sub TupleWithNonReservedNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x As (Item1 As Integer, Item01 As Integer, Item10 As Integer) = (Item01:=1, Item1:=2, Item10:=3) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37261: Tuple element name 'Item10' is only allowed at position 10. Dim x As (Item1 As Integer, Item01 As Integer, Item10 As Integer) = (Item01:=1, Item1:=2, Item10:=3) ~~~~~~ BC37261: Tuple element name 'Item1' is only allowed at position 1. Dim x As (Item1 As Integer, Item01 As Integer, Item10 As Integer) = (Item01:=1, Item1:=2, Item10:=3) ~~~~~ BC37261: Tuple element name 'Item10' is only allowed at position 10. Dim x As (Item1 As Integer, Item01 As Integer, Item10 As Integer) = (Item01:=1, Item1:=2, Item10:=3) ~~~~~~ </errors>) End Sub <Fact> Public Sub DefaultValueForTuple() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x As (a As Integer, b As String) = (1, "hello") x = Nothing System.Console.WriteLine(x.a) System.Console.WriteLine(If(x.b, "null")) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[0 null]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleWithDuplicateMemberNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x As (a As Integer, a As String) = (b:=1, c:="hello", b:=2) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37262: Tuple element names must be unique. Dim x As (a As Integer, a As String) = (b:=1, c:="hello", b:=2) ~ BC37262: Tuple element names must be unique. Dim x As (a As Integer, a As String) = (b:=1, c:="hello", b:=2) ~ </errors>) End Sub <Fact> Public Sub TupleWithReservedMemberNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x As (Item1 As Integer, Item3 As String, Item2 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Rest As Integer) = (Item2:="bad", Item4:="bad", Item3:=3, Item4:=4, Item5:=5, Item6:=6, Item7:=7, Rest:="bad") End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37261: Tuple element name 'Item3' is only allowed at position 3. Dim x As (Item1 As Integer, Item3 As String, Item2 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Rest As Integer) = ~~~~~ BC37261: Tuple element name 'Item2' is only allowed at position 2. Dim x As (Item1 As Integer, Item3 As String, Item2 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Rest As Integer) = ~~~~~ BC37260: Tuple element name 'Rest' is disallowed at any position. Dim x As (Item1 As Integer, Item3 As String, Item2 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Rest As Integer) = ~~~~ BC37261: Tuple element name 'Item2' is only allowed at position 2. (Item2:="bad", Item4:="bad", Item3:=3, Item4:=4, Item5:=5, Item6:=6, Item7:=7, Rest:="bad") ~~~~~ BC37261: Tuple element name 'Item4' is only allowed at position 4. (Item2:="bad", Item4:="bad", Item3:=3, Item4:=4, Item5:=5, Item6:=6, Item7:=7, Rest:="bad") ~~~~~ BC37260: Tuple element name 'Rest' is disallowed at any position. (Item2:="bad", Item4:="bad", Item3:=3, Item4:=4, Item5:=5, Item6:=6, Item7:=7, Rest:="bad") ~~~~ </errors>) End Sub <Fact> Public Sub TupleWithExistingUnderlyingMemberNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim x = (CompareTo:=2, Create:=3, Deconstruct:=4, Equals:=5, GetHashCode:=6, Rest:=8, ToString:=10) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37260: Tuple element name 'CompareTo' is disallowed at any position. Dim x = (CompareTo:=2, Create:=3, Deconstruct:=4, Equals:=5, GetHashCode:=6, Rest:=8, ToString:=10) ~~~~~~~~~ BC37260: Tuple element name 'Deconstruct' is disallowed at any position. Dim x = (CompareTo:=2, Create:=3, Deconstruct:=4, Equals:=5, GetHashCode:=6, Rest:=8, ToString:=10) ~~~~~~~~~~~ BC37260: Tuple element name 'Equals' is disallowed at any position. Dim x = (CompareTo:=2, Create:=3, Deconstruct:=4, Equals:=5, GetHashCode:=6, Rest:=8, ToString:=10) ~~~~~~ BC37260: Tuple element name 'GetHashCode' is disallowed at any position. Dim x = (CompareTo:=2, Create:=3, Deconstruct:=4, Equals:=5, GetHashCode:=6, Rest:=8, ToString:=10) ~~~~~~~~~~~ BC37260: Tuple element name 'Rest' is disallowed at any position. Dim x = (CompareTo:=2, Create:=3, Deconstruct:=4, Equals:=5, GetHashCode:=6, Rest:=8, ToString:=10) ~~~~ BC37260: Tuple element name 'ToString' is disallowed at any position. Dim x = (CompareTo:=2, Create:=3, Deconstruct:=4, Equals:=5, GetHashCode:=6, Rest:=8, ToString:=10) ~~~~~~~~ </errors>) End Sub <Fact> Public Sub LongTupleDeclaration() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, String, Integer, Integer, Integer, Integer) = (1, 2, 3, 4, 5, 6, 7, "Alice", 2, 3, 4, 5) System.Console.Write($"{x.Item1} {x.Item2} {x.Item3} {x.Item4} {x.Item5} {x.Item6} {x.Item7} {x.Item8} {x.Item9} {x.Item10} {x.Item11} {x.Item12}") End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1 2 3 4 5 6 7 Alice 2 3 4 5]]>, sourceSymbolValidator:= Sub(m As ModuleSymbol) Dim compilation = m.DeclaringCompilation Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().Single().Names(0) Assert.Equal("x As (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, " _ + "System.String, System.Int32, System.Int32, System.Int32, System.Int32)", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub LongTupleDeclarationWithNames() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x As (a As Integer, b As Integer, c As Integer, d As Integer, e As Integer, f As Integer, g As Integer, _ h As String, i As Integer, j As Integer, k As Integer, l As Integer) = (1, 2, 3, 4, 5, 6, 7, "Alice", 2, 3, 4, 5) System.Console.Write($"{x.a} {x.b} {x.c} {x.d} {x.e} {x.f} {x.g} {x.h} {x.i} {x.j} {x.k} {x.l}") End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1 2 3 4 5 6 7 Alice 2 3 4 5]]>, sourceSymbolValidator:=Sub(m As ModuleSymbol) Dim compilation = m.DeclaringCompilation Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().Single().Names(0) Assert.Equal("x As (a As System.Int32, b As System.Int32, c As System.Int32, d As System.Int32, " _ + "e As System.Int32, f As System.Int32, g As System.Int32, h As System.String, " _ + "i As System.Int32, j As System.Int32, k As System.Int32, l As System.Int32)", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub) verifier.VerifyDiagnostics() End Sub <ConditionalFact(GetType(NoIOperationValidation))> Public Sub HugeTupleCreationParses() Dim b = New StringBuilder() b.Append("(") For i As Integer = 0 To 2000 b.Append("1, ") Next b.Append("1)") Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x = <%= b.ToString() %> End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertNoDiagnostics() End Sub <ConditionalFact(GetType(NoIOperationValidation))> Public Sub HugeTupleDeclarationParses() Dim b = New StringBuilder() b.Append("(") For i As Integer = 0 To 3000 b.Append("Integer, ") Next b.Append("Integer)") Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x As <%= b.ToString() %>; End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) End Sub <Fact> <WorkItem(13302, "https://github.com/dotnet/roslyn/issues/13302")> Public Sub GenericTupleWithoutTupleLibrary_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub Main() Dim x = M(Of Integer, Boolean)() System.Console.Write($"{x.first} {x.second}") End Sub Public Shared Function M(Of T1, T2)() As (first As T1, second As T2) return (Nothing, Nothing) End Function End Class ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported. Public Shared Function M(Of T1, T2)() As (first As T1, second As T2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Function M(Of T1, T2)() As (first As T1, second As T2) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported. return (Nothing, Nothing) ~~~~~~~~~~~~~~~~~~ </errors>) Dim mTuple = DirectCast(comp.GetMember(Of MethodSymbol)("C.M").ReturnType, NamedTypeSymbol) Assert.True(mTuple.IsTupleType) Assert.Equal(TypeKind.Error, mTuple.TupleUnderlyingType.TypeKind) Assert.Equal(SymbolKind.ErrorType, mTuple.TupleUnderlyingType.Kind) Assert.IsAssignableFrom(Of ErrorTypeSymbol)(mTuple.TupleUnderlyingType) Assert.Equal(TypeKind.Struct, mTuple.TypeKind) 'AssertTupleTypeEquality(mTuple) Assert.False(mTuple.IsImplicitlyDeclared) 'Assert.Equal("Predefined type 'System.ValueTuple`2' is not defined or imported", mTuple.GetUseSiteDiagnostic().GetMessage(CultureInfo.InvariantCulture)) Assert.Null(mTuple.BaseType) Assert.False(DirectCast(mTuple, TupleTypeSymbol).UnderlyingDefinitionToMemberMap.Any()) Dim mFirst = DirectCast(mTuple.GetMembers("first").Single(), FieldSymbol) Assert.IsType(Of TupleErrorFieldSymbol)(mFirst) Assert.True(mFirst.IsTupleField) Assert.Equal("first", mFirst.Name) Assert.Same(mFirst, mFirst.OriginalDefinition) Assert.True(mFirst.Equals(mFirst)) Assert.Null(mFirst.TupleUnderlyingField) Assert.Null(mFirst.AssociatedSymbol) Assert.Same(mTuple, mFirst.ContainingSymbol) Assert.True(mFirst.CustomModifiers.IsEmpty) Assert.True(mFirst.GetAttributes().IsEmpty) 'Assert.Null(mFirst.GetUseSiteDiagnostic()) Assert.False(mFirst.Locations.IsEmpty) Assert.Equal("first As T1", mFirst.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.False(mFirst.IsImplicitlyDeclared) Assert.Null(mFirst.TypeLayoutOffset) Assert.True(DirectCast(mFirst, IFieldSymbol).IsExplicitlyNamedTupleElement) Dim mItem1 = DirectCast(mTuple.GetMembers("Item1").Single(), FieldSymbol) Assert.IsType(Of TupleErrorFieldSymbol)(mItem1) Assert.True(mItem1.IsTupleField) Assert.Equal("Item1", mItem1.Name) Assert.Same(mItem1, mItem1.OriginalDefinition) Assert.True(mItem1.Equals(mItem1)) Assert.Null(mItem1.TupleUnderlyingField) Assert.Null(mItem1.AssociatedSymbol) Assert.Same(mTuple, mItem1.ContainingSymbol) Assert.True(mItem1.CustomModifiers.IsEmpty) Assert.True(mItem1.GetAttributes().IsEmpty) 'Assert.Null(mItem1.GetUseSiteDiagnostic()) Assert.True(mItem1.Locations.IsEmpty) Assert.True(mItem1.IsImplicitlyDeclared) Assert.Null(mItem1.TypeLayoutOffset) Assert.False(DirectCast(mItem1, IFieldSymbol).IsExplicitlyNamedTupleElement) End Sub <Fact> <WorkItem(13300, "https://github.com/dotnet/roslyn/issues/13300")> Public Sub GenericTupleWithoutTupleLibrary_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class C Function M(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)() As (T1, T2, T3, T4, T5, T6, T7, T8, T9) Throw New System.NotSupportedException() End Function End Class Namespace System Public Structure ValueTuple(Of T1, T2) End Structure End Namespace ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC37267: Predefined type 'ValueTuple(Of ,,,,,,,)' is not defined or imported. Function M(Of T1, T2, T3, T4, T5, T6, T7, T8, T9)() As (T1, T2, T3, T4, T5, T6, T7, T8, T9) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub GenericTuple() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x = M(Of Integer, Boolean)() System.Console.Write($"{x.first} {x.second}") End Sub Shared Function M(Of T1, T2)() As (first As T1, second As T2) Return (Nothing, Nothing) End Function End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[0 False]]>) End Sub <Fact> Public Sub LongTupleCreation() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x = (1, 2, 3, 4, 5, 6, 7, "Alice", 2, 3, 4, 5, 6, 7, "Bob", 2, 3) System.Console.Write($"{x.Item1} {x.Item2} {x.Item3} {x.Item4} {x.Item5} {x.Item6} {x.Item7} {x.Item8} " _ + $"{x.Item9} {x.Item10} {x.Item11} {x.Item12} {x.Item13} {x.Item14} {x.Item15} {x.Item16} {x.Item17}") End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1 2 3 4 5 6 7 Alice 2 3 4 5 6 7 Bob 2 3]]>, sourceSymbolValidator:= Sub(m As ModuleSymbol) Dim compilation = m.DeclaringCompilation Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim x = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, " _ + "System.String, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, " _ + "System.String, System.Int32, System.Int32)", model.GetTypeInfo(x).Type.ToTestDisplayString()) End Sub) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleInLambda() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim f As System.Action(Of (Integer, String)) = Sub(x As (Integer, String)) System.Console.Write($"{x.Item1} {x.Item2}") f((42, "Alice")) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42 Alice]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleWithNamesInLambda() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim f As System.Action(Of (Integer, String)) = Sub(x As (a As Integer, b As String)) System.Console.Write($"{x.Item1} {x.Item2}") f((c:=42, d:="Alice")) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42 Alice]]>) End Sub <Fact> Public Sub TupleInProperty() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Property P As (a As Integer, b As String) Shared Sub Main() P = (42, "Alice") System.Console.Write($"{P.a} {P.b}") End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42 Alice]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub ExtensionMethodOnTuple() Dim comp = CompileAndVerify( <compilation> <file name="a.vb"> Module M &lt;System.Runtime.CompilerServices.Extension()&gt; Sub Extension(x As (a As Integer, b As String)) System.Console.Write($"{x.a} {x.b}") End Sub End Module Class C Shared Sub Main() Call (42, "Alice").Extension() End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:="42 Alice") End Sub <Fact> Public Sub TupleInOptionalParam() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Sub M(x As Integer, Optional y As (a As Integer, b As String) = (42, "Alice")) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics(<![CDATA[ BC30059: Constant expression is required. Sub M(x As Integer, Optional y As (a As Integer, b As String) = (42, "Alice")) ~~~~~~~~~~~~~ ]]>) End Sub <Fact> Public Sub TupleDefaultInOptionalParam() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() M() End Sub Shared Sub M(Optional x As (a As Integer, b As String) = Nothing) System.Console.Write($"{x.a} {x.b}") End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[0 ]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleAsNamedParam() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() M(y:=(42, "Alice"), x:=1) End Sub Shared Sub M(x As Integer, y As (a As Integer, b As String)) System.Console.Write($"{y.a} {y.Item2}") End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[42 Alice]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub LongTupleCreationWithNames() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x = (a:=1, b:=2, c:=3, d:=4, e:=5, f:=6, g:=7, h:="Alice", i:=2, j:=3, k:=4, l:=5, m:=6, n:=7, o:="Bob", p:=2, q:=3) System.Console.Write($"{x.a} {x.b} {x.c} {x.d} {x.e} {x.f} {x.g} {x.h} {x.i} {x.j} {x.k} {x.l} {x.m} {x.n} {x.o} {x.p} {x.q}") End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1 2 3 4 5 6 7 Alice 2 3 4 5 6 7 Bob 2 3]]>, sourceSymbolValidator:= Sub(m As ModuleSymbol) Dim compilation = m.DeclaringCompilation Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim x = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(a As System.Int32, b As System.Int32, c As System.Int32, d As System.Int32, e As System.Int32, f As System.Int32, g As System.Int32, " _ + "h As System.String, i As System.Int32, j As System.Int32, k As System.Int32, l As System.Int32, m As System.Int32, n As System.Int32, " _ + "o As System.String, p As System.Int32, q As System.Int32)", model.GetTypeInfo(x).Type.ToTestDisplayString()) End Sub) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleCreationWithInferredNamesWithVB15() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Dim e As Integer = 5 Dim f As Integer = 6 Dim instance As C = Nothing Sub M() Dim a As Integer = 1 Dim b As Integer = 3 Dim Item4 As Integer = 4 Dim g As Integer = 7 Dim Rest As Integer = 9 Dim y As (x As Integer, Integer, b As Integer, Integer, Integer, Integer, f As Integer, Integer, Integer, Integer) = (a, (a), b:=2, b, Item4, instance.e, Me.f, g, g, Rest) Dim z = (x:=b, b) System.Console.Write(y) System.Console.Write(z) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15), sourceSymbolValidator:= Sub(m As ModuleSymbol) Dim compilation = m.DeclaringCompilation Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim yTuple = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(0) Assert.Equal("(a As System.Int32, System.Int32, b As System.Int32, System.Int32, System.Int32, e As System.Int32, f As System.Int32, System.Int32, System.Int32, System.Int32)", model.GetTypeInfo(yTuple).Type.ToTestDisplayString()) Dim zTuple = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(1) Assert.Equal("(x As System.Int32, b As System.Int32)", model.GetTypeInfo(zTuple).Type.ToTestDisplayString()) End Sub) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleCreationWithInferredNames() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Dim e As Integer = 5 Dim f As Integer = 6 Dim instance As C = Nothing Sub M() Dim a As Integer = 1 Dim b As Integer = 3 Dim Item4 As Integer = 4 Dim g As Integer = 7 Dim Rest As Integer = 9 Dim y As (x As Integer, Integer, b As Integer, Integer, Integer, Integer, f As Integer, Integer, Integer, Integer) = (a, (a), b:=2, b, Item4, instance.e, Me.f, g, g, Rest) Dim z = (x:=b, b) System.Console.Write(y) System.Console.Write(z) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3), sourceSymbolValidator:= Sub(m As ModuleSymbol) Dim compilation = m.DeclaringCompilation Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim yTuple = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(0) Assert.Equal("(a As System.Int32, System.Int32, b As System.Int32, System.Int32, System.Int32, e As System.Int32, f As System.Int32, System.Int32, System.Int32, System.Int32)", model.GetTypeInfo(yTuple).Type.ToTestDisplayString()) Dim zTuple = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(1) Assert.Equal("(x As System.Int32, b As System.Int32)", model.GetTypeInfo(zTuple).Type.ToTestDisplayString()) End Sub) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleCreationWithInferredNames2() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Dim e As Integer = 5 Dim instance As C = Nothing Function M() As Integer Dim y As (Integer?, object) = (instance?.e, (e, instance.M())) System.Console.Write(y) Return 42 End Function End Class </file> </compilation>, references:=s_valueTupleRefs, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3), sourceSymbolValidator:= Sub(m As ModuleSymbol) Dim compilation = m.DeclaringCompilation Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim yTuple = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(0) Assert.Equal("(e As System.Nullable(Of System.Int32), (e As System.Int32, M As System.Int32))", model.GetTypeInfo(yTuple).Type.ToTestDisplayString()) End Sub) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub MissingMemberAccessWithVB15() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Sub M() Dim a As Integer = 1 Dim t = (a, 2) System.Console.Write(t.A) System.Console.Write(GetTuple().a) End Sub Function GetTuple() As (Integer, Integer) Return (1, 2) End Function End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15)) comp.AssertTheseDiagnostics(<errors> BC37289: Tuple element name 'a' is inferred. Please use language version 15.3 or greater to access an element by its inferred name. System.Console.Write(t.A) ~~~ BC30456: 'a' is not a member of '(Integer, Integer)'. System.Console.Write(GetTuple().a) ~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub UseSiteDiagnosticOnTupleField() Dim missingComp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="UseSiteDiagnosticOnTupleField_missingComp"> <file name="missing.vb"> Public Class Missing End Class </file> </compilation>) missingComp.VerifyDiagnostics() Dim libComp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="lib.vb"> Public Class C Public Shared Function GetTuple() As (Missing, Integer) Throw New System.Exception() End Function End Class </file> </compilation>, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef, missingComp.ToMetadataReference()}) libComp.VerifyDiagnostics() Dim source = <compilation> <file name="a.vb"> Class D Sub M() System.Console.Write(C.GetTuple().Item1) End Sub End Class </file> </compilation> Dim comp15 = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef, libComp.ToMetadataReference()}, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15)) comp15.AssertTheseDiagnostics(<errors> BC30652: Reference required to assembly 'UseSiteDiagnosticOnTupleField_missingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'Missing'. Add one to your project. System.Console.Write(C.GetTuple().Item1) ~~~~~~~~~~~~ </errors>) Dim comp15_3 = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef, libComp.ToMetadataReference()}, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3)) comp15_3.AssertTheseDiagnostics(<errors> BC30652: Reference required to assembly 'UseSiteDiagnosticOnTupleField_missingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'Missing'. Add one to your project. System.Console.Write(C.GetTuple().Item1) ~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub UseSiteDiagnosticOnTupleField2() Dim source = <compilation> <file name="a.vb"> Class C Sub M() Dim a = 1 Dim t = (a, 2) System.Console.Write(t.a) End Sub End Class Namespace System Public Structure ValueTuple(Of T1, T2) Public Sub New(item1 As T1, item2 As T2) End Sub End Structure End Namespace </file> </compilation> Dim comp15 = CreateCompilationWithMscorlib40AndVBRuntime(source, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15)) comp15.AssertTheseDiagnostics(<errors> BC35000: Requested operation is not available because the runtime library function 'ValueTuple.Item1' is not defined. System.Console.Write(t.a) ~~~ </errors>) Dim comp15_3 = CreateCompilationWithMscorlib40AndVBRuntime(source, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3)) comp15_3.AssertTheseDiagnostics(<errors> BC35000: Requested operation is not available because the runtime library function 'ValueTuple.Item1' is not defined. System.Console.Write(t.a) ~~~ </errors>) End Sub <Fact> Public Sub MissingMemberAccessWithExtensionWithVB15() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime( <compilation> <file name="a.vb"> Imports System Class C Sub M() Dim a As Integer = 1 Dim t = (a, 2) System.Console.Write(t.A) System.Console.Write(GetTuple().a) End Sub Function GetTuple() As (Integer, Integer) Return (1, 2) End Function End Class Module Extensions &lt;System.Runtime.CompilerServices.Extension()&gt; Public Function A(self As (Integer, Action)) As String Return Nothing End Function End Module </file> </compilation>, references:={ValueTupleRef, Net451.SystemRuntime, Net451.SystemCore}, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15)) comp.AssertTheseDiagnostics(<errors> BC37289: Tuple element name 'a' is inferred. Please use language version 15.3 or greater to access an element by its inferred name. System.Console.Write(t.A) ~~~ BC30456: 'a' is not a member of '(Integer, Integer)'. System.Console.Write(GetTuple().a) ~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub MissingMemberAccessWithVB15_3() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Sub M() Dim a As Integer = 1 Dim t = (a, 2) System.Console.Write(t.b) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3)) comp.AssertTheseDiagnostics(<errors> BC30456: 'b' is not a member of '(a As Integer, Integer)'. System.Console.Write(t.b) ~~~ </errors>) End Sub <Fact> Public Sub InferredNamesInLinq() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Collections.Generic Imports System.Linq Class C Dim f1 As Integer = 0 Dim f2 As Integer = 1 Shared Sub Main(list As IEnumerable(Of C)) Dim result = list.Select(Function(c) (c.f1, c.f2)).Where(Function(t) t.f2 = 1) ' t and result have names f1 and f2 System.Console.Write(result.Count()) End Sub End Class </file> </compilation>, references:={ValueTupleRef, SystemRuntimeFacadeRef, LinqAssemblyRef}, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3), sourceSymbolValidator:= Sub(m As ModuleSymbol) Dim compilation = m.DeclaringCompilation Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Dim result = tree.GetRoot().DescendantNodes().OfType(Of VariableDeclaratorSyntax)().ElementAt(2).Names(0) Dim resultSymbol = model.GetDeclaredSymbol(result) Assert.Equal("result As System.Collections.Generic.IEnumerable(Of (f1 As System.Int32, f2 As System.Int32))", resultSymbol.ToTestDisplayString()) End Sub) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub InferredNamesInTernary() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim i = 1 Dim flag = False Dim t = If(flag, (i, 2), (i, 3)) System.Console.Write(t.i) End Sub End Class </file> </compilation>, references:={ValueTupleRef, SystemRuntimeFacadeRef, LinqAssemblyRef}, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3), expectedOutput:="1") verifier.VerifyDiagnostics() End Sub <Fact> Public Sub InferredNames_ExtensionNowFailsInVB15ButNotVB15_3() Dim source = <compilation> <file name="a.vb"> Imports System Class C Shared Sub Main() Dim M As Action = Sub() Console.Write("lambda") Dim t = (1, M) t.M() End Sub End Class Module Extensions &lt;System.Runtime.CompilerServices.Extension()&gt; Public Sub M(self As (Integer, Action)) Console.Write("extension") End Sub End Module </file> </compilation> ' When VB 15 shipped, no tuple element would be found/inferred, so the extension method was called. ' The VB 15.3 compiler disallows that, even when LanguageVersion is 15. Dim comp15 = CreateCompilationWithMscorlib45AndVBRuntime(source, references:={ValueTupleRef, Net451.SystemRuntime, Net451.SystemCore}, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15)) comp15.AssertTheseDiagnostics(<errors> BC37289: Tuple element name 'M' is inferred. Please use language version 15.3 or greater to access an element by its inferred name. t.M() ~~~ </errors>) Dim verifier15_3 = CompileAndVerify(source, allReferences:={ValueTupleRef, Net451.mscorlib, Net451.SystemCore, Net451.SystemRuntime, Net451.MicrosoftVisualBasic}, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_3), expectedOutput:="lambda") verifier15_3.VerifyDiagnostics() End Sub <Fact> Public Sub InferredName_Conversion() Dim source = <compilation> <file> Class C Shared Sub F(t As (Object, Object)) End Sub Shared Sub G(o As Object) Dim t = (1, o) F(t) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={ValueTupleRef, SystemRuntimeFacadeRef, SystemCoreRef}, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic15)) comp.AssertTheseEmitDiagnostics(<errors/>) End Sub <Fact> Public Sub LongTupleWithArgumentEvaluation() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x = (a:=PrintAndReturn(1), b:=2, c:=3, d:=PrintAndReturn(4), e:=5, f:=6, g:=PrintAndReturn(7), h:=PrintAndReturn("Alice"), i:=2, j:=3, k:=4, l:=5, m:=6, n:=PrintAndReturn(7), o:=PrintAndReturn("Bob"), p:=2, q:=PrintAndReturn(3)) End Sub Shared Function PrintAndReturn(Of T)(i As T) System.Console.Write($"{i} ") Return i End Function End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1 4 7 Alice 7 Bob 3]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DuplicateTupleMethodsNotAllowed() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C Function M(a As (String, String)) As (Integer, Integer) Return new System.ValueTuple(Of Integer, Integer)(a.Item1.Length, a.Item2.Length) End Function Function M(a As System.ValueTuple(Of String, String)) As System.ValueTuple(Of Integer, Integer) Return (a.Item1.Length, a.Item2.Length) End Function End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30269: 'Public Function M(a As (String, String)) As (Integer, Integer)' has multiple definitions with identical signatures. Function M(a As (String, String)) As (Integer, Integer) ~ </errors>) End Sub <Fact> Public Sub TupleArrays() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Interface I Function M(a As (Integer, Integer)()) As System.ValueTuple(Of Integer, Integer)() End Interface Class C Implements I Shared Sub Main() Dim i As I = new C() Dim r = i.M(new System.ValueTuple(Of Integer, Integer)() { new System.ValueTuple(Of Integer, Integer)(1, 2) }) System.Console.Write($"{r(0).Item1} {r(0).Item2}") End Sub Public Function M(a As (Integer, Integer)()) As System.ValueTuple(Of Integer, Integer)() Implements I.M Return New System.ValueTuple(Of Integer, Integer)() { (a(0).Item1, a(0).Item2) } End Function End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1 2]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleRef() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim r = (1, 2) M(r) System.Console.Write($"{r.Item1} {r.Item2}") End Sub Shared Sub M(ByRef a As (Integer, Integer)) System.Console.WriteLine($"{a.Item1} {a.Item2}") a = (3, 4) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1 2 3 4]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleOut() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim r As (Integer, Integer) M(r) System.Console.Write($"{r.Item1} {r.Item2}") End Sub Shared Sub M(ByRef a As (Integer, Integer)) System.Console.WriteLine($"{a.Item1} {a.Item2}") a = (1, 2) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[0 0 1 2]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleTypeArgs() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim a = (1, "Alice") Dim r = M(Of Integer, String)(a) System.Console.Write($"{r.Item1} {r.Item2}") End Sub Shared Function M(Of T1, T2)(a As (T1, T2)) As (T1, T2) Return a End Function End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[1 Alice]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub NullableTuple() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() M((1, "Alice")) End Sub Shared Sub M(a As (Integer, String)?) System.Console.Write($"{a.HasValue} {a.Value.Item1} {a.Value.Item2}") End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[True 1 Alice]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleUnsupportedInUsingStatement() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports VT2 = (Integer, Integer) ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC30203: Identifier expected. Imports VT2 = (Integer, Integer) ~ BC40056: Namespace or type specified in the Imports '' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. Imports VT2 = (Integer, Integer) ~~~~~~~~~~~~~~~~~~ BC32093: 'Of' required when specifying type arguments for a generic type or method. Imports VT2 = (Integer, Integer) ~ </errors>) End Sub <Fact> Public Sub MissingTypeInAlias() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports VT2 = System.ValueTuple(Of Integer, Integer) ' ValueTuple is referenced but does not exist Namespace System Public Class Bogus End Class End Namespace Namespace TuplesCrash2 Class C Shared Sub Main() End Sub End Class End Namespace ]]></file> </compilation>) Dim tree = comp.SyntaxTrees.First() Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = model.LookupStaticMembers(234) For i As Integer = 0 To tree.GetText().Length model.LookupStaticMembers(i) Next ' Didn't crash End Sub <Fact> Public Sub MultipleDefinitionsOfValueTuple() Dim source1 = <compilation> <file name="a.vb"> Public Module M1 &lt;System.Runtime.CompilerServices.Extension()&gt; Public Sub Extension(x As Integer, y As (Integer, Integer)) System.Console.Write("M1.Extension") End Sub End Module <%= s_trivial2uple %></file> </compilation> Dim source2 = <compilation> <file name="a.vb"> Public Module M2 &lt;System.Runtime.CompilerServices.Extension()&gt; Public Sub Extension(x As Integer, y As (Integer, Integer)) System.Console.Write("M2.Extension") End Sub End Module <%= s_trivial2uple %></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40AndVBRuntime(source1, additionalRefs:={MscorlibRef_v46}, assemblyName:="comp1") comp1.AssertNoDiagnostics() Dim comp2 = CreateCompilationWithMscorlib40AndVBRuntime(source2, additionalRefs:={MscorlibRef_v46}, assemblyName:="comp2") comp2.AssertNoDiagnostics() Dim source = <compilation> <file name="a.vb"> Imports System Imports M1 Imports M2 Class C Public Shared Sub Main() Dim x As Integer = 0 x.Extension((1, 1)) End Sub End Class </file> </compilation> Dim comp3 = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={comp1.ToMetadataReference(), comp2.ToMetadataReference()}) comp3.AssertTheseDiagnostics( <errors> BC30521: Overload resolution failed because no accessible 'Extension' is most specific for these arguments: Extension method 'Public Sub Extension(y As (Integer, Integer))' defined in 'M1': Not most specific. Extension method 'Public Sub Extension(y As (Integer, Integer))' defined in 'M2': Not most specific. x.Extension((1, 1)) ~~~~~~~~~ BC37305: Predefined type 'ValueTuple(Of ,)' is declared in multiple referenced assemblies: 'comp1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'comp2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' x.Extension((1, 1)) ~~~~~~ </errors>) Dim comp4 = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={comp1.ToMetadataReference()}, options:=TestOptions.DebugExe) comp4.AssertTheseDiagnostics( <errors> BC40056: Namespace or type specified in the Imports 'M2' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. Imports M2 ~~ </errors>) CompileAndVerify(comp4, expectedOutput:=<![CDATA[M1.Extension]]>) End Sub <Fact> Public Sub Tuple2To8Members() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Console Class C Shared Sub Main() Write((1, 2).Item1) Write((1, 2).Item2) WriteLine() Write((1, 2, 3).Item1) Write((1, 2, 3).Item2) Write((1, 2, 3).Item3) WriteLine() Write((1, 2, 3, 4).Item1) Write((1, 2, 3, 4).Item2) Write((1, 2, 3, 4).Item3) Write((1, 2, 3, 4).Item4) WriteLine() Write((1, 2, 3, 4, 5).Item1) Write((1, 2, 3, 4, 5).Item2) Write((1, 2, 3, 4, 5).Item3) Write((1, 2, 3, 4, 5).Item4) Write((1, 2, 3, 4, 5).Item5) WriteLine() Write((1, 2, 3, 4, 5, 6).Item1) Write((1, 2, 3, 4, 5, 6).Item2) Write((1, 2, 3, 4, 5, 6).Item3) Write((1, 2, 3, 4, 5, 6).Item4) Write((1, 2, 3, 4, 5, 6).Item5) Write((1, 2, 3, 4, 5, 6).Item6) WriteLine() Write((1, 2, 3, 4, 5, 6, 7).Item1) Write((1, 2, 3, 4, 5, 6, 7).Item2) Write((1, 2, 3, 4, 5, 6, 7).Item3) Write((1, 2, 3, 4, 5, 6, 7).Item4) Write((1, 2, 3, 4, 5, 6, 7).Item5) Write((1, 2, 3, 4, 5, 6, 7).Item6) Write((1, 2, 3, 4, 5, 6, 7).Item7) WriteLine() Write((1, 2, 3, 4, 5, 6, 7, 8).Item1) Write((1, 2, 3, 4, 5, 6, 7, 8).Item2) Write((1, 2, 3, 4, 5, 6, 7, 8).Item3) Write((1, 2, 3, 4, 5, 6, 7, 8).Item4) Write((1, 2, 3, 4, 5, 6, 7, 8).Item5) Write((1, 2, 3, 4, 5, 6, 7, 8).Item6) Write((1, 2, 3, 4, 5, 6, 7, 8).Item7) Write((1, 2, 3, 4, 5, 6, 7, 8).Item8) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[12 123 1234 12345 123456 1234567 12345678]]>) End Sub <Fact> Public Sub CreateTupleTypeSymbol_BadArguments() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Assert.Throws(Of ArgumentNullException)(Sub() comp.CreateTupleTypeSymbol(underlyingType:=Nothing, elementNames:=Nothing)) Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, intType) Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("Item1"))) Assert.Contains(CodeAnalysisResources.TupleElementNameCountMismatch, ex.Message) Dim tree = VisualBasicSyntaxTree.ParseText("Class C") Dim loc1 = Location.Create(tree, New TextSpan(0, 1)) ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(vt2, elementLocations:=ImmutableArray.Create(loc1))) Assert.Contains(CodeAnalysisResources.TupleElementLocationCountMismatch, ex.Message) End Sub <Fact> Public Sub CreateTupleTypeSymbol_WithValueTuple() Dim tupleComp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><%= s_trivial2uple %></file> </compilation>) Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef, tupleComp.ToMetadataReference()}) Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType) Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create(Of String)(Nothing, Nothing)) Assert.True(tupleWithoutNames.IsTupleType) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.TupleUnderlyingType.Kind) Assert.Equal("(System.Int32, System.String)", tupleWithoutNames.ToTestDisplayString()) Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault) Assert.Equal((New String() {"System.Int32", "System.String"}), ElementTypeNames(tupleWithoutNames)) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind) Assert.All(tupleWithoutNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()), Sub(Loc) Assert.Equal(Loc, Nothing)) End Sub Private Shared Function ElementTypeNames(tuple As INamedTypeSymbol) As IEnumerable(Of String) Return tuple.TupleElements.Select(Function(t) t.Type.ToTestDisplayString()) End Function <Fact> Public Sub CreateTupleTypeSymbol_Locations() Dim tupleComp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><%= s_trivial2uple %></file> </compilation>) Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef, tupleComp.ToMetadataReference()}) Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType) Dim tree = VisualBasicSyntaxTree.ParseText("Class C") Dim loc1 = Location.Create(tree, New TextSpan(0, 1)) Dim loc2 = Location.Create(tree, New TextSpan(1, 1)) Dim tuple = comp.CreateTupleTypeSymbol( vt2, ImmutableArray.Create("i1", "i2"), ImmutableArray.Create(loc1, loc2)) Assert.True(tuple.IsTupleType) Assert.Equal(SymbolKind.NamedType, tuple.TupleUnderlyingType.Kind) Assert.Equal("(i1 As System.Int32, i2 As System.String)", tuple.ToTestDisplayString()) Assert.Equal(New String() {"System.Int32", "System.String"}, ElementTypeNames(tuple)) Assert.Equal(SymbolKind.NamedType, tuple.Kind) Assert.Equal(loc1, tuple.GetMembers("i1").Single.Locations.Single()) Assert.Equal(loc2, tuple.GetMembers("i2").Single.Locations.Single()) End Sub <Fact> Public Sub CreateTupleTypeSymbol_NoNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType) Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(vt2, Nothing) Assert.True(tupleWithoutNames.IsTupleType) Assert.Equal(SymbolKind.ErrorType, tupleWithoutNames.TupleUnderlyingType.Kind) Assert.Equal("(System.Int32, System.String)", tupleWithoutNames.ToTestDisplayString()) Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault) Assert.Equal(New String() {"System.Int32", "System.String"}, ElementTypeNames(tupleWithoutNames)) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind) Assert.All(tupleWithoutNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()), Sub(Loc) Assert.Equal(Loc, Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_WithNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, stringType) Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("Alice", "Bob")) Assert.True(tupleWithoutNames.IsTupleType) Assert.Equal(SymbolKind.ErrorType, tupleWithoutNames.TupleUnderlyingType.Kind) Assert.Equal("(Alice As System.Int32, Bob As System.String)", tupleWithoutNames.ToTestDisplayString()) Assert.Equal(New String() {"Alice", "Bob"}, GetTupleElementNames(tupleWithoutNames)) Assert.Equal(New String() {"System.Int32", "System.String"}, ElementTypeNames(tupleWithoutNames)) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind) Assert.All(tupleWithoutNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()), Sub(Loc) Assert.Equal(Loc, Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_WithSomeNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim vt3 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T3).Construct(intType, stringType, intType) Dim tupleWithSomeNames = comp.CreateTupleTypeSymbol(vt3, ImmutableArray.Create(Nothing, "Item2", "Charlie")) Assert.True(tupleWithSomeNames.IsTupleType) Assert.Equal(SymbolKind.ErrorType, tupleWithSomeNames.TupleUnderlyingType.Kind) Assert.Equal("(System.Int32, Item2 As System.String, Charlie As System.Int32)", tupleWithSomeNames.ToTestDisplayString()) Assert.Equal(New String() {Nothing, "Item2", "Charlie"}, GetTupleElementNames(tupleWithSomeNames)) Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32"}, ElementTypeNames(tupleWithSomeNames)) Assert.Equal(SymbolKind.NamedType, tupleWithSomeNames.Kind) Assert.All(tupleWithSomeNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()), Sub(Loc) Assert.Equal(Loc, Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_WithBadNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, intType) Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("Item2", "Item1")) Assert.True(tupleWithoutNames.IsTupleType) Assert.Equal("(Item2 As System.Int32, Item1 As System.Int32)", tupleWithoutNames.ToTestDisplayString()) Assert.Equal(New String() {"Item2", "Item1"}, GetTupleElementNames(tupleWithoutNames)) Assert.Equal(New String() {"System.Int32", "System.Int32"}, ElementTypeNames(tupleWithoutNames)) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind) Assert.All(tupleWithoutNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()), Sub(Loc) Assert.Equal(Loc, Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_Tuple8NoNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim vt8 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest). Construct(intType, stringType, intType, stringType, intType, stringType, intType, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T1).Construct(stringType)) Dim tuple8WithoutNames = comp.CreateTupleTypeSymbol(vt8, Nothing) Assert.True(tuple8WithoutNames.IsTupleType) Assert.Equal("(System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, System.String)", tuple8WithoutNames.ToTestDisplayString()) Assert.True(GetTupleElementNames(tuple8WithoutNames).IsDefault) Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String"}, ElementTypeNames(tuple8WithoutNames)) Assert.All(tuple8WithoutNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()), Sub(Loc) Assert.Equal(Loc, Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_Tuple8WithNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim vt8 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest). Construct(intType, stringType, intType, stringType, intType, stringType, intType, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T1).Construct(stringType)) Dim tuple8WithNames = comp.CreateTupleTypeSymbol(vt8, ImmutableArray.Create("Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8")) Assert.True(tuple8WithNames.IsTupleType) Assert.Equal("(Alice1 As System.Int32, Alice2 As System.String, Alice3 As System.Int32, Alice4 As System.String, Alice5 As System.Int32, Alice6 As System.String, Alice7 As System.Int32, Alice8 As System.String)", tuple8WithNames.ToTestDisplayString()) Assert.Equal(New String() {"Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8"}, GetTupleElementNames(tuple8WithNames)) Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String"}, ElementTypeNames(tuple8WithNames)) Assert.All(tuple8WithNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()), Sub(Loc) Assert.Equal(Loc, Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_Tuple9NoNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim vt9 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest). Construct(intType, stringType, intType, stringType, intType, stringType, intType, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(stringType, intType)) Dim tuple9WithoutNames = comp.CreateTupleTypeSymbol(vt9, Nothing) Assert.True(tuple9WithoutNames.IsTupleType) Assert.Equal("(System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32)", tuple9WithoutNames.ToTestDisplayString()) Assert.True(GetTupleElementNames(tuple9WithoutNames).IsDefault) Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32"}, ElementTypeNames(tuple9WithoutNames)) Assert.All(tuple9WithoutNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()), Sub(Loc) Assert.Equal(Loc, Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_Tuple9WithNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim vt9 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest). Construct(intType, stringType, intType, stringType, intType, stringType, intType, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(stringType, intType)) Dim tuple9WithNames = comp.CreateTupleTypeSymbol(vt9, ImmutableArray.Create("Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8", "Alice9")) Assert.True(tuple9WithNames.IsTupleType) Assert.Equal("(Alice1 As System.Int32, Alice2 As System.String, Alice3 As System.Int32, Alice4 As System.String, Alice5 As System.Int32, Alice6 As System.String, Alice7 As System.Int32, Alice8 As System.String, Alice9 As System.Int32)", tuple9WithNames.ToTestDisplayString()) Assert.Equal(New String() {"Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8", "Alice9"}, GetTupleElementNames(tuple9WithNames)) Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32"}, ElementTypeNames(tuple9WithNames)) Assert.All(tuple9WithNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()), Sub(Loc) Assert.Equal(Loc, Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_Tuple9WithDefaultNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As TypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim vt9 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest). Construct(intType, stringType, intType, stringType, intType, stringType, intType, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(stringType, intType)) Dim tuple9WithNames = comp.CreateTupleTypeSymbol(vt9, ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9")) Assert.True(tuple9WithNames.IsTupleType) Assert.Equal("(Item1 As System.Int32, Item2 As System.String, Item3 As System.Int32, Item4 As System.String, Item5 As System.Int32, Item6 As System.String, Item7 As System.Int32, Item8 As System.String, Item9 As System.Int32)", tuple9WithNames.ToTestDisplayString()) Assert.Equal(New String() {"Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9"}, GetTupleElementNames(tuple9WithNames)) Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32"}, ElementTypeNames(tuple9WithNames)) Assert.All(tuple9WithNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()), Sub(Loc) Assert.Equal(Loc, Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_ElementTypeIsError() Dim tupleComp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><%= s_trivial2uple %></file> </compilation>) Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef, tupleComp.ToMetadataReference()}) Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, ErrorTypeSymbol.UnknownResultType) Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(vt2, Nothing) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind) Dim types = tupleWithoutNames.TupleElements.SelectAsArray(Function(e) e.Type) Assert.Equal(2, types.Length) Assert.Equal(SymbolKind.NamedType, types(0).Kind) Assert.Equal(SymbolKind.ErrorType, types(1).Kind) Assert.All(tupleWithoutNames.GetMembers().OfType(Of IFieldSymbol)().Select(Function(f) f.Locations.FirstOrDefault()), Sub(Loc) Assert.Equal(Loc, Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_BadNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) Dim intType As NamedTypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, intType) Dim vt3 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T3).Construct(intType, intType, intType) ' Illegal VB identifier, space and null Dim tuple2 = comp.CreateTupleTypeSymbol(vt3, ImmutableArray.Create("123", " ", Nothing)) Assert.Equal({"123", " ", Nothing}, GetTupleElementNames(tuple2)) ' Reserved keywords Dim tuple3 = comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("return", "class")) Assert.Equal({"return", "class"}, GetTupleElementNames(tuple3)) Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(underlyingType:=intType)) Assert.Contains(CodeAnalysisResources.TupleUnderlyingTypeMustBeTupleCompatible, ex.Message) End Sub <Fact> Public Sub CreateTupleTypeSymbol_EmptyNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) Dim intType As NamedTypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim vt2 = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(intType, intType) ' Illegal VB identifier and empty Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(vt2, ImmutableArray.Create("123", ""))) Assert.Contains(CodeAnalysisResources.TupleElementNameEmpty, ex.Message) Assert.Contains("1", ex.Message) End Sub <Fact> Public Sub CreateTupleTypeSymbol_CSharpElements() Dim csSource = "public class C { }" Dim csComp = CreateCSharpCompilation("CSharp", csSource, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) csComp.VerifyDiagnostics() Dim csType = DirectCast(csComp.GlobalNamespace.GetMembers("C").Single(), INamedTypeSymbol) Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(csType, Nothing)) Assert.Contains(VBResources.NotAVbSymbol, ex.Message) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_BadArguments() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Assert.Throws(Of ArgumentNullException)(Sub() comp.CreateTupleTypeSymbol(elementTypes:=Nothing, elementNames:=Nothing)) ' 0-tuple and 1-tuple are not supported at this point Assert.Throws(Of ArgumentException)(Sub() comp.CreateTupleTypeSymbol(elementTypes:=ImmutableArray(Of ITypeSymbol).Empty, elementNames:=Nothing)) Assert.Throws(Of ArgumentException)(Sub() comp.CreateTupleTypeSymbol(elementTypes:=ImmutableArray.Create(intType), elementNames:=Nothing)) ' If names are provided, you need as many as element types Assert.Throws(Of ArgumentException)(Sub() comp.CreateTupleTypeSymbol(elementTypes:=ImmutableArray.Create(intType, intType), elementNames:=ImmutableArray.Create("Item1"))) ' null types aren't allowed Assert.Throws(Of ArgumentNullException)(Sub() comp.CreateTupleTypeSymbol(elementTypes:=ImmutableArray.Create(intType, Nothing), elementNames:=Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_WithValueTuple() Dim tupleComp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><%= s_trivial2uple %></file> </compilation>) Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef, tupleComp.ToMetadataReference()}) Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType), ImmutableArray.Create(Of String)(Nothing, Nothing)) Assert.True(tupleWithoutNames.IsTupleType) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.TupleUnderlyingType.Kind) Assert.Equal("(System.Int32, System.String)", tupleWithoutNames.ToTestDisplayString()) Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault) Assert.Equal(New String() {"System.Int32", "System.String"}, ElementTypeNames(tupleWithoutNames)) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_Locations() Dim tupleComp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><%= s_trivial2uple %></file> </compilation>) Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef, tupleComp.ToMetadataReference()}) Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim tree = VisualBasicSyntaxTree.ParseText("Class C") Dim loc1 = Location.Create(tree, New TextSpan(0, 1)) Dim loc2 = Location.Create(tree, New TextSpan(1, 1)) Dim tuple = comp.CreateTupleTypeSymbol( ImmutableArray.Create(intType, stringType), ImmutableArray.Create("i1", "i2"), ImmutableArray.Create(loc1, loc2)) Assert.True(tuple.IsTupleType) Assert.Equal(SymbolKind.NamedType, tuple.TupleUnderlyingType.Kind) Assert.Equal("(i1 As System.Int32, i2 As System.String)", tuple.ToTestDisplayString()) Assert.Equal(New String() {"System.Int32", "System.String"}, ElementTypeNames(tuple)) Assert.Equal(SymbolKind.NamedType, tuple.Kind) Assert.Equal(loc1, tuple.GetMembers("i1").Single().Locations.Single()) Assert.Equal(loc2, tuple.GetMembers("i2").Single().Locations.Single()) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_NoNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType), Nothing) Assert.True(tupleWithoutNames.IsTupleType) Assert.Equal(SymbolKind.ErrorType, tupleWithoutNames.TupleUnderlyingType.Kind) Assert.Equal("(System.Int32, System.String)", tupleWithoutNames.ToTestDisplayString()) Assert.True(GetTupleElementNames(tupleWithoutNames).IsDefault) Assert.Equal(New String() {"System.Int32", "System.String"}, ElementTypeNames(tupleWithoutNames)) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_WithNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType), ImmutableArray.Create("Alice", "Bob")) Assert.True(tupleWithoutNames.IsTupleType) Assert.Equal(SymbolKind.ErrorType, tupleWithoutNames.TupleUnderlyingType.Kind) Assert.Equal("(Alice As System.Int32, Bob As System.String)", tupleWithoutNames.ToTestDisplayString()) Assert.Equal(New String() {"Alice", "Bob"}, GetTupleElementNames(tupleWithoutNames)) Assert.Equal(New String() {"System.Int32", "System.String"}, ElementTypeNames(tupleWithoutNames)) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_WithBadNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, intType), ImmutableArray.Create("Item2", "Item1")) Assert.True(tupleWithoutNames.IsTupleType) Assert.Equal("(Item2 As System.Int32, Item1 As System.Int32)", tupleWithoutNames.ToTestDisplayString()) Assert.Equal(New String() {"Item2", "Item1"}, GetTupleElementNames(tupleWithoutNames)) Assert.Equal(New String() {"System.Int32", "System.Int32"}, ElementTypeNames(tupleWithoutNames)) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_Tuple8NoNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim tuple8WithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType, intType, stringType, intType, stringType, intType, stringType), Nothing) Assert.True(tuple8WithoutNames.IsTupleType) Assert.Equal("(System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, System.String)", tuple8WithoutNames.ToTestDisplayString()) Assert.True(GetTupleElementNames(tuple8WithoutNames).IsDefault) Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String"}, ElementTypeNames(tuple8WithoutNames)) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_Tuple8WithNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim tuple8WithNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType, intType, stringType, intType, stringType, intType, stringType), ImmutableArray.Create("Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8")) Assert.True(tuple8WithNames.IsTupleType) Assert.Equal("(Alice1 As System.Int32, Alice2 As System.String, Alice3 As System.Int32, Alice4 As System.String, Alice5 As System.Int32, Alice6 As System.String, Alice7 As System.Int32, Alice8 As System.String)", tuple8WithNames.ToTestDisplayString()) Assert.Equal(New String() {"Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8"}, GetTupleElementNames(tuple8WithNames)) Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String"}, ElementTypeNames(tuple8WithNames)) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_Tuple9NoNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim tuple9WithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType, intType, stringType, intType, stringType, intType, stringType, intType), Nothing) Assert.True(tuple9WithoutNames.IsTupleType) Assert.Equal("(System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32, System.String, System.Int32)", tuple9WithoutNames.ToTestDisplayString()) Assert.True(GetTupleElementNames(tuple9WithoutNames).IsDefault) Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32"}, ElementTypeNames(tuple9WithoutNames)) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_Tuple9WithNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) ' no ValueTuple Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String) Dim tuple9WithNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, stringType, intType, stringType, intType, stringType, intType, stringType, intType), ImmutableArray.Create("Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8", "Alice9")) Assert.True(tuple9WithNames.IsTupleType) Assert.Equal("(Alice1 As System.Int32, Alice2 As System.String, Alice3 As System.Int32, Alice4 As System.String, Alice5 As System.Int32, Alice6 As System.String, Alice7 As System.Int32, Alice8 As System.String, Alice9 As System.Int32)", tuple9WithNames.ToTestDisplayString()) Assert.Equal(New String() {"Alice1", "Alice2", "Alice3", "Alice4", "Alice5", "Alice6", "Alice7", "Alice8", "Alice9"}, GetTupleElementNames(tuple9WithNames)) Assert.Equal(New String() {"System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32", "System.String", "System.Int32"}, ElementTypeNames(tuple9WithNames)) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_ElementTypeIsError() Dim tupleComp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><%= s_trivial2uple %></file> </compilation>) Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef, tupleComp.ToMetadataReference()}) Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim tupleWithoutNames = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, ErrorTypeSymbol.UnknownResultType), Nothing) Assert.Equal(SymbolKind.NamedType, tupleWithoutNames.Kind) Dim types = tupleWithoutNames.TupleElements.SelectAsArray(Function(e) e.Type) Assert.Equal(2, types.Length) Assert.Equal(SymbolKind.NamedType, types(0).Kind) Assert.Equal(SymbolKind.ErrorType, types(1).Kind) End Sub <Fact> Public Sub CreateTupleTypeSymbol2_BadNames() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) Dim intType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) ' Illegal VB identifier and blank Dim tuple2 = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, intType), ImmutableArray.Create("123", " ")) Assert.Equal({"123", " "}, GetTupleElementNames(tuple2)) ' Reserved keywords Dim tuple3 = comp.CreateTupleTypeSymbol(ImmutableArray.Create(intType, intType), ImmutableArray.Create("return", "class")) Assert.Equal({"return", "class"}, GetTupleElementNames(tuple3)) End Sub Private Shared Function GetTupleElementNames(tuple As INamedTypeSymbol) As ImmutableArray(Of String) Dim elements = tuple.TupleElements If elements.All(Function(e) e.IsImplicitlyDeclared) Then Return Nothing End If Return elements.SelectAsArray(Function(e) e.ProvidedTupleElementNameOrNull) End Function <Fact> Public Sub CreateTupleTypeSymbol2_CSharpElements() Dim csSource = "public class C { }" Dim csComp = CreateCSharpCompilation("CSharp", csSource, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) csComp.VerifyDiagnostics() Dim csType = DirectCast(csComp.GlobalNamespace.GetMembers("C").Single(), INamedTypeSymbol) Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) Dim stringType As ITypeSymbol = comp.GetSpecialType(SpecialType.System_String) Assert.Throws(Of ArgumentException)(Sub() comp.CreateTupleTypeSymbol(ImmutableArray.Create(stringType, csType), Nothing)) End Sub <Fact> Public Sub CreateTupleTypeSymbol_ComparingSymbols() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Dim F As System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (a As String, b As String)) End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) Dim tuple1 = comp.GlobalNamespace.GetMember(Of SourceMemberFieldSymbol)("C.F").Type Dim intType = comp.GetSpecialType(SpecialType.System_Int32) Dim stringType = comp.GetSpecialType(SpecialType.System_String) Dim twoStrings = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).Construct(stringType, stringType) Dim twoStringsWithNames = DirectCast(comp.CreateTupleTypeSymbol(twoStrings, ImmutableArray.Create("a", "b")), TypeSymbol) Dim tuple2Underlying = comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest).Construct(intType, intType, intType, intType, intType, intType, intType, twoStringsWithNames) Dim tuple2 = DirectCast(comp.CreateTupleTypeSymbol(tuple2Underlying), TypeSymbol) Dim tuple3 = DirectCast(comp.CreateTupleTypeSymbol(ImmutableArray.Create(Of ITypeSymbol)(intType, intType, intType, intType, intType, intType, intType, stringType, stringType), ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "a", "b")), TypeSymbol) Dim tuple4 = DirectCast(comp.CreateTupleTypeSymbol(CType(tuple1.TupleUnderlyingType, INamedTypeSymbol), ImmutableArray.Create("Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "a", "b")), TypeSymbol) Assert.True(tuple1.Equals(tuple2)) 'Assert.True(tuple1.Equals(tuple2, TypeCompareKind.IgnoreDynamicAndTupleNames)) Assert.False(tuple1.Equals(tuple3)) 'Assert.True(tuple1.Equals(tuple3, TypeCompareKind.IgnoreDynamicAndTupleNames)) Assert.False(tuple1.Equals(tuple4)) 'Assert.True(tuple1.Equals(tuple4, TypeCompareKind.IgnoreDynamicAndTupleNames)) End Sub <Fact> Public Sub TupleMethodsOnNonTupleType() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef}) Dim intType As NamedTypeSymbol = comp.GetSpecialType(SpecialType.System_String) Assert.False(intType.IsTupleType) Assert.True(intType.TupleElementNames.IsDefault) Assert.True(intType.TupleElementTypes.IsDefault) End Sub <Fact> <WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")> Public Sub CreateTupleTypeSymbol_UnderlyingType_DefaultArgs() Dim comp = CreateCompilation( "Module Program Private F As (Integer, String) End Module") Dim tuple1 = DirectCast(DirectCast(comp.GetMember("Program.F"), IFieldSymbol).Type, INamedTypeSymbol) Dim underlyingType = tuple1.TupleUnderlyingType Dim tuple2 = comp.CreateTupleTypeSymbol(underlyingType) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(underlyingType, Nothing) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(underlyingType, Nothing, Nothing) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(underlyingType, Nothing, Nothing, Nothing) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNames:=Nothing) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementLocations:=Nothing) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations:=Nothing) Assert.True(tuple1.Equals(tuple2)) End Sub <Fact> <WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")> Public Sub CreateTupleTypeSymbol_ElementTypes_DefaultArgs() Dim comp = CreateCompilation( "Module Program Private F As (Integer, String) End Module") Dim tuple1 = DirectCast(DirectCast(comp.GetMember("Program.F"), IFieldSymbol).Type, INamedTypeSymbol) Dim elementTypes = tuple1.TupleElements.SelectAsArray(Function(e) e.Type) Dim tuple2 = comp.CreateTupleTypeSymbol(elementTypes) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(elementTypes, Nothing) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(elementTypes, Nothing, Nothing) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(elementTypes, Nothing, Nothing, Nothing) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNames:=Nothing) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementLocations:=Nothing) Assert.True(tuple1.Equals(tuple2)) tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations:=Nothing) Assert.True(tuple1.Equals(tuple2)) End Sub <Fact> <WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")> Public Sub CreateTupleTypeSymbol_UnderlyingType_WithNullableAnnotations_01() Dim comp = CreateCompilation( "Module Program Private F As (Integer, String) End Module") Dim tuple1 = DirectCast(DirectCast(comp.GetMember("Program.F"), IFieldSymbol).Type, INamedTypeSymbol) Dim underlyingType = tuple1.TupleUnderlyingType Dim tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations:=Nothing) Assert.True(tuple1.Equals(tuple2)) Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations:=ImmutableArray(Of NullableAnnotation).Empty)) Assert.Contains(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, ex.Message) tuple2 = comp.CreateTupleTypeSymbol( underlyingType, elementNullableAnnotations:=ImmutableArray.Create(CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None)) Assert.True(tuple1.Equals(tuple2)) Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString()) tuple2 = comp.CreateTupleTypeSymbol( underlyingType, elementNullableAnnotations:=ImmutableArray.Create(CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableAnnotation.Annotated)) Assert.True(tuple1.Equals(tuple2)) Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString()) tuple2 = comp.CreateTupleTypeSymbol( underlyingType, elementNullableAnnotations:=ImmutableArray.Create(CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.None)) Assert.True(tuple1.Equals(tuple2)) Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString()) End Sub <Fact> <WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")> Public Sub CreateTupleTypeSymbol_UnderlyingType_WithNullableAnnotations_02() Dim comp = CreateCompilation( "Module Program Private F As (_1 As Object, _2 As Object, _3 As Object, _4 As Object, _5 As Object, _6 As Object, _7 As Object, _8 As Object, _9 As Object) End Module") Dim tuple1 = DirectCast(DirectCast(comp.GetMember("Program.F"), IFieldSymbol).Type, INamedTypeSymbol) Dim underlyingType = tuple1.TupleUnderlyingType Dim tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations:=Nothing) Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)) Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString()) Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations:=CreateAnnotations(CodeAnalysis.NullableAnnotation.NotAnnotated, 8))) Assert.Contains(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, ex.Message) tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations:=CreateAnnotations(CodeAnalysis.NullableAnnotation.None, 9)) Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)) Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString()) tuple2 = comp.CreateTupleTypeSymbol(underlyingType, elementNullableAnnotations:=CreateAnnotations(CodeAnalysis.NullableAnnotation.Annotated, 9)) Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)) Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString()) End Sub <Fact> <WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")> Public Sub CreateTupleTypeSymbol_ElementTypes_WithNullableAnnotations_01() Dim comp = CreateCompilation( "Module Program Private F As (Integer, String) End Module") Dim tuple1 = DirectCast(DirectCast(comp.GetMember("Program.F"), IFieldSymbol).Type, INamedTypeSymbol) Dim elementTypes = tuple1.TupleElements.SelectAsArray(Function(e) e.Type) Dim tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations:=Nothing) Assert.True(tuple1.Equals(tuple2)) Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations:=ImmutableArray(Of NullableAnnotation).Empty)) Assert.Contains(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, ex.Message) tuple2 = comp.CreateTupleTypeSymbol( elementTypes, elementNullableAnnotations:=ImmutableArray.Create(CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None)) Assert.True(tuple1.Equals(tuple2)) Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString()) tuple2 = comp.CreateTupleTypeSymbol( elementTypes, elementNullableAnnotations:=ImmutableArray.Create(CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableAnnotation.Annotated)) Assert.True(tuple1.Equals(tuple2)) Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString()) tuple2 = comp.CreateTupleTypeSymbol( elementTypes, elementNullableAnnotations:=ImmutableArray.Create(CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.None)) Assert.True(tuple1.Equals(tuple2)) Assert.Equal("(System.Int32, System.String)", tuple2.ToTestDisplayString()) End Sub <Fact> <WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")> Public Sub CreateTupleTypeSymbol_ElementTypes_WithNullableAnnotations_02() Dim comp = CreateCompilation( "Module Program Private F As (_1 As Object, _2 As Object, _3 As Object, _4 As Object, _5 As Object, _6 As Object, _7 As Object, _8 As Object, _9 As Object) End Module") Dim tuple1 = DirectCast(DirectCast(comp.GetMember("Program.F"), IFieldSymbol).Type, INamedTypeSymbol) Dim elementTypes = tuple1.TupleElements.SelectAsArray(Function(e) e.Type) Dim tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations:=Nothing) Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)) Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString()) Dim ex = Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations:=CreateAnnotations(CodeAnalysis.NullableAnnotation.NotAnnotated, 8))) Assert.Contains(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, ex.Message) tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations:=CreateAnnotations(CodeAnalysis.NullableAnnotation.None, 9)) Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)) Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString()) tuple2 = comp.CreateTupleTypeSymbol(elementTypes, elementNullableAnnotations:=CreateAnnotations(CodeAnalysis.NullableAnnotation.Annotated, 9)) Assert.True(TypeEquals(tuple1, tuple2, TypeCompareKind.IgnoreTupleNames)) Assert.Equal("(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", tuple2.ToTestDisplayString()) End Sub Private Shared Function CreateAnnotations(annotation As CodeAnalysis.NullableAnnotation, n As Integer) As ImmutableArray(Of CodeAnalysis.NullableAnnotation) Return ImmutableArray.CreateRange(Enumerable.Range(0, n).Select(Function(i) annotation)) End Function Private Shared Function TypeEquals(a As ITypeSymbol, b As ITypeSymbol, compareKind As TypeCompareKind) As Boolean Return TypeSymbol.Equals(DirectCast(a, TypeSymbol), DirectCast(b, TypeSymbol), compareKind) End Function <Fact> Public Sub TupleTargetTypeAndConvert01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class C Shared Sub Main() ' This works Dim x1 As (Short, String) = (1, "hello") Dim x2 As (Short, String) = DirectCast((1, "hello"), (Long, String)) Dim x3 As (a As Short, b As String) = DirectCast((1, "hello"), (c As Long, d As String)) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30512: Option Strict On disallows implicit conversions from '(Long, String)' to '(Short, String)'. Dim x2 As (Short, String) = DirectCast((1, "hello"), (Long, String)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from '(c As Long, d As String)' to '(a As Short, b As String)'. Dim x3 As (a As Short, b As String) = DirectCast((1, "hello"), (c As Long, d As String)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleTargetTypeAndConvert02() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x2 As (Short, String) = DirectCast((1, "hello"), (Byte, String)) System.Console.WriteLine(x2) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(1, hello)]]>) verifier.VerifyDiagnostics() verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 41 (0x29) .maxstack 3 .locals init (System.ValueTuple(Of Byte, String) V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: ldstr "hello" IL_0008: call "Sub System.ValueTuple(Of Byte, String)..ctor(Byte, String)" IL_000d: ldloc.0 IL_000e: ldfld "System.ValueTuple(Of Byte, String).Item1 As Byte" IL_0013: ldloc.0 IL_0014: ldfld "System.ValueTuple(Of Byte, String).Item2 As String" IL_0019: newobj "Sub System.ValueTuple(Of Short, String)..ctor(Short, String)" IL_001e: box "System.ValueTuple(Of Short, String)" IL_0023: call "Sub System.Console.WriteLine(Object)" IL_0028: ret } ]]>) End Sub <Fact> Public Sub TupleImplicitConversionFail01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class C Shared Sub Main() Dim x As (Integer, Integer) x = (Nothing, Nothing, Nothing) x = (1, 2, 3) x = (1, "string") x = (1, 1, garbage) x = (1, 1, ) x = (Nothing, Nothing) ' ok x = (1, Nothing) ' ok x = (1, Function(t) t) x = Nothing ' ok End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30311: Value of type '(Object, Object, Object)' cannot be converted to '(Integer, Integer)'. x = (Nothing, Nothing, Nothing) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30311: Value of type '(Integer, Integer, Integer)' cannot be converted to '(Integer, Integer)'. x = (1, 2, 3) ~~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Integer'. x = (1, "string") ~~~~~~~~ BC30451: 'garbage' is not declared. It may be inaccessible due to its protection level. x = (1, 1, garbage) ~~~~~~~ BC30201: Expression expected. x = (1, 1, ) ~ BC36625: Lambda expression cannot be converted to 'Integer' because 'Integer' is not a delegate type. x = (1, Function(t) t) ~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleExplicitConversionFail01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class C Shared Sub Main() Dim x As (Integer, Integer) x = DirectCast((Nothing, Nothing, Nothing), (Integer, Integer)) x = DirectCast((1, 2, 3), (Integer, Integer)) x = DirectCast((1, "string"), (Integer, Integer)) ' ok x = DirectCast((1, 1, garbage), (Integer, Integer)) x = DirectCast((1, 1, ), (Integer, Integer)) x = DirectCast((Nothing, Nothing), (Integer, Integer)) ' ok x = DirectCast((1, Nothing), (Integer, Integer)) ' ok x = DirectCast((1, Function(t) t), (Integer, Integer)) x = DirectCast(Nothing, (Integer, Integer)) ' ok End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30311: Value of type '(Object, Object, Object)' cannot be converted to '(Integer, Integer)'. x = DirectCast((Nothing, Nothing, Nothing), (Integer, Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30311: Value of type '(Integer, Integer, Integer)' cannot be converted to '(Integer, Integer)'. x = DirectCast((1, 2, 3), (Integer, Integer)) ~~~~~~~~~ BC30451: 'garbage' is not declared. It may be inaccessible due to its protection level. x = DirectCast((1, 1, garbage), (Integer, Integer)) ~~~~~~~ BC30201: Expression expected. x = DirectCast((1, 1, ), (Integer, Integer)) ~ BC36625: Lambda expression cannot be converted to 'Integer' because 'Integer' is not a delegate type. x = DirectCast((1, Function(t) t), (Integer, Integer)) ~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleImplicitConversionFail02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class C Shared Sub Main() Dim x As System.ValueTuple(Of Integer, Integer) x = (Nothing, Nothing, Nothing) x = (1, 2, 3) x = (1, "string") x = (1, 1, garbage) x = (1, 1, ) x = (Nothing, Nothing) ' ok x = (1, Nothing) ' ok x = (1, Function(t) t) x = Nothing ' ok End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30311: Value of type '(Object, Object, Object)' cannot be converted to '(Integer, Integer)'. x = (Nothing, Nothing, Nothing) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30311: Value of type '(Integer, Integer, Integer)' cannot be converted to '(Integer, Integer)'. x = (1, 2, 3) ~~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Integer'. x = (1, "string") ~~~~~~~~ BC30451: 'garbage' is not declared. It may be inaccessible due to its protection level. x = (1, 1, garbage) ~~~~~~~ BC30201: Expression expected. x = (1, 1, ) ~ BC36625: Lambda expression cannot be converted to 'Integer' because 'Integer' is not a delegate type. x = (1, Function(t) t) ~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleInferredLambdaStrictOn() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class C Shared Sub Main() Dim valid = (1, Function() Nothing) Dim x = (Nothing, Function(t) t) Dim y = (1, Function(t) t) Dim z = (Function(t) t, Function(t) t) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred. Dim x = (Nothing, Function(t) t) ~ BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred. Dim y = (1, Function(t) t) ~ BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred. Dim z = (Function(t) t, Function(t) t) ~ BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred. Dim z = (Function(t) t, Function(t) t) ~ </errors>) End Sub <Fact()> Public Sub TupleInferredLambdaStrictOff() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict Off Class C Shared Sub Main() Dim valid = (1, Function() Nothing) Test(valid) Dim x = (Nothing, Function(t) t) Test(x) Dim y = (1, Function(t) t) Test(y) End Sub shared function Test(of T)(x as T) as T System.Console.WriteLine(GetType(T)) return x End Function End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ System.ValueTuple`2[System.Int32,VB$AnonymousDelegate_0`1[System.Object]] System.ValueTuple`2[System.Object,VB$AnonymousDelegate_1`2[System.Object,System.Object]] System.ValueTuple`2[System.Int32,VB$AnonymousDelegate_1`2[System.Object,System.Object]] ]]>) End Sub <Fact> Public Sub TupleImplicitConversionFail03() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class C Shared Sub Main() Dim x As (String, String) x = (Nothing, Nothing, Nothing) x = (1, 2, 3) x = (1, "string") x = (1, 1, garbage) x = (1, 1, ) x = (Nothing, Nothing) ' ok x = (1, Nothing) ' ok x = (1, Function(t) t) x = Nothing ' ok End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30311: Value of type '(Object, Object, Object)' cannot be converted to '(String, String)'. x = (Nothing, Nothing, Nothing) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30311: Value of type '(Integer, Integer, Integer)' cannot be converted to '(String, String)'. x = (1, 2, 3) ~~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'. x = (1, "string") ~ BC30451: 'garbage' is not declared. It may be inaccessible due to its protection level. x = (1, 1, garbage) ~~~~~~~ BC30201: Expression expected. x = (1, 1, ) ~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'. x = (1, Nothing) ' ok ~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'. x = (1, Function(t) t) ~ BC36625: Lambda expression cannot be converted to 'String' because 'String' is not a delegate type. x = (1, Function(t) t) ~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleImplicitConversionFail04() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class C Shared Sub Main() Dim x As ((Integer, Integer), Integer) x = ((Nothing, Nothing, Nothing), 1) x = ((1, 2, 3), 1) x = ((1, "string"), 1) x = ((1, 1, garbage), 1) x = ((1, 1, ), 1) x = ((Nothing, Nothing), 1) ' ok x = ((1, Nothing), 1) ' ok x = ((1, Function(t) t), 1) x = (Nothing, 1) ' ok End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30311: Value of type '(Object, Object, Object)' cannot be converted to '(Integer, Integer)'. x = ((Nothing, Nothing, Nothing), 1) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30311: Value of type '(Integer, Integer, Integer)' cannot be converted to '(Integer, Integer)'. x = ((1, 2, 3), 1) ~~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'String' to 'Integer'. x = ((1, "string"), 1) ~~~~~~~~ BC30451: 'garbage' is not declared. It may be inaccessible due to its protection level. x = ((1, 1, garbage), 1) ~~~~~~~ BC30201: Expression expected. x = ((1, 1, ), 1) ~ BC36625: Lambda expression cannot be converted to 'Integer' because 'Integer' is not a delegate type. x = ((1, Function(t) t), 1) ~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleImplicitConversionFail05() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub Main() Dim x As (x0 As System.ValueTuple(Of Integer, Integer), x1 As Integer, x2 As Integer, x3 As Integer, x4 As Integer, x5 As Integer, x6 As Integer, x7 As Integer, x8 As Integer, x9 As Integer, x10 As Integer) x = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) x = ((0, 0.0), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8 ) x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9.1, 10) x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9 x = ((0, 0), 1, 2, 3, 4, oops, 6, 7, oopsss, 9, 10) x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9) x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, (1, 1, 1), 10) End Sub End Class ]]><%= s_trivial2uple %><%= s_trivialRemainingTuples %></file> </compilation>) ' Intentionally not including 3-tuple for use-site errors comp.AssertTheseDiagnostics( <errors> BC30311: Value of type 'Integer' cannot be converted to '(Integer, Integer)'. x = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) ~ BC30311: Value of type '((Integer, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)' cannot be converted to '(x0 As (Integer, Integer), x1 As Integer, x2 As Integer, x3 As Integer, x4 As Integer, x5 As Integer, x6 As Integer, x7 As Integer, x8 As Integer, x9 As Integer, x10 As Integer)'. x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30311: Value of type '((Integer, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)' cannot be converted to '(x0 As (Integer, Integer), x1 As Integer, x2 As Integer, x3 As Integer, x4 As Integer, x5 As Integer, x6 As Integer, x7 As Integer, x8 As Integer, x9 As Integer, x10 As Integer)'. x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8 ) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of ,,)' is not defined or imported. x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30452: Operator '=' is not defined for types '(x0 As (Integer, Integer), x1 As Integer, x2 As Integer, x3 As Integer, x4 As Integer, x5 As Integer, x6 As Integer, x7 As Integer, x8 As Integer, x9 As Integer, x10 As Integer)' and '((Integer, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'. x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of ,,)' is not defined or imported. x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30198: ')' expected. x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9 ~ BC30198: ')' expected. x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9 ~ BC30451: 'oops' is not declared. It may be inaccessible due to its protection level. x = ((0, 0), 1, 2, 3, 4, oops, 6, 7, oopsss, 9, 10) ~~~~ BC30451: 'oopsss' is not declared. It may be inaccessible due to its protection level. x = ((0, 0), 1, 2, 3, 4, oops, 6, 7, oopsss, 9, 10) ~~~~~~ BC30311: Value of type '((Integer, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)' cannot be converted to '(x0 As (Integer, Integer), x1 As Integer, x2 As Integer, x3 As Integer, x4 As Integer, x5 As Integer, x6 As Integer, x7 As Integer, x8 As Integer, x9 As Integer, x10 As Integer)'. x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of ,,)' is not defined or imported. x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, 9) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30311: Value of type '(Integer, Integer, Integer)' cannot be converted to 'Integer'. x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, (1, 1, 1), 10) ~~~~~~~~~ BC37267: Predefined type 'ValueTuple(Of ,,)' is not defined or imported. x = ((0, 0), 1, 2, 3, 4, 5, 6, 7, 8, (1, 1, 1), 10) ~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleImplicitConversionFail06() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Class C Shared Sub Main() Dim l As Func(Of String) = Function() 1 Dim x As (String, Func(Of String)) = (Nothing, Function() 1) Dim l1 As Func(Of (String, String)) = Function() (Nothing, 1.1) Dim x1 As (String, Func(Of (String, String))) = (Nothing, Function() (Nothing, 1.1)) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'. Dim l As Func(Of String) = Function() 1 ~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'. Dim x As (String, Func(Of String)) = (Nothing, Function() 1) ~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'String'. Dim l1 As Func(Of (String, String)) = Function() (Nothing, 1.1) ~~~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'String'. Dim x1 As (String, Func(Of (String, String))) = (Nothing, Function() (Nothing, 1.1)) ~~~ </errors>) End Sub <Fact> Public Sub TupleExplicitConversionFail06() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Class C Shared Sub Main() Dim l As Func(Of String) = Function() 1 Dim x As (String, Func(Of String)) = DirectCast((Nothing, Function() 1), (String, Func(Of String))) Dim l1 As Func(Of (String, String)) = DirectCast(Function() (Nothing, 1.1), Func(Of (String, String))) Dim x1 As (String, Func(Of (String, String))) = DirectCast((Nothing, Function() (Nothing, 1.1)), (String, Func(Of (String, String)))) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'. Dim l As Func(Of String) = Function() 1 ~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'. Dim x As (String, Func(Of String)) = DirectCast((Nothing, Function() 1), (String, Func(Of String))) ~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'String'. Dim l1 As Func(Of (String, String)) = DirectCast(Function() (Nothing, 1.1), Func(Of (String, String))) ~~~ BC30512: Option Strict On disallows implicit conversions from 'Double' to 'String'. Dim x1 As (String, Func(Of (String, String))) = DirectCast((Nothing, Function() (Nothing, 1.1)), (String, Func(Of (String, String)))) ~~~ </errors>) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub TupleCTypeNullableConversionWithTypelessTuple() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Class C Shared Sub Main() Dim x As (Integer, String)? = CType((1, Nothing), (Integer, String)?) Console.Write(x) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertNoDiagnostics() CompileAndVerify(comp, expectedOutput:="(1, )") Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(1, Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(node).Kind) Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) Dim [ctype] = tree.GetRoot().DescendantNodes().OfType(Of CTypeExpressionSyntax)().Single() Assert.Equal("CType((1, Nothing), (Integer, String)?)", [ctype].ToString()) comp.VerifyOperationTree([ctype], expectedOperationTree:= <![CDATA[ IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of (System.Int32, System.String))) (Syntax: 'CType((1, N ... , String)?)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.String)) (Syntax: '(1, Nothing)') NaturalType: null Elements(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') ]]>.Value) End Sub <Fact> Public Sub TupleDirectCastNullableConversionWithTypelessTuple() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Class C Shared Sub Main() Dim x As (Integer, String)? = DirectCast((1, Nothing), (Integer, String)?) Console.Write(x) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertNoDiagnostics() CompileAndVerify(comp, expectedOutput:="(1, )") Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(1, Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(node).Kind) Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) End Sub <Fact> Public Sub TupleTryCastNullableConversionWithTypelessTuple() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Class C Shared Sub Main() Dim x As (Integer, String)? = TryCast((1, Nothing), (Integer, String)?) Console.Write(x) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics(<errors> BC30792: 'TryCast' operand must be reference type, but '(Integer, String)?' is a value type. Dim x As (Integer, String)? = TryCast((1, Nothing), (Integer, String)?) ~~~~~~~~~~~~~~~~~~ </errors>) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(1, Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(node).Kind) Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) End Sub <Fact> Public Sub TupleTryCastNullableConversionWithTypelessTuple2() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Imports System Class C Shared Sub M(Of T)() Dim x = TryCast((0, Nothing), C(Of Integer, T)) Console.Write(x) End Sub End Class Class C(Of T, U) End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics(<errors> BC30311: Value of type '(Integer, Object)' cannot be converted to 'C(Of Integer, T)'. Dim x = TryCast((0, Nothing), C(Of Integer, T)) ~~~~~~~~~~~~ </errors>) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(0, Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(node).Kind) Assert.Equal("C(Of System.Int32, T)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("C(Of System.Int32, T)", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) End Sub <Fact> Public Sub TupleImplicitNullableConversionWithTypelessTuple() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Class C Shared Sub Main() Dim x As (Integer, String)? = (1, Nothing) System.Console.Write(x) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertNoDiagnostics() CompileAndVerify(comp, expectedOutput:="(1, )") Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(1, Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Assert.Equal("System.Nullable(Of (System.Int32, System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(node).Kind) End Sub <Fact> Public Sub ImplicitConversionOnTypelessTupleWithUserConversion() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Structure C Shared Sub Main() Dim x As C = (1, Nothing) Dim y As C? = (2, Nothing) End Sub Public Shared Widening Operator CType(ByVal d As (Integer, String)) As C Return New C() End Operator End Structure ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics(<errors> BC30311: Value of type '(Integer, Object)' cannot be converted to 'C?'. Dim y As C? = (2, Nothing) ~~~~~~~~~~~~ </errors>) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim firstTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(0) Assert.Equal("(1, Nothing)", firstTuple.ToString()) Assert.Null(model.GetTypeInfo(firstTuple).Type) Assert.Equal("C", model.GetTypeInfo(firstTuple).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Narrowing Or ConversionKind.UserDefined, model.GetConversion(firstTuple).Kind) Dim secondTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(1) Assert.Equal("(2, Nothing)", secondTuple.ToString()) Assert.Null(model.GetTypeInfo(secondTuple).Type) Assert.Equal("System.Nullable(Of C)", model.GetTypeInfo(secondTuple).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.DelegateRelaxationLevelNone, model.GetConversion(secondTuple).Kind) End Sub <Fact> Public Sub DirectCastOnTypelessTupleWithUserConversion() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Structure C Shared Sub Main() Dim x = DirectCast((1, Nothing), C) Dim y = DirectCast((2, Nothing), C?) End Sub Public Shared Widening Operator CType(ByVal d As (Integer, String)) As C Return New C() End Operator End Structure ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics(<errors> BC30311: Value of type '(Integer, Object)' cannot be converted to 'C'. Dim x = DirectCast((1, Nothing), C) ~~~~~~~~~~~~ BC30311: Value of type '(Integer, Object)' cannot be converted to 'C?'. Dim y = DirectCast((2, Nothing), C?) ~~~~~~~~~~~~ </errors>) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim firstTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(0) Assert.Equal("(1, Nothing)", firstTuple.ToString()) Assert.Null(model.GetTypeInfo(firstTuple).Type) Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(firstTuple).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(firstTuple).Kind) Dim secondTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(1) Assert.Equal("(2, Nothing)", secondTuple.ToString()) Assert.Null(model.GetTypeInfo(secondTuple).Type) Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(secondTuple).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(secondTuple).Kind) End Sub <Fact> Public Sub TryCastOnTypelessTupleWithUserConversion() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Structure C Shared Sub Main() Dim x = TryCast((1, Nothing), C) Dim y = TryCast((2, Nothing), C?) End Sub Public Shared Widening Operator CType(ByVal d As (Integer, String)) As C Return New C() End Operator End Structure ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics(<errors> BC30792: 'TryCast' operand must be reference type, but 'C' is a value type. Dim x = TryCast((1, Nothing), C) ~ BC30792: 'TryCast' operand must be reference type, but 'C?' is a value type. Dim y = TryCast((2, Nothing), C?) ~~ </errors>) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim firstTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(0) Assert.Equal("(1, Nothing)", firstTuple.ToString()) Assert.Null(model.GetTypeInfo(firstTuple).Type) Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(firstTuple).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(firstTuple).Kind) Dim secondTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(1) Assert.Equal("(2, Nothing)", secondTuple.ToString()) Assert.Null(model.GetTypeInfo(secondTuple).Type) Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(secondTuple).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(secondTuple).Kind) End Sub <Fact> Public Sub CTypeOnTypelessTupleWithUserConversion() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Structure C Shared Sub Main() Dim x = CType((1, Nothing), C) Dim y = CType((2, Nothing), C?) End Sub Public Shared Widening Operator CType(ByVal d As (Integer, String)) As C Return New C() End Operator End Structure ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics(<errors> BC30311: Value of type '(Integer, Object)' cannot be converted to 'C?'. Dim y = CType((2, Nothing), C?) ~~~~~~~~~~~~ </errors>) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim firstTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(0) Assert.Equal("(1, Nothing)", firstTuple.ToString()) Assert.Null(model.GetTypeInfo(firstTuple).Type) Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(firstTuple).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(firstTuple).Kind) Dim secondTuple = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ElementAt(1) Assert.Equal("(2, Nothing)", secondTuple.ToString()) Assert.Null(model.GetTypeInfo(secondTuple).Type) Assert.Equal("(System.Int32, System.Object)", model.GetTypeInfo(secondTuple).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(secondTuple).Kind) End Sub <Fact> Public Sub TupleTargetTypeLambda() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Imports System Class C Shared Sub Test(d As Func(Of Func(Of (Short, Short)))) Console.WriteLine("short") End Sub Shared Sub Test(d As Func(Of Func(Of (Byte, Byte)))) Console.WriteLine("byte") End Sub Shared Sub Main() Test(Function() Function() DirectCast((1, 1), (Byte, Byte))) Test(Function() Function() (1, 1)) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30521: Overload resolution failed because no accessible 'Test' is most specific for these arguments: 'Public Shared Sub Test(d As Func(Of Func(Of (Short, Short))))': Not most specific. 'Public Shared Sub Test(d As Func(Of Func(Of (Byte, Byte))))': Not most specific. Test(Function() Function() DirectCast((1, 1), (Byte, Byte))) ~~~~ BC30521: Overload resolution failed because no accessible 'Test' is most specific for these arguments: 'Public Shared Sub Test(d As Func(Of Func(Of (Short, Short))))': Not most specific. 'Public Shared Sub Test(d As Func(Of Func(Of (Byte, Byte))))': Not most specific. Test(Function() Function() (1, 1)) ~~~~ </errors>) End Sub <Fact> Public Sub TupleTargetTypeLambda1() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Imports System Class C Shared Sub Test(d As Func(Of (Func(Of Short), Integer))) Console.WriteLine("short") End Sub Shared Sub Test(d As Func(Of (Func(Of Byte), Integer))) Console.WriteLine("byte") End Sub Shared Sub Main() Test(Function() (Function() CType(1, Byte), 1)) Test(Function() (Function() 1, 1)) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30521: Overload resolution failed because no accessible 'Test' is most specific for these arguments: 'Public Shared Sub Test(d As Func(Of (Func(Of Short), Integer)))': Not most specific. 'Public Shared Sub Test(d As Func(Of (Func(Of Byte), Integer)))': Not most specific. Test(Function() (Function() CType(1, Byte), 1)) ~~~~ BC30521: Overload resolution failed because no accessible 'Test' is most specific for these arguments: 'Public Shared Sub Test(d As Func(Of (Func(Of Short), Integer)))': Not most specific. 'Public Shared Sub Test(d As Func(Of (Func(Of Byte), Integer)))': Not most specific. Test(Function() (Function() 1, 1)) ~~~~ </errors>) End Sub <Fact> Public Sub TargetTypingOverload01() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C Shared Sub Main() Test((Nothing, Nothing)) Test((1, 1)) Test((Function() 7, Function() 8), 2) End Sub Shared Sub Test(Of T)(x As (T, T)) Console.WriteLine("first") End Sub Shared Sub Test(x As (Object, Object)) Console.WriteLine("second") End Sub Shared Sub Test(Of T)(x As (Func(Of T), Func(Of T)), y As T) Console.WriteLine("third") Console.WriteLine(x.Item1().ToString()) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[second first third 7]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TargetTypingOverload02() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Class C Shared Sub Main() Test1((Function() 7, Function() 8)) Test2(Function() 7, Function() 8) End Sub Shared Sub Test1(Of T)(x As (T, T)) Console.WriteLine("first") End Sub Shared Sub Test1(x As (Object, Object)) Console.WriteLine("second") End Sub Shared Sub Test1(Of T)(x As (Func(Of T), Func(Of T))) Console.WriteLine("third") Console.WriteLine(x.Item1().ToString()) End Sub Shared Sub Test2(Of T)(x As T, y as T) Console.WriteLine("first") End Sub Shared Sub Test2(x As Object, y as Object) Console.WriteLine("second") End Sub Shared Sub Test2(Of T)(x As Func(Of T), y as Func(Of T)) Console.WriteLine("third") End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:= "first first") verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TargetTypingNullable01() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C Shared Sub Main() Dim x = M1() Test(x) End Sub Shared Function M1() As (a As Integer, b As Double)? Return (1, 2) End Function Shared Sub Test(Of T)(arg As T) Console.WriteLine(GetType(T)) Console.WriteLine(arg) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[System.Nullable`1[System.ValueTuple`2[System.Int32,System.Double]] (1, 2)]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub TargetTypingOverload01Long() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C Shared Sub Main() Test((Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing)) Test((1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) Test((Function() 11, Function() 12, Function() 13, Function() 14, Function() 15, Function() 16, Function() 17, Function() 18, Function() 19, Function() 20)) End Sub Shared Sub Test(Of T)(x As (T, T, T, T, T, T, T, T, T, T)) Console.WriteLine("first") End Sub Shared Sub Test(x As (Object, Object, Object, Object, Object, Object, Object, Object, Object, Object)) Console.WriteLine("second") End Sub Shared Sub Test(Of T)(x As (Func(Of T), Func(Of T), Func(Of T), Func(Of T), Func(Of T), Func(Of T), Func(Of T), Func(Of T), Func(Of T), Func(Of T)), y As T) Console.WriteLine("third") Console.WriteLine(x.Item1().ToString()) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[second first first]]>) verifier.VerifyDiagnostics() End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/12961")> Public Sub TargetTypingNullable02() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C Shared Sub Main() Dim x = M1() Test(x) End Sub Shared Function M1() As (a As Integer, b As String)? Return (1, Nothing) End Function Shared Sub Test(Of T)(arg As T) Console.WriteLine(GetType(T)) Console.WriteLine(arg) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[System.Nullable`1[System.ValueTuple`2[System.Int32,System.String]] (1, )]]>) verifier.VerifyDiagnostics() End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/12961")> Public Sub TargetTypingNullable02Long() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C Shared Sub Main() Dim x = M1() Console.WriteLine(x?.a) Console.WriteLine(x?.a8) Test(x) End Sub Shared Function M1() As (a As Integer, b As String, a1 As Integer, a2 As Integer, a3 As Integer, a4 As Integer, a5 As Integer, a6 As Integer, a7 As Integer, a8 As Integer)? Return (1, Nothing, 1, 2, 3, 4, 5, 6, 7, 8) End Function Shared Sub Test(Of T)(arg As T) Console.WriteLine(arg) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[System.Nullable`1[System.ValueTuple`2[System.Int32,System.String]] (1, )]]>) verifier.VerifyDiagnostics() End Sub <Fact(Skip:="https://github.com/dotnet/roslyn/issues/12961")> Public Sub TargetTypingNullableOverload() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C Shared Sub Main() Test((Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing)) ' Overload resolution fails Test(("a", "a", "a", "a", "a", "a", "a", "a", "a", "a")) Test((1, 1, 1, 1, 1, 1, 1, 1, 1, 1)) End Sub Shared Sub Test(x As (String, String, String, String, String, String, String, String, String, String)) Console.WriteLine("first") End Sub Shared Sub Test(x As (String, String, String, String, String, String, String, String, String, String)?) Console.WriteLine("second") End Sub Shared Sub Test(x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)?) Console.WriteLine("third") End Sub Shared Sub Test(x As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)) Console.WriteLine("fourth") End Sub End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[first fourth]]>) verifier.VerifyDiagnostics() End Sub <Fact()> <WorkItem(13277, "https://github.com/dotnet/roslyn/issues/13277")> <WorkItem(14365, "https://github.com/dotnet/roslyn/issues/14365")> Public Sub CreateTupleTypeSymbol_UnderlyingTypeIsError() Dim comp = VisualBasicCompilation.Create("test", references:={MscorlibRef, TestReferences.SymbolsTests.netModule.netModule1}) Dim intType As TypeSymbol = comp.GetSpecialType(SpecialType.System_Int32) Dim vt2 = comp.CreateErrorTypeSymbol(Nothing, "ValueTuple", 2).Construct(intType, intType) Assert.Throws(Of ArgumentException)(Function() comp.CreateTupleTypeSymbol(underlyingType:=vt2)) Dim csComp = CreateCSharpCompilation("") Assert.Throws(Of ArgumentNullException)(Sub() comp.CreateErrorTypeSymbol(Nothing, Nothing, 2)) Assert.Throws(Of ArgumentException)(Sub() comp.CreateErrorTypeSymbol(Nothing, "a", -1)) Assert.Throws(Of ArgumentException)(Sub() comp.CreateErrorTypeSymbol(csComp.GlobalNamespace, "a", 1)) Assert.Throws(Of ArgumentNullException)(Sub() comp.CreateErrorNamespaceSymbol(Nothing, "a")) Assert.Throws(Of ArgumentNullException)(Sub() comp.CreateErrorNamespaceSymbol(csComp.GlobalNamespace, Nothing)) Assert.Throws(Of ArgumentException)(Sub() comp.CreateErrorNamespaceSymbol(csComp.GlobalNamespace, "a")) Dim ns = comp.CreateErrorNamespaceSymbol(comp.GlobalNamespace, "a") Assert.Equal("a", ns.ToTestDisplayString()) Assert.False(ns.IsGlobalNamespace) Assert.Equal(NamespaceKind.Compilation, ns.NamespaceKind) Assert.Same(comp.GlobalNamespace, ns.ContainingSymbol) Assert.Same(comp.GlobalNamespace.ContainingAssembly, ns.ContainingAssembly) Assert.Same(comp.GlobalNamespace.ContainingModule, ns.ContainingModule) ns = comp.CreateErrorNamespaceSymbol(comp.Assembly.GlobalNamespace, "a") Assert.Equal("a", ns.ToTestDisplayString()) Assert.False(ns.IsGlobalNamespace) Assert.Equal(NamespaceKind.Assembly, ns.NamespaceKind) Assert.Same(comp.Assembly.GlobalNamespace, ns.ContainingSymbol) Assert.Same(comp.Assembly.GlobalNamespace.ContainingAssembly, ns.ContainingAssembly) Assert.Same(comp.Assembly.GlobalNamespace.ContainingModule, ns.ContainingModule) ns = comp.CreateErrorNamespaceSymbol(comp.SourceModule.GlobalNamespace, "a") Assert.Equal("a", ns.ToTestDisplayString()) Assert.False(ns.IsGlobalNamespace) Assert.Equal(NamespaceKind.Module, ns.NamespaceKind) Assert.Same(comp.SourceModule.GlobalNamespace, ns.ContainingSymbol) Assert.Same(comp.SourceModule.GlobalNamespace.ContainingAssembly, ns.ContainingAssembly) Assert.Same(comp.SourceModule.GlobalNamespace.ContainingModule, ns.ContainingModule) ns = comp.CreateErrorNamespaceSymbol(comp.CreateErrorNamespaceSymbol(comp.GlobalNamespace, "a"), "b") Assert.Equal("a.b", ns.ToTestDisplayString()) ns = comp.CreateErrorNamespaceSymbol(comp.GlobalNamespace, "") Assert.Equal("", ns.ToTestDisplayString()) Assert.False(ns.IsGlobalNamespace) vt2 = comp.CreateErrorTypeSymbol(comp.CreateErrorNamespaceSymbol(comp.GlobalNamespace, "System"), "ValueTuple", 2).Construct(intType, intType) Assert.Equal("(System.Int32, System.Int32)", comp.CreateTupleTypeSymbol(underlyingType:=vt2).ToTestDisplayString()) vt2 = comp.CreateErrorTypeSymbol(comp.CreateErrorNamespaceSymbol(comp.Assembly.GlobalNamespace, "System"), "ValueTuple", 2).Construct(intType, intType) Assert.Equal("(System.Int32, System.Int32)", comp.CreateTupleTypeSymbol(underlyingType:=vt2).ToTestDisplayString()) vt2 = comp.CreateErrorTypeSymbol(comp.CreateErrorNamespaceSymbol(comp.SourceModule.GlobalNamespace, "System"), "ValueTuple", 2).Construct(intType, intType) Assert.Equal("(System.Int32, System.Int32)", comp.CreateTupleTypeSymbol(underlyingType:=vt2).ToTestDisplayString()) End Sub <Fact> <WorkItem(13042, "https://github.com/dotnet/roslyn/issues/13042")> Public Sub GetSymbolInfoOnTupleType() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module C Function M() As (System.Int32, String) throw new System.Exception() End Function End Module </file> </compilation>, references:=s_valueTupleRefs) Dim comp = verifier.Compilation Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim type = nodes.OfType(Of QualifiedNameSyntax)().First() Assert.Equal("System.Int32", type.ToString()) Assert.NotNull(model.GetSymbolInfo(type).Symbol) Assert.Equal("System.Int32", model.GetSymbolInfo(type).Symbol.ToTestDisplayString()) End Sub <Fact(Skip:="See bug 16697")> <WorkItem(16697, "https://github.com/dotnet/roslyn/issues/16697")> Public Sub GetSymbolInfo_01() Dim source = " Class C Shared Sub Main() Dim x1 = (Alice:=1, ""hello"") Dim Alice = x1.Alice End Sub End Class " Dim tree = Parse(source, options:=TestOptions.Regular) Dim comp = CreateCompilationWithMscorlib40(tree) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim nc = nodes.OfType(Of NameColonEqualsSyntax)().ElementAt(0) Dim sym = model.GetSymbolInfo(nc.Name) Assert.Equal("Alice", sym.Symbol.Name) Assert.Equal(SymbolKind.Field, sym.Symbol.Kind) ' Incorrectly returns Local Assert.Equal(nc.Name.GetLocation(), sym.Symbol.Locations(0)) ' Incorrect location End Sub <Fact> <WorkItem(23651, "https://github.com/dotnet/roslyn/issues/23651")> Public Sub GetSymbolInfo_WithDuplicateInferredNames() Dim source = " Class C Shared Sub M(Bob As String) Dim x1 = (Bob, Bob) End Sub End Class " Dim tree = Parse(source, options:=TestOptions.Regular) Dim comp = CreateCompilationWithMscorlib40(tree) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim tuple = nodes.OfType(Of TupleExpressionSyntax)().Single() Dim type = DirectCast(model.GetTypeInfo(tuple).Type, TypeSymbol) Assert.True(type.TupleElementNames.IsDefault) End Sub <Fact> Public Sub RetargetTupleErrorType() Dim libComp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class A Public Shared Function M() As (Integer, Integer) Return (1, 2) End Function End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) libComp.AssertNoDiagnostics() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class B Public Sub M2() A.M() End Sub End Class </file> </compilation>, additionalRefs:={libComp.ToMetadataReference()}) comp.AssertTheseDiagnostics( <errors> BC30652: Reference required to assembly 'System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' containing the type 'ValueTuple(Of ,)'. Add one to your project. A.M() ~~~~~ </errors>) Dim methodM = comp.GetMember(Of MethodSymbol)("A.M") Assert.Equal("(System.Int32, System.Int32)", methodM.ReturnType.ToTestDisplayString()) Assert.True(methodM.ReturnType.IsTupleType) Assert.False(methodM.ReturnType.IsErrorType()) Assert.True(methodM.ReturnType.TupleUnderlyingType.IsErrorType()) End Sub <Fact> Public Sub CaseSensitivity001() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x2 = (A:=10, B:=20) System.Console.Write(x2.a) System.Console.Write(x2.item2) Dim x3 = (item1 := 1, item2 := 2) System.Console.Write(x3.Item1) System.Console.WriteLine(x3.Item2) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[102012]]>) End Sub <Fact> Public Sub CaseSensitivity002() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Module Module1 Sub Main() Dim x1 = (A:=10, a:=20) System.Console.Write(x1.a) System.Console.Write(x1.A) Dim x2 as (A as Integer, a As Integer) = (10, 20) System.Console.Write(x1.a) System.Console.Write(x1.A) Dim x3 = (I1:=10, item1:=20) Dim x4 = (Item1:=10, item1:=20) Dim x5 = (item1:=10, item1:=20) Dim x6 = (tostring:=10, item1:=20) End Sub End Module ]]> </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37262: Tuple element names must be unique. Dim x1 = (A:=10, a:=20) ~ BC31429: 'A' is ambiguous because multiple kinds of members with this name exist in structure '(A As Integer, a As Integer)'. System.Console.Write(x1.a) ~~~~ BC31429: 'A' is ambiguous because multiple kinds of members with this name exist in structure '(A As Integer, a As Integer)'. System.Console.Write(x1.A) ~~~~ BC37262: Tuple element names must be unique. Dim x2 as (A as Integer, a As Integer) = (10, 20) ~ BC31429: 'A' is ambiguous because multiple kinds of members with this name exist in structure '(A As Integer, a As Integer)'. System.Console.Write(x1.a) ~~~~ BC31429: 'A' is ambiguous because multiple kinds of members with this name exist in structure '(A As Integer, a As Integer)'. System.Console.Write(x1.A) ~~~~ BC37261: Tuple element name 'item1' is only allowed at position 1. Dim x3 = (I1:=10, item1:=20) ~~~~~ BC37261: Tuple element name 'item1' is only allowed at position 1. Dim x4 = (Item1:=10, item1:=20) ~~~~~ BC37261: Tuple element name 'item1' is only allowed at position 1. Dim x5 = (item1:=10, item1:=20) ~~~~~ BC37260: Tuple element name 'tostring' is disallowed at any position. Dim x6 = (tostring:=10, item1:=20) ~~~~~~~~ BC37261: Tuple element name 'item1' is only allowed at position 1. Dim x6 = (tostring:=10, item1:=20) ~~~~~ </errors>) End Sub <Fact> Public Sub CaseSensitivity003() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x as (Item1 as String, itEm2 as String, Bob as string) = (Nothing, Nothing, Nothing) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (, , ) ]]>) Dim comp = verifier.Compilation Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(Nothing, Nothing, Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Dim fields = From m In model.GetTypeInfo(node).ConvertedType.GetMembers() Where m.Kind = SymbolKind.Field Order By m.Name Select m.Name ' check no duplication of original/default ItemX fields Assert.Equal("Bob#Item1#Item2#Item3", fields.Join("#")) End Sub <Fact> Public Sub CaseSensitivity004() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim x = ( I1 := 1, I2 := 2, I3 := 3, ITeM4 := 4, I5 := 5, I6 := 6, I7 := 7, ITeM8 := 8, ItEM9 := 9 ) System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (1, 2, 3, 4, 5, 6, 7, 8, 9) ]]>) Dim comp = verifier.Compilation Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Dim fields = From m In model.GetTypeInfo(node).Type.GetMembers() Where m.Kind = SymbolKind.Field Order By m.Name Select m.Name ' check no duplication of original/default ItemX fields Assert.Equal("I1#I2#I3#I5#I6#I7#Item1#Item2#Item3#Item4#Item5#Item6#Item7#Item8#Item9#Rest", fields.Join("#")) End Sub ' The NonNullTypes context for nested tuple types is using a dummy rather than actual context from surrounding code. ' This does not affect `IsNullable`, but it affects `IsAnnotatedWithNonNullTypesContext`, which is used in comparisons. ' So when we copy modifiers (re-applying nullability information, including actual NonNullTypes context), we make the comparison fail. ' I think the solution is to never use a dummy context, even for value types. <Fact> Public Sub TupleNamesFromCS001() Dim csCompilation = CreateCSharpCompilation("CSDll", <![CDATA[ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary1 { public class Class1 { public (int Alice, int Bob) goo = (2, 3); public (int Alice, int Bob) Bar() => (4, 5); public (int Alice, int Bob) Baz => (6, 7); } public class Class2 { public (int Alice, int q, int w, int e, int f, int g, int h, int j, int Bob) goo = SetBob(11); public (int Alice, int q, int w, int e, int f, int g, int h, int j, int Bob) Bar() => SetBob(12); public (int Alice, int q, int w, int e, int f, int g, int h, int j, int Bob) Baz => SetBob(13); private static (int Alice, int q, int w, int e, int f, int g, int h, int j, int Bob) SetBob(int x) { var result = default((int Alice, int q, int w, int e, int f, int g, int h, int j, int Bob)); result.Bob = x; return result; } } public class class3: IEnumerable<(int Alice, int Bob)> { IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } IEnumerator<(Int32 Alice, Int32 Bob)> IEnumerable<(Int32 Alice, Int32 Bob)>.GetEnumerator() { yield return (1, 2); yield return (3, 4); } } } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbCompilation = CreateVisualBasicCompilation("VBDll", <![CDATA[ Module Module1 Sub Main() Dim x As New ClassLibrary1.Class1 System.Console.WriteLine(x.goo.Alice) System.Console.WriteLine(x.goo.Bob) System.Console.WriteLine(x.Bar.Alice) System.Console.WriteLine(x.Bar.Bob) System.Console.WriteLine(x.Baz.Alice) System.Console.WriteLine(x.Baz.Bob) Dim y As New ClassLibrary1.Class2 System.Console.WriteLine(y.goo.Alice) System.Console.WriteLine(y.goo.Bob) System.Console.WriteLine(y.Bar.Alice) System.Console.WriteLine(y.Bar.Bob) System.Console.WriteLine(y.Baz.Alice) System.Console.WriteLine(y.Baz.Bob) Dim z As New ClassLibrary1.class3 For Each item In z System.Console.WriteLine(item.Alice) System.Console.WriteLine(item.Bob) Next End Sub End Module ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}, referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbexeVerifier = CompileAndVerify(vbCompilation, expectedOutput:=" 2 3 4 5 6 7 0 11 0 12 0 13 1 2 3 4") vbexeVerifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleNamesFromVB001() Dim classLib = CreateVisualBasicCompilation("VBClass", <![CDATA[ Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Linq Imports System.Text Imports System.Threading.Tasks Namespace ClassLibrary1 Public Class Class1 Public goo As (Alice As Integer, Bob As Integer) = (2, 3) Public Function Bar() As (Alice As Integer, Bob As Integer) Return (4, 5) End Function Public ReadOnly Property Baz As (Alice As Integer, Bob As Integer) Get Return (6, 7) End Get End Property End Class Public Class Class2 Public goo As (Alice As Integer, q As Integer, w As Integer, e As Integer, f As Integer, g As Integer, h As Integer, j As Integer, Bob As Integer) = SetBob(11) Public Function Bar() As (Alice As Integer, q As Integer, w As Integer, e As Integer, f As Integer, g As Integer, h As Integer, j As Integer, Bob As Integer) Return SetBob(12) End Function Public ReadOnly Property Baz As (Alice As Integer, q As Integer, w As Integer, e As Integer, f As Integer, g As Integer, h As Integer, j As Integer, Bob As Integer) Get Return SetBob(13) End Get End Property Private Shared Function SetBob(x As Integer) As (Alice As Integer, q As Integer, w As Integer, e As Integer, f As Integer, g As Integer, h As Integer, j As Integer, Bob As Integer) Dim result As (Alice As Integer, q As Integer, w As Integer, e As Integer, f As Integer, g As Integer, h As Integer, j As Integer, Bob As Integer) = Nothing result.Bob = x Return result End Function End Class Public Class class3 Implements IEnumerable(Of (Alice As Integer, Bob As Integer)) Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function Public Iterator Function GetEnumerator() As IEnumerator(Of (Alice As Integer, Bob As Integer)) Implements IEnumerable(Of (Alice As Integer, Bob As Integer)).GetEnumerator Yield (1, 2) Yield (3, 4) End Function End Class End Namespace ]]>, compilationOptions:=New Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbCompilation = CreateVisualBasicCompilation("VBDll", <![CDATA[ Module Module1 Sub Main() Dim x As New ClassLibrary1.Class1 System.Console.WriteLine(x.goo.Alice) System.Console.WriteLine(x.goo.Bob) System.Console.WriteLine(x.Bar.Alice) System.Console.WriteLine(x.Bar.Bob) System.Console.WriteLine(x.Baz.Alice) System.Console.WriteLine(x.Baz.Bob) Dim y As New ClassLibrary1.Class2 System.Console.WriteLine(y.goo.Alice) System.Console.WriteLine(y.goo.Bob) System.Console.WriteLine(y.Bar.Alice) System.Console.WriteLine(y.Bar.Bob) System.Console.WriteLine(y.Baz.Alice) System.Console.WriteLine(y.Baz.Bob) Dim z As New ClassLibrary1.class3 For Each item In z System.Console.WriteLine(item.Alice) System.Console.WriteLine(item.Bob) Next End Sub End Module ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={classLib}, referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbexeVerifier = CompileAndVerify(vbCompilation, expectedOutput:=" 2 3 4 5 6 7 0 11 0 12 0 13 1 2 3 4") vbexeVerifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleNamesFromVB001_InterfaceImpl() Dim classLib = CreateVisualBasicCompilation("VBClass", <![CDATA[ Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Linq Imports System.Text Imports System.Threading.Tasks Namespace ClassLibrary1 Public Class class3 Implements IEnumerable(Of (Alice As Integer, Bob As Integer)) Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function Private Iterator Function GetEnumerator() As IEnumerator(Of (Alice As Integer, Bob As Integer)) Implements IEnumerable(Of (Alice As Integer, Bob As Integer)).GetEnumerator Yield (1, 2) Yield (3, 4) End Function End Class End Namespace ]]>, compilationOptions:=New Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbCompilation = CreateVisualBasicCompilation("VBDll", <![CDATA[ Module Module1 Sub Main() Dim z As New ClassLibrary1.class3 For Each item In z System.Console.WriteLine(item.Alice) System.Console.WriteLine(item.Bob) Next End Sub End Module ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={classLib}, referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbexeVerifier = CompileAndVerify(vbCompilation, expectedOutput:=" 1 2 3 4") vbexeVerifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleNamesFromCS002() Dim csCompilation = CreateCSharpCompilation("CSDll", <![CDATA[ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary1 { public class Class1 { public (int Alice, (int Alice, int Bob) Bob) goo = (2, (2, 3)); public ((int Alice, int Bob)[] Alice, int Bob) Bar() => (new(int, int)[] { (4, 5) }, 5); public (int Alice, List<(int Alice, int Bob)?> Bob) Baz => (6, new List<(int Alice, int Bob)?>() { (8, 9) }); public static event Action<(int i0, int i1, int i2, int i3, int i4, int i5, int i6, int i7, (int Alice, int Bob) Bob)> goo1; public static void raise() { goo1((0, 1, 2, 3, 4, 5, 6, 7, (8, 42))); } } } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbCompilation = CreateVisualBasicCompilation("VBDll", <![CDATA[ Module Module1 Sub Main() Dim x As New ClassLibrary1.Class1 System.Console.WriteLine(x.goo.Bob.Bob) System.Console.WriteLine(x.goo.Item2.Item2) System.Console.WriteLine(x.Bar.Alice(0).Bob) System.Console.WriteLine(x.Bar.Item1(0).Item2) System.Console.WriteLine(x.Baz.Bob(0).Value) System.Console.WriteLine(x.Baz.Item2(0).Value) AddHandler ClassLibrary1.Class1.goo1, Sub(p) System.Console.WriteLine(p.Bob.Bob) System.Console.WriteLine(p.Rest.Item2.Bob) End Sub ClassLibrary1.Class1.raise() End Sub End Module ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}, referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbexeVerifier = CompileAndVerify(vbCompilation, expectedOutput:=" 3 3 5 5 (8, 9) (8, 9) 42 42") vbexeVerifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleNamesFromVB002() Dim classLib = CreateVisualBasicCompilation("VBClass", <![CDATA[ Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Linq Imports System.Text Imports System.Threading.Tasks Namespace ClassLibrary1 Public Class Class1 Public goo As (Alice As Integer, Bob As (Alice As Integer, Bob As Integer)) = (2, (2, 3)) Public Function Bar() As (Alice As (Alice As Integer, Bob As Integer)(), Bob As Integer) Return (New(Integer, Integer)() {(4, 5)}, 5) End Function Public ReadOnly Property Baz As (Alice As Integer, Bob As List(Of (Alice As Integer, Bob As Integer) ?)) Get Return (6, New List(Of (Alice As Integer, Bob As Integer) ?)() From {(8, 9)}) End Get End Property Public Shared Event goo1 As Action(Of (i0 As Integer, i1 As Integer, i2 As Integer, i3 As Integer, i4 As Integer, i5 As Integer, i6 As Integer, i7 As Integer, Bob As (Alice As Integer, Bob As Integer))) Public Shared Sub raise() RaiseEvent goo1((0, 1, 2, 3, 4, 5, 6, 7, (8, 42))) End Sub End Class End Namespace ]]>, compilationOptions:=New Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbCompilation = CreateVisualBasicCompilation("VBDll", <![CDATA[ Module Module1 Sub Main() Dim x As New ClassLibrary1.Class1 System.Console.WriteLine(x.goo.Bob.Bob) System.Console.WriteLine(x.goo.Item2.Item2) System.Console.WriteLine(x.Bar.Alice(0).Bob) System.Console.WriteLine(x.Bar.Item1(0).Item2) System.Console.WriteLine(x.Baz.Bob(0).Value) System.Console.WriteLine(x.Baz.Item2(0).Value) AddHandler ClassLibrary1.Class1.goo1, Sub(p) System.Console.WriteLine(p.Bob.Bob) System.Console.WriteLine(p.Rest.Item2.Bob) End Sub ClassLibrary1.Class1.raise() End Sub End Module ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={classLib}, referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbexeVerifier = CompileAndVerify(vbCompilation, expectedOutput:=" 3 3 5 5 (8, 9) (8, 9) 42 42") vbexeVerifier.VerifyDiagnostics() End Sub <Fact> Public Sub TupleNamesFromCS003() Dim csCompilation = CreateCSharpCompilation("CSDll", <![CDATA[ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary1 { public class Class1 { public (int Alice, int alice) goo = (2, 3); } } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbCompilation = CreateVisualBasicCompilation("VBDll", <![CDATA[ Module Module1 Sub Main() Dim x As New ClassLibrary1.Class1 System.Console.WriteLine(x.goo.Item1) System.Console.WriteLine(x.goo.Item2) System.Console.WriteLine(x.goo.Alice) System.Console.WriteLine(x.goo.alice) Dim f = x.goo System.Console.WriteLine(f.Item1) System.Console.WriteLine(f.Item2) System.Console.WriteLine(f.Alice) System.Console.WriteLine(f.alice) End Sub End Module ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}, referencedAssemblies:=s_valueTupleRefsAndDefault) vbCompilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "x.goo.Alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer)").WithLocation(8, 34), Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "x.goo.alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer)").WithLocation(9, 34), Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "f.Alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer)").WithLocation(14, 34), Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "f.alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer)").WithLocation(15, 34) ) End Sub <Fact> Public Sub TupleNamesFromCS004() Dim csCompilation = CreateCSharpCompilation("CSDll", <![CDATA[ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary1 { public class Class1 { public (int Alice, int alice, int) goo = (2, 3, 4); } } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedAssemblies:=s_valueTupleRefsAndDefault) Dim vbCompilation = CreateVisualBasicCompilation("VBDll", <![CDATA[ Module Module1 Sub Main() Dim x As New ClassLibrary1.Class1 System.Console.WriteLine(x.goo.Item1) System.Console.WriteLine(x.goo.Item2) System.Console.WriteLine(x.goo.Item3) System.Console.WriteLine(x.goo.Alice) System.Console.WriteLine(x.goo.alice) Dim f = x.goo System.Console.WriteLine(f.Item1) System.Console.WriteLine(f.Item2) System.Console.WriteLine(f.Item3) System.Console.WriteLine(f.Alice) System.Console.WriteLine(f.alice) End Sub End Module ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}, referencedAssemblies:=s_valueTupleRefsAndDefault) vbCompilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "x.goo.Alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer, Integer)").WithLocation(9, 34), Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "x.goo.alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer, Integer)").WithLocation(10, 34), Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "f.Alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer, Integer)").WithLocation(16, 34), Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "f.alice").WithArguments("Alice", "structure", "(Alice As Integer, alice As Integer, Integer)").WithLocation(17, 34) ) End Sub <Fact> Public Sub BadTupleNameMetadata() Dim comp = CreateCompilationWithCustomILSource(<compilation> <file name="a.vb"> </file> </compilation>, " .assembly extern mscorlib { } .assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 } .class public auto ansi C extends [mscorlib]System.Object { .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> ValidField .field public int32 ValidFieldWithAttribute .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[1](""name1"")} = ( 01 00 01 00 00 00 05 6E 61 6D 65 31 ) .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> TooFewNames .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[1](""name1"")} = ( 01 00 01 00 00 00 05 6E 61 6D 65 31 ) .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> TooManyNames .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[3](""e1"", ""e2"", ""e3"")} = ( 01 00 03 00 00 00 02 65 31 02 65 32 02 65 33 ) .method public hidebysig instance class [System.ValueTuple]System.ValueTuple`2<int32,int32> TooFewNamesMethod() cil managed { .param [0] .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[1](""name1"")} = ( 01 00 01 00 00 00 05 6E 61 6D 65 31 ) // Code size 8 (0x8) .maxstack 8 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: newobj instance void class [System.ValueTuple]System.ValueTuple`2<int32,int32>::.ctor(!0, !1) IL_0007: ret } // end of method C::TooFewNamesMethod .method public hidebysig instance class [System.ValueTuple]System.ValueTuple`2<int32,int32> TooManyNamesMethod() cil managed { .param [0] .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[3](""e1"", ""e2"", ""e3"")} = ( 01 00 03 00 00 00 02 65 31 02 65 32 02 65 33 ) // Code size 8 (0x8) .maxstack 8 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: newobj instance void class [System.ValueTuple]System.ValueTuple`2<int32,int32>::.ctor(!0, !1) IL_0007: ret } // end of method C::TooManyNamesMethod } // end of class C ", additionalReferences:=s_valueTupleRefs) Dim c = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim validField = c.GetMember(Of FieldSymbol)("ValidField") Assert.False(validField.Type.IsErrorType()) Assert.True(validField.Type.IsTupleType) Assert.True(validField.Type.TupleElementNames.IsDefault) Dim validFieldWithAttribute = c.GetMember(Of FieldSymbol)("ValidFieldWithAttribute") Assert.True(validFieldWithAttribute.Type.IsErrorType()) Assert.False(validFieldWithAttribute.Type.IsTupleType) Assert.IsType(Of UnsupportedMetadataTypeSymbol)(validFieldWithAttribute.Type) Assert.False(DirectCast(validFieldWithAttribute.Type, INamedTypeSymbol).IsSerializable) Dim tooFewNames = c.GetMember(Of FieldSymbol)("TooFewNames") Assert.True(tooFewNames.Type.IsErrorType()) Assert.IsType(Of UnsupportedMetadataTypeSymbol)(tooFewNames.Type) Assert.False(DirectCast(tooFewNames.Type, INamedTypeSymbol).IsSerializable) Dim tooManyNames = c.GetMember(Of FieldSymbol)("TooManyNames") Assert.True(tooManyNames.Type.IsErrorType()) Assert.IsType(Of UnsupportedMetadataTypeSymbol)(tooManyNames.Type) Dim tooFewNamesMethod = c.GetMember(Of MethodSymbol)("TooFewNamesMethod") Assert.True(tooFewNamesMethod.ReturnType.IsErrorType()) Assert.IsType(Of UnsupportedMetadataTypeSymbol)(tooFewNamesMethod.ReturnType) Dim tooManyNamesMethod = c.GetMember(Of MethodSymbol)("TooManyNamesMethod") Assert.True(tooManyNamesMethod.ReturnType.IsErrorType()) Assert.IsType(Of UnsupportedMetadataTypeSymbol)(tooManyNamesMethod.ReturnType) End Sub <Fact> Public Sub MetadataForPartiallyNamedTuples() Dim comp = CreateCompilationWithCustomILSource(<compilation> <file name="a.vb"> </file> </compilation>, " .assembly extern mscorlib { } .assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 } .class public auto ansi C extends [mscorlib]System.Object { .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> ValidField .field public int32 ValidFieldWithAttribute .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[1](""name1"")} = ( 01 00 01 00 00 00 05 6E 61 6D 65 31 ) // In source, all or no names must be specified for a tuple .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> PartialNames .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[2](""e1"", null)} = ( 01 00 02 00 00 00 02 65 31 FF ) .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> AllNullNames .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // = {string[2](null, null)} = ( 01 00 02 00 00 00 ff ff 00 00 ) .method public hidebysig instance void PartialNamesMethod( class [System.ValueTuple]System.ValueTuple`1<class [System.ValueTuple]System.ValueTuple`2<int32,int32>> c) cil managed { .param [1] .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // First null is fine (unnamed tuple) but the second is half-named // = {string[3](null, ""e1"", null)} = ( 01 00 03 00 00 00 FF 02 65 31 FF ) // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method C::PartialNamesMethod .method public hidebysig instance void AllNullNamesMethod( class [System.ValueTuple]System.ValueTuple`1<class [System.ValueTuple]System.ValueTuple`2<int32,int32>> c) cil managed { .param [1] .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) // First null is fine (unnamed tuple) but the second is half-named // = {string[3](null, null, null)} = ( 01 00 03 00 00 00 ff ff ff 00 00 ) // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method C::AllNullNamesMethod } // end of class C ", additionalReferences:=s_valueTupleRefs) Dim c = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim validField = c.GetMember(Of FieldSymbol)("ValidField") Assert.False(validField.Type.IsErrorType()) Assert.True(validField.Type.IsTupleType) Assert.True(validField.Type.TupleElementNames.IsDefault) Dim validFieldWithAttribute = c.GetMember(Of FieldSymbol)("ValidFieldWithAttribute") Assert.True(validFieldWithAttribute.Type.IsErrorType()) Assert.False(validFieldWithAttribute.Type.IsTupleType) Assert.IsType(Of UnsupportedMetadataTypeSymbol)(validFieldWithAttribute.Type) Dim partialNames = c.GetMember(Of FieldSymbol)("PartialNames") Assert.False(partialNames.Type.IsErrorType()) Assert.True(partialNames.Type.IsTupleType) Assert.Equal("(e1 As System.Int32, System.Int32)", partialNames.Type.ToTestDisplayString()) Dim allNullNames = c.GetMember(Of FieldSymbol)("AllNullNames") Assert.False(allNullNames.Type.IsErrorType()) Assert.True(allNullNames.Type.IsTupleType) Assert.Equal("(System.Int32, System.Int32)", allNullNames.Type.ToTestDisplayString()) Dim partialNamesMethod = c.GetMember(Of MethodSymbol)("PartialNamesMethod") Dim partialParamType = partialNamesMethod.Parameters.Single().Type Assert.False(partialParamType.IsErrorType()) Assert.True(partialParamType.IsTupleType) Assert.Equal("ValueTuple(Of (e1 As System.Int32, System.Int32))", partialParamType.ToTestDisplayString()) Dim allNullNamesMethod = c.GetMember(Of MethodSymbol)("AllNullNamesMethod") Dim allNullParamType = allNullNamesMethod.Parameters.Single().Type Assert.False(allNullParamType.IsErrorType()) Assert.True(allNullParamType.IsTupleType) Assert.Equal("ValueTuple(Of (System.Int32, System.Int32))", allNullParamType.ToTestDisplayString()) End Sub <Fact> Public Sub NestedTuplesNoAttribute() Dim comp = CreateCompilationWithCustomILSource(<compilation> <file name="a.vb"> </file> </compilation>, " .assembly extern mscorlib { } .assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 } .class public auto ansi beforefieldinit Base`1<T> extends [mscorlib]System.Object { } .class public auto ansi C extends [mscorlib]System.Object { .field public class [System.ValueTuple]System.ValueTuple`2<int32, int32> Field1 .field public class Base`1<class [System.ValueTuple]System.ValueTuple`1< class [System.ValueTuple]System.ValueTuple`2<int32, int32>>> Field2; } // end of class C ", additionalReferences:=s_valueTupleRefs) Dim c = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim base1 = comp.GlobalNamespace.GetTypeMember("Base") Assert.NotNull(base1) Dim field1 = c.GetMember(Of FieldSymbol)("Field1") Assert.False(field1.Type.IsErrorType()) Assert.True(field1.Type.IsTupleType) Assert.True(field1.Type.TupleElementNames.IsDefault) Dim field2Type = DirectCast(c.GetMember(Of FieldSymbol)("Field2").Type, NamedTypeSymbol) Assert.Equal(base1, field2Type.OriginalDefinition) Assert.True(field2Type.IsGenericType) Dim first = field2Type.TypeArguments(0) Assert.True(first.IsTupleType) Assert.Equal(1, first.TupleElementTypes.Length) Assert.True(first.TupleElementNames.IsDefault) Dim second = first.TupleElementTypes(0) Assert.True(second.IsTupleType) Assert.True(second.TupleElementNames.IsDefault) Assert.Equal(2, second.TupleElementTypes.Length) Assert.All(second.TupleElementTypes, Sub(t) Assert.Equal(SpecialType.System_Int32, t.SpecialType)) End Sub <Fact> <WorkItem(258853, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/258853")> Public Sub BadOverloadWithTupleLiteralWithNaturalType() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub M(x As Integer) End Sub Sub M(x As String) End Sub Sub Main() M((1, 2)) End Sub End Module </file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics( <errors> BC30518: Overload resolution failed because no accessible 'M' can be called with these arguments: 'Public Sub M(x As Integer)': Value of type '(Integer, Integer)' cannot be converted to 'Integer'. 'Public Sub M(x As String)': Value of type '(Integer, Integer)' cannot be converted to 'String'. M((1, 2)) ~ </errors>) End Sub <Fact> <WorkItem(258853, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/258853")> Public Sub BadOverloadWithTupleLiteralWithNothing() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub M(x As Integer) End Sub Sub M(x As String) End Sub Sub Main() M((1, Nothing)) End Sub End Module </file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics( <errors> BC30518: Overload resolution failed because no accessible 'M' can be called with these arguments: 'Public Sub M(x As Integer)': Value of type '(Integer, Object)' cannot be converted to 'Integer'. 'Public Sub M(x As String)': Value of type '(Integer, Object)' cannot be converted to 'String'. M((1, Nothing)) ~ </errors>) End Sub <Fact> <WorkItem(258853, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/258853")> Public Sub BadOverloadWithTupleLiteralWithAddressOf() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub M(x As Integer) End Sub Sub M(x As String) End Sub Sub Main() M((1, AddressOf Main)) End Sub End Module </file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics( <errors> BC30518: Overload resolution failed because no accessible 'M' can be called with these arguments: 'Public Sub M(x As Integer)': Expression does not produce a value. 'Public Sub M(x As String)': Expression does not produce a value. M((1, AddressOf Main)) ~ </errors>) End Sub <Fact> Public Sub TupleLiteralWithOnlySomeNames() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module C Sub Main() Dim t As (Integer, String, Integer) = (1, b:="hello", Item3:=3) console.write($"{t.Item1} {t.Item2} {t.Item3}") End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:="1 hello 3") End Sub <Fact()> <WorkItem(13705, "https://github.com/dotnet/roslyn/issues/13705")> Public Sub TupleCoVariance() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Interface I(Of Out T) Function M() As System.ValueTuple(Of Integer, T) End Interface ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC36726: Type 'T' cannot be used for the 'T2' in 'System.ValueTuple(Of T1, T2)' in this context because 'T' is an 'Out' type parameter. Function M() As System.ValueTuple(Of Integer, T) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> <WorkItem(13705, "https://github.com/dotnet/roslyn/issues/13705")> Public Sub TupleCoVariance2() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Interface I(Of Out T) Function M() As (Integer, T) End Interface ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC36726: Type 'T' cannot be used for the 'T2' in 'System.ValueTuple(Of T1, T2)' in this context because 'T' is an 'Out' type parameter. Function M() As (Integer, T) ~~~~~~~~~~~~ </errors>) End Sub <Fact()> <WorkItem(13705, "https://github.com/dotnet/roslyn/issues/13705")> Public Sub TupleContraVariance() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Interface I(Of In T) Sub M(x As (Boolean, T)) End Interface ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC36727: Type 'T' cannot be used for the 'T2' in 'System.ValueTuple(Of T1, T2)' in this context because 'T' is an 'In' type parameter. Sub M(x As (Boolean, T)) ~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub DefiniteAssignment001() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (A as string, B as string) ss.A = "q" ss.Item2 = "w" System.Console.WriteLine(ss) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, w)]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DefiniteAssignment001Err() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (A as string, B as string) ss.A = "q" 'ss.Item2 = "w" System.Console.WriteLine(ss) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, )]]>) verifier.VerifyDiagnostics( Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss").WithArguments("ss").WithLocation(8, 34) ) End Sub <Fact> Public Sub DefiniteAssignment002() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (A as string, B as string) ss.A = "q" ss.B = "q" ss.Item1 = "w" ss.Item2 = "w" System.Console.WriteLine(ss) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(w, w)]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DefiniteAssignment003() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (A as string, D as (B as string, C as string )) ss.A = "q" ss.D.B = "w" ss.D.C = "e" System.Console.WriteLine(ss) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, (w, e))]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DefiniteAssignment004() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (I1 as string , I2 As string, I3 As string, I4 As string, I5 As string, I6 As string, I7 As string, I8 As string, I9 As string, I10 As string) ss.I1 = "q" ss.I2 = "q" ss.I3 = "q" ss.I4 = "q" ss.I5 = "q" ss.I6 = "q" ss.I7 = "q" ss.I8 = "q" ss.I9 = "q" ss.I10 = "q" System.Console.WriteLine(ss) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q, q, q, q, q, q, q, q)]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DefiniteAssignment005() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String, I9 As String, I10 As String) ss.Item1 = "q" ss.Item2 = "q" ss.Item3 = "q" ss.Item4 = "q" ss.Item5 = "q" ss.Item6 = "q" ss.Item7 = "q" ss.Item8 = "q" ss.Item9 = "q" ss.Item10 = "q" System.Console.WriteLine(ss) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q, q, q, q, q, q, q, q)]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DefiniteAssignment006() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String, I9 As String, I10 As String) ss.Item1 = "q" ss.I2 = "q" ss.Item3 = "q" ss.I4 = "q" ss.Item5 = "q" ss.I6 = "q" ss.Item7 = "q" ss.I8 = "q" ss.Item9 = "q" ss.I10 = "q" System.Console.WriteLine(ss) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q, q, q, q, q, q, q, q)]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DefiniteAssignment007() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String, I9 As String, I10 As String) ss.Item1 = "q" ss.I2 = "q" ss.Item3 = "q" ss.I4 = "q" ss.Item5 = "q" ss.I6 = "q" ss.Item7 = "q" ss.I8 = "q" ss.Item9 = "q" ss.I10 = "q" System.Console.WriteLine(ss.Rest) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q)]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DefiniteAssignment008() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String, I9 As String, I10 As String) ss.I8 = "q" ss.Item9 = "q" ss.I10 = "q" System.Console.WriteLine(ss.Rest) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q)]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DefiniteAssignment008long() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String, I9 As String, I10 As String, I11 as string, I12 As String, I13 As String, I14 As String, I15 As String, I16 As String, I17 As String, I18 As String, I19 As String, I20 As String, I21 as string, I22 As String, I23 As String, I24 As String, I25 As String, I26 As String, I27 As String, I28 As String, I29 As String, I30 As String, I31 As String) 'warn System.Console.WriteLine(ss.Rest.Rest.Rest) 'warn System.Console.WriteLine(ss.I31) ss.I29 = "q" ss.Item30 = "q" ss.I31 = "q" System.Console.WriteLine(ss.I29) System.Console.WriteLine(ss.Rest.Rest.Rest) System.Console.WriteLine(ss.I31) ' warn System.Console.WriteLine(ss.Rest.Rest) ' warn System.Console.WriteLine(ss.Rest) ' warn System.Console.WriteLine(ss) ' warn System.Console.WriteLine(ss.I2) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ (, , , , , , , , , ) q (, , , , , , , q, q, q) q (, , , , , , , , , , , , , , q, q, q) (, , , , , , , , , , , , , , , , , , , , , q, q, q) (, , , , , , , , , , , , , , , , , , , , , , , , , , , , q, q, q)]]>) verifier.VerifyDiagnostics( Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss.Rest.Rest.Rest").WithArguments("Rest").WithLocation(36, 34), Diagnostic(ERRID.WRN_DefAsgUseNullRef, "ss.I31").WithArguments("I31").WithLocation(38, 34), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss.Rest.Rest").WithArguments("Rest").WithLocation(49, 34), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss.Rest").WithArguments("Rest").WithLocation(52, 34), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss").WithArguments("ss").WithLocation(55, 34), Diagnostic(ERRID.WRN_DefAsgUseNullRef, "ss.I2").WithArguments("I2").WithLocation(58, 34)) End Sub <Fact> Public Sub DefiniteAssignment009() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String, I9 As String, I10 As String) ss.I1 = "q" ss.I2 = "q" ss.I3 = "q" ss.I4 = "q" ss.I5 = "q" ss.I6 = "q" ss.I7 = "q" ss.Rest = Nothing System.Console.WriteLine(ss) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q, q, q, q, q, , , )]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DefiniteAssignment010() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String, I9 As String, I10 As String) ss.Rest = ("q", "w", "e") System.Console.WriteLine(ss.I9) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[w]]>) verifier.VerifyDiagnostics() End Sub <Fact> Public Sub DefiniteAssignment011() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() if (1.ToString() = 2.ToString()) Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String) ss.I1 = "q" ss.I2 = "q" ss.I3 = "q" ss.I4 = "q" ss.I5 = "q" ss.I6 = "q" ss.I7 = "q" ss.I8 = "q" System.Console.WriteLine(ss) elseif (1.ToString() = 3.ToString()) Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String) ss.I1 = "q" ss.I2 = "q" ss.I3 = "q" ss.I4 = "q" ss.I5 = "q" ss.I6 = "q" ss.I7 = "q" ' ss.I8 = "q" System.Console.WriteLine(ss) else Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String) ss.I1 = "q" ss.I2 = "q" ss.I3 = "q" ss.I4 = "q" ss.I5 = "q" ss.I6 = "q" ' ss.I7 = "q" ss.I8 = "q" System.Console.WriteLine(ss) ' should fail end if End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q, q, q, q, , q)]]>) verifier.VerifyDiagnostics( Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss").WithArguments("ss").WithLocation(44, 38), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss").WithArguments("ss").WithLocation(65, 38) ) End Sub <Fact> Public Sub DefiniteAssignment012() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() if (1.ToString() = 2.ToString()) Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String) ss.I1 = "q" ss.I2 = "q" ss.I3 = "q" ss.I4 = "q" ss.I5 = "q" ss.I6 = "q" ss.I7 = "q" ss.I8 = "q" System.Console.WriteLine(ss) else if (1.ToString() = 3.ToString()) Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String) ss.I1 = "q" ss.I2 = "q" ss.I3 = "q" ss.I4 = "q" ss.I5 = "q" ss.I6 = "q" ss.I7 = "q" ' ss.I8 = "q" System.Console.WriteLine(ss) ' should fail1 else Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String) ss.I1 = "q" ss.I2 = "q" ss.I3 = "q" ss.I4 = "q" ss.I5 = "q" ss.I6 = "q" ' ss.I7 = "q" ss.I8 = "q" System.Console.WriteLine(ss) ' should fail2 end if End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(q, q, q, q, q, q, , q)]]>) verifier.VerifyDiagnostics( Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss").WithArguments("ss").WithLocation(43, 38), Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss").WithArguments("ss").WithLocation(64, 38) ) End Sub <Fact> Public Sub DefiniteAssignment013() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String) ss.I1 = "q" ss.I2 = "q" ss.I3 = "q" ss.I4 = "q" ss.I5 = "q" ss.I6 = "q" ss.I7 = "q" ss.Item1 = "q" ss.Item2 = "q" ss.Item3 = "q" ss.Item4 = "q" ss.Item5 = "q" ss.Item6 = "q" ss.Item7 = "q" System.Console.WriteLine(ss.Rest) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[()]]>) verifier.VerifyDiagnostics( Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "ss.Rest").WithArguments("Rest").WithLocation(28, 38) ) End Sub <Fact> Public Sub DefiniteAssignment014() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim ss as (I1 as string, I2 As String, I3 As String, I4 As String, I5 As String, I6 As String, I7 As String, I8 As String) ss.I1 = "q" ss.Item2 = "aa" System.Console.WriteLine(ss.Item1) System.Console.WriteLine(ss.I2) System.Console.WriteLine(ss.I3) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[q aa]]>) verifier.VerifyDiagnostics( Diagnostic(ERRID.WRN_DefAsgUseNullRef, "ss.I3").WithArguments("I3").WithLocation(18, 38) ) End Sub <Fact> Public Sub DefiniteAssignment015() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Threading.Tasks Module Module1 Sub Main() Dim v = Test().Result end sub async Function Test() as Task(of long) Dim v1 as (a as Integer, b as Integer) Dim v2 as (x as Byte, y as Integer) v1.a = 5 v2.x = 5 ' no need to persist across await since it is unused after it. System.Console.WriteLine(v2.Item1) await Task.Yield() ' this is assigned and persisted across await return v1.Item1 end Function End Module </file> </compilation>, useLatestFramework:=True, references:=s_valueTupleRefs, expectedOutput:="5") ' NOTE: !!! There should be NO IL local for " v1 as (Long, Integer)" , it should be captured instead ' NOTE: !!! There should be an IL local for " v2 as (Byte, Integer)" , it should not be captured verifier.VerifyIL("Module1.VB$StateMachine_1_Test.MoveNext()", <![CDATA[ { // Code size 214 (0xd6) .maxstack 3 .locals init (Long V_0, Integer V_1, System.ValueTuple(Of Byte, Integer) V_2, //v2 System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_3, System.Runtime.CompilerServices.YieldAwaitable V_4, System.Exception V_5) IL_0000: ldarg.0 IL_0001: ldfld "Module1.VB$StateMachine_1_Test.$State As Integer" IL_0006: stloc.1 .try { IL_0007: ldloc.1 IL_0008: brfalse.s IL_0061 IL_000a: ldarg.0 IL_000b: ldflda "Module1.VB$StateMachine_1_Test.$VB$ResumableLocal_v1$0 As (a As Integer, b As Integer)" IL_0010: ldc.i4.5 IL_0011: stfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0016: ldloca.s V_2 IL_0018: ldc.i4.5 IL_0019: stfld "System.ValueTuple(Of Byte, Integer).Item1 As Byte" IL_001e: ldloc.2 IL_001f: ldfld "System.ValueTuple(Of Byte, Integer).Item1 As Byte" IL_0024: call "Sub System.Console.WriteLine(Integer)" IL_0029: call "Function System.Threading.Tasks.Task.Yield() As System.Runtime.CompilerServices.YieldAwaitable" IL_002e: stloc.s V_4 IL_0030: ldloca.s V_4 IL_0032: call "Function System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter() As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0037: stloc.3 IL_0038: ldloca.s V_3 IL_003a: call "Function System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.get_IsCompleted() As Boolean" IL_003f: brtrue.s IL_007d IL_0041: ldarg.0 IL_0042: ldc.i4.0 IL_0043: dup IL_0044: stloc.1 IL_0045: stfld "Module1.VB$StateMachine_1_Test.$State As Integer" IL_004a: ldarg.0 IL_004b: ldloc.3 IL_004c: stfld "Module1.VB$StateMachine_1_Test.$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0051: ldarg.0 IL_0052: ldflda "Module1.VB$StateMachine_1_Test.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Long)" IL_0057: ldloca.s V_3 IL_0059: ldarg.0 IL_005a: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Long).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Module1.VB$StateMachine_1_Test)(ByRef System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ByRef Module1.VB$StateMachine_1_Test)" IL_005f: leave.s IL_00d5 IL_0061: ldarg.0 IL_0062: ldc.i4.m1 IL_0063: dup IL_0064: stloc.1 IL_0065: stfld "Module1.VB$StateMachine_1_Test.$State As Integer" IL_006a: ldarg.0 IL_006b: ldfld "Module1.VB$StateMachine_1_Test.$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0070: stloc.3 IL_0071: ldarg.0 IL_0072: ldflda "Module1.VB$StateMachine_1_Test.$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_0077: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_007d: ldloca.s V_3 IL_007f: call "Sub System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()" IL_0084: ldloca.s V_3 IL_0086: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter" IL_008c: ldarg.0 IL_008d: ldflda "Module1.VB$StateMachine_1_Test.$VB$ResumableLocal_v1$0 As (a As Integer, b As Integer)" IL_0092: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0097: conv.i8 IL_0098: stloc.0 IL_0099: leave.s IL_00bf } catch System.Exception { IL_009b: dup IL_009c: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)" IL_00a1: stloc.s V_5 IL_00a3: ldarg.0 IL_00a4: ldc.i4.s -2 IL_00a6: stfld "Module1.VB$StateMachine_1_Test.$State As Integer" IL_00ab: ldarg.0 IL_00ac: ldflda "Module1.VB$StateMachine_1_Test.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Long)" IL_00b1: ldloc.s V_5 IL_00b3: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Long).SetException(System.Exception)" IL_00b8: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()" IL_00bd: leave.s IL_00d5 } IL_00bf: ldarg.0 IL_00c0: ldc.i4.s -2 IL_00c2: dup IL_00c3: stloc.1 IL_00c4: stfld "Module1.VB$StateMachine_1_Test.$State As Integer" IL_00c9: ldarg.0 IL_00ca: ldflda "Module1.VB$StateMachine_1_Test.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Long)" IL_00cf: ldloc.0 IL_00d0: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Long).SetResult(Long)" IL_00d5: ret } ]]>) End Sub <Fact> <WorkItem(13661, "https://github.com/dotnet/roslyn/issues/13661")> Public Sub LongTupleWithPartialNames_Bug13661() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Module C Sub Main() Dim t = (A:=1, 2, C:=3, D:=4, E:=5, F:=6, G:=7, 8, I:=9) System.Console.Write($"{t.I}") End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, options:=TestOptions.DebugExe, expectedOutput:="9", sourceSymbolValidator:= Sub(m As ModuleSymbol) Dim compilation = m.DeclaringCompilation Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim t = nodes.OfType(Of VariableDeclaratorSyntax)().Single().Names(0) Dim xSymbol = DirectCast(model.GetDeclaredSymbol(t), LocalSymbol).Type AssertEx.SetEqual(xSymbol.GetMembers().OfType(Of FieldSymbol)().Select(Function(f) f.Name), "A", "C", "D", "E", "F", "G", "I", "Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9", "Rest") End Sub) ' No assert hit End Sub <Fact> Public Sub UnifyUnderlyingWithTuple_08() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Module Module1 Sub Main() Dim x = (1, 3) Dim s As String = x System.Console.WriteLine(s) System.Console.WriteLine(CType(x, Long)) Dim y As (Integer, String) = New KeyValuePair(Of Integer, String)(2, "4") System.Console.WriteLine(y) System.Console.WriteLine(CType("5", ValueTuple(Of String, String))) System.Console.WriteLine(+x) System.Console.WriteLine(-x) System.Console.WriteLine(Not x) System.Console.WriteLine(If(x, True, False)) System.Console.WriteLine(If(Not x, True, False)) System.Console.WriteLine(x + 1) System.Console.WriteLine(x - 1) System.Console.WriteLine(x * 3) System.Console.WriteLine(x / 2) System.Console.WriteLine(x \ 2) System.Console.WriteLine(x Mod 3) System.Console.WriteLine(x & 3) System.Console.WriteLine(x And 3) System.Console.WriteLine(x Or 15) System.Console.WriteLine(x Xor 3) System.Console.WriteLine(x Like 15) System.Console.WriteLine(x ^ 4) System.Console.WriteLine(x << 1) System.Console.WriteLine(x >> 1) System.Console.WriteLine(x = 1) System.Console.WriteLine(x <> 1) System.Console.WriteLine(x > 1) System.Console.WriteLine(x < 1) System.Console.WriteLine(x >= 1) System.Console.WriteLine(x <= 1) End Sub End Module ]]></file> </compilation> Dim tuple = <compilation> <file name="a.vb"><![CDATA[ Namespace System Public Structure ValueTuple(Of T1, T2) Public Item1 As T1 Public Item2 As T2 Public Sub New(item1 As T1, item2 As T2) Me.Item1 = item1 Me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}" End Function Public Shared Widening Operator CType(arg As ValueTuple(Of T1, T2)) As String Return arg.ToString() End Operator Public Shared Narrowing Operator CType(arg As ValueTuple(Of T1, T2)) As Long Return CLng(CObj(arg.Item1) + CObj(arg.Item2)) End Operator Public Shared Widening Operator CType(arg As System.Collections.Generic.KeyValuePair(Of T1, T2)) As ValueTuple(Of T1, T2) Return New ValueTuple(Of T1, T2)(arg.Key, arg.Value) End Operator Public Shared Narrowing Operator CType(arg As String) As ValueTuple(Of T1, T2) Return New ValueTuple(Of T1, T2)(CType(CObj(arg), T1), CType(CObj(arg), T2)) End Operator Public Shared Operator +(arg As ValueTuple(Of T1, T2)) As ValueTuple(Of T1, T2) Return arg End Operator Public Shared Operator -(arg As ValueTuple(Of T1, T2)) As Long Return -CType(arg, Long) End Operator Public Shared Operator Not(arg As ValueTuple(Of T1, T2)) As Boolean Return CType(arg, Long) = 0 End Operator Public Shared Operator IsTrue(arg As ValueTuple(Of T1, T2)) As Boolean Return CType(arg, Long) <> 0 End Operator Public Shared Operator IsFalse(arg As ValueTuple(Of T1, T2)) As Boolean Return CType(arg, Long) = 0 End Operator Public Shared Operator +(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long Return CType(arg1, Long) + arg2 End Operator Public Shared Operator -(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long Return CType(arg1, Long) - arg2 End Operator Public Shared Operator *(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long Return CType(arg1, Long) * arg2 End Operator Public Shared Operator /(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long Return CType(arg1, Long) / arg2 End Operator Public Shared Operator \(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long Return CType(arg1, Long) \ arg2 End Operator Public Shared Operator Mod(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long Return CType(arg1, Long) Mod arg2 End Operator Public Shared Operator &(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long Return CType(arg1, Long) & arg2 End Operator Public Shared Operator And(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long Return CType(arg1, Long) And arg2 End Operator Public Shared Operator Or(arg1 As ValueTuple(Of T1, T2), arg2 As Long) As Long Return CType(arg1, Long) Or arg2 End Operator Public Shared Operator Xor(arg1 As ValueTuple(Of T1, T2), arg2 As Long) As Long Return CType(arg1, Long) Xor arg2 End Operator Public Shared Operator Like(arg1 As ValueTuple(Of T1, T2), arg2 As Long) As Long Return CType(arg1, Long) Or arg2 End Operator Public Shared Operator ^(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long Return CType(arg1, Long) ^ arg2 End Operator Public Shared Operator <<(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long Return CType(arg1, Long) << arg2 End Operator Public Shared Operator >>(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Long Return CType(arg1, Long) >> arg2 End Operator Public Shared Operator =(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Boolean Return CType(arg1, Long) = arg2 End Operator Public Shared Operator <>(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Boolean Return CType(arg1, Long) <> arg2 End Operator Public Shared Operator >(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Boolean Return CType(arg1, Long) > arg2 End Operator Public Shared Operator <(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Boolean Return CType(arg1, Long) < arg2 End Operator Public Shared Operator >=(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Boolean Return CType(arg1, Long) >= arg2 End Operator Public Shared Operator <=(arg1 As ValueTuple(Of T1, T2), arg2 As Integer) As Boolean Return CType(arg1, Long) <= arg2 End Operator Public Overrides Function Equals(obj As Object) As Boolean Return False End Function Public Overrides Function GetHashCode() As Integer Return 0 End Function End Structure End Namespace ]]></file> </compilation> Dim expectedOutput = "{1, 3} 4 {2, 4} {5, 5} {1, 3} -4 False True False 5 3 12 2 2 1 43 0 15 7 15 256 8 2 False True True False True False " Dim [lib] = CreateCompilationWithMscorlib40AndVBRuntime(tuple, options:=TestOptions.ReleaseDll) [lib].VerifyEmitDiagnostics() Dim consumer1 = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.ReleaseExe, additionalRefs:={[lib].ToMetadataReference()}) CompileAndVerify(consumer1, expectedOutput:=expectedOutput).VerifyDiagnostics() Dim consumer2 = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.ReleaseExe, additionalRefs:={[lib].EmitToImageReference()}) CompileAndVerify(consumer2, expectedOutput:=expectedOutput).VerifyDiagnostics() End Sub <Fact> Public Sub UnifyUnderlyingWithTuple_12() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Module Module1 Sub Main() Dim x? = (1, 3) Dim s As String = x System.Console.WriteLine(s) System.Console.WriteLine(CType(x, Long)) Dim y As (Integer, String)? = New KeyValuePair(Of Integer, String)(2, "4") System.Console.WriteLine(y) System.Console.WriteLine(CType("5", ValueTuple(Of String, String))) System.Console.WriteLine(+x) System.Console.WriteLine(-x) System.Console.WriteLine(Not x) System.Console.WriteLine(If(x, True, False)) System.Console.WriteLine(If(Not x, True, False)) System.Console.WriteLine(x + 1) System.Console.WriteLine(x - 1) System.Console.WriteLine(x * 3) System.Console.WriteLine(x / 2) System.Console.WriteLine(x \ 2) System.Console.WriteLine(x Mod 3) System.Console.WriteLine(x & 3) System.Console.WriteLine(x And 3) System.Console.WriteLine(x Or 15) System.Console.WriteLine(x Xor 3) System.Console.WriteLine(x Like 15) System.Console.WriteLine(x ^ 4) System.Console.WriteLine(x << 1) System.Console.WriteLine(x >> 1) System.Console.WriteLine(x = 1) System.Console.WriteLine(x <> 1) System.Console.WriteLine(x > 1) System.Console.WriteLine(x < 1) System.Console.WriteLine(x >= 1) System.Console.WriteLine(x <= 1) End Sub End Module ]]></file> </compilation> Dim tuple = <compilation> <file name="a.vb"><![CDATA[ Namespace System Public Structure ValueTuple(Of T1, T2) Public Item1 As T1 Public Item2 As T2 Public Sub New(item1 As T1, item2 As T2) Me.Item1 = item1 Me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}" End Function Public Shared Widening Operator CType(arg As ValueTuple(Of T1, T2)?) As String Return arg.ToString() End Operator Public Shared Narrowing Operator CType(arg As ValueTuple(Of T1, T2)?) As Long Return CLng(CObj(arg.Value.Item1) + CObj(arg.Value.Item2)) End Operator Public Shared Widening Operator CType(arg As System.Collections.Generic.KeyValuePair(Of T1, T2)) As ValueTuple(Of T1, T2)? Return New ValueTuple(Of T1, T2)(arg.Key, arg.Value) End Operator Public Shared Narrowing Operator CType(arg As String) As ValueTuple(Of T1, T2)? Return New ValueTuple(Of T1, T2)(CType(CObj(arg), T1), CType(CObj(arg), T2)) End Operator Public Shared Operator +(arg As ValueTuple(Of T1, T2)?) As ValueTuple(Of T1, T2)? Return arg End Operator Public Shared Operator -(arg As ValueTuple(Of T1, T2)?) As Long Return -CType(arg, Long) End Operator Public Shared Operator Not(arg As ValueTuple(Of T1, T2)?) As Boolean Return CType(arg, Long) = 0 End Operator Public Shared Operator IsTrue(arg As ValueTuple(Of T1, T2)?) As Boolean Return CType(arg, Long) <> 0 End Operator Public Shared Operator IsFalse(arg As ValueTuple(Of T1, T2)?) As Boolean Return CType(arg, Long) = 0 End Operator Public Shared Operator +(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long Return CType(arg1, Long) + arg2 End Operator Public Shared Operator -(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long Return CType(arg1, Long) - arg2 End Operator Public Shared Operator *(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long Return CType(arg1, Long) * arg2 End Operator Public Shared Operator /(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long Return CType(arg1, Long) / arg2 End Operator Public Shared Operator \(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long Return CType(arg1, Long) \ arg2 End Operator Public Shared Operator Mod(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long Return CType(arg1, Long) Mod arg2 End Operator Public Shared Operator &(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long Return CType(arg1, Long) & arg2 End Operator Public Shared Operator And(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long Return CType(arg1, Long) And arg2 End Operator Public Shared Operator Or(arg1 As ValueTuple(Of T1, T2)?, arg2 As Long) As Long Return CType(arg1, Long) Or arg2 End Operator Public Shared Operator Xor(arg1 As ValueTuple(Of T1, T2)?, arg2 As Long) As Long Return CType(arg1, Long) Xor arg2 End Operator Public Shared Operator Like(arg1 As ValueTuple(Of T1, T2)?, arg2 As Long) As Long Return CType(arg1, Long) Or arg2 End Operator Public Shared Operator ^(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long Return CType(arg1, Long) ^ arg2 End Operator Public Shared Operator <<(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long Return CType(arg1, Long) << arg2 End Operator Public Shared Operator >>(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Long Return CType(arg1, Long) >> arg2 End Operator Public Shared Operator =(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Boolean Return CType(arg1, Long) = arg2 End Operator Public Shared Operator <>(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Boolean Return CType(arg1, Long) <> arg2 End Operator Public Shared Operator >(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Boolean Return CType(arg1, Long) > arg2 End Operator Public Shared Operator <(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Boolean Return CType(arg1, Long) < arg2 End Operator Public Shared Operator >=(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Boolean Return CType(arg1, Long) >= arg2 End Operator Public Shared Operator <=(arg1 As ValueTuple(Of T1, T2)?, arg2 As Integer) As Boolean Return CType(arg1, Long) <= arg2 End Operator Public Overrides Function Equals(obj As Object) As Boolean Return False End Function Public Overrides Function GetHashCode() As Integer Return 0 End Function End Structure End Namespace ]]></file> </compilation> Dim expectedOutput = "{1, 3} 4 {2, 4} {5, 5} {1, 3} -4 False True False 5 3 12 2 2 1 43 0 15 7 15 256 8 2 False True True False True False " Dim [lib] = CreateCompilationWithMscorlib40AndVBRuntime(tuple, options:=TestOptions.ReleaseDll) [lib].VerifyEmitDiagnostics() Dim consumer1 = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.ReleaseExe, additionalRefs:={[lib].ToMetadataReference()}) CompileAndVerify(consumer1, expectedOutput:=expectedOutput).VerifyDiagnostics() Dim consumer2 = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.ReleaseExe, additionalRefs:={[lib].EmitToImageReference()}) CompileAndVerify(consumer2, expectedOutput:=expectedOutput).VerifyDiagnostics() End Sub <Fact> Public Sub TupleConversion01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module C Sub Main() Dim x1 As (a As Integer, b As Integer) = DirectCast((e:=1, f:=2), (c As Long, d As Long)) Dim x2 As (a As Short, b As Short) = DirectCast((e:=1, f:=2), (c As Integer, d As Integer)) Dim x3 As (a As Integer, b As Integer) = DirectCast((e:=1, f:="qq"), (c As Long, d As Long)) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC41009: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'. Dim x1 As (a As Integer, b As Integer) = DirectCast((e:=1, f:=2), (c As Long, d As Long)) ~~~~ BC41009: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'. Dim x1 As (a As Integer, b As Integer) = DirectCast((e:=1, f:=2), (c As Long, d As Long)) ~~~~ BC41009: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(c As Integer, d As Integer)'. Dim x2 As (a As Short, b As Short) = DirectCast((e:=1, f:=2), (c As Integer, d As Integer)) ~~~~ BC41009: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(c As Integer, d As Integer)'. Dim x2 As (a As Short, b As Short) = DirectCast((e:=1, f:=2), (c As Integer, d As Integer)) ~~~~ BC41009: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'. Dim x3 As (a As Integer, b As Integer) = DirectCast((e:=1, f:="qq"), (c As Long, d As Long)) ~~~~ BC41009: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'. Dim x3 As (a As Integer, b As Integer) = DirectCast((e:=1, f:="qq"), (c As Long, d As Long)) ~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleConversion01_StrictOn() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Module C Sub Main() Dim x1 As (a As Integer, b As Integer) = DirectCast((e:=1, f:=2), (c As Long, d As Long)) Dim x2 As (a As Short, b As Short) = DirectCast((e:=1, f:=2), (c As Integer, d As Integer)) Dim x3 As (a As Integer, b As Integer) = DirectCast((e:=1, f:="qq"), (c As Long, d As Long)) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30512: Option Strict On disallows implicit conversions from '(c As Long, d As Long)' to '(a As Integer, b As Integer)'. Dim x1 As (a As Integer, b As Integer) = DirectCast((e:=1, f:=2), (c As Long, d As Long)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC41009: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'. Dim x1 As (a As Integer, b As Integer) = DirectCast((e:=1, f:=2), (c As Long, d As Long)) ~~~~ BC41009: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'. Dim x1 As (a As Integer, b As Integer) = DirectCast((e:=1, f:=2), (c As Long, d As Long)) ~~~~ BC30512: Option Strict On disallows implicit conversions from '(c As Integer, d As Integer)' to '(a As Short, b As Short)'. Dim x2 As (a As Short, b As Short) = DirectCast((e:=1, f:=2), (c As Integer, d As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC41009: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(c As Integer, d As Integer)'. Dim x2 As (a As Short, b As Short) = DirectCast((e:=1, f:=2), (c As Integer, d As Integer)) ~~~~ BC41009: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(c As Integer, d As Integer)'. Dim x2 As (a As Short, b As Short) = DirectCast((e:=1, f:=2), (c As Integer, d As Integer)) ~~~~ BC30512: Option Strict On disallows implicit conversions from '(c As Long, d As Long)' to '(a As Integer, b As Integer)'. Dim x3 As (a As Integer, b As Integer) = DirectCast((e:=1, f:="qq"), (c As Long, d As Long)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC41009: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'. Dim x3 As (a As Integer, b As Integer) = DirectCast((e:=1, f:="qq"), (c As Long, d As Long)) ~~~~ BC41009: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(c As Long, d As Long)'. Dim x3 As (a As Integer, b As Integer) = DirectCast((e:=1, f:="qq"), (c As Long, d As Long)) ~~~~~~~ </errors>) End Sub <Fact> <WorkItem(11288, "https://github.com/dotnet/roslyn/issues/11288")> Public Sub TupleConversion02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x4 As (a As Integer, b As Integer) = DirectCast((1, Nothing, 2), (c As Long, d As Long)) End Sub End Module <%= s_trivial2uple %><%= s_trivial3uple %> </file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC30311: Value of type '(Integer, Object, Integer)' cannot be converted to '(c As Long, d As Long)'. Dim x4 As (a As Integer, b As Integer) = DirectCast((1, Nothing, 2), (c As Long, d As Long)) ~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleConvertedType01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Short, b As String)? = (e:=1, f:="hello") End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Dim typeInfo As TypeInfo = model.GetTypeInfo(node) Assert.Equal("(e As System.Int32, f As System.String)", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (a As System.Int16, b As System.String))", typeInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Dim e = node.Arguments(0).Expression Assert.Equal("1", e.ToString()) typeInfo = model.GetTypeInfo(e) Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.Int16", typeInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(e).Kind) Dim f = node.Arguments(1).Expression Assert.Equal("""hello""", f.ToString()) typeInfo = model.GetTypeInfo(f) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.String", typeInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(f).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As System.Nullable(Of (a As System.Int16, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType01_StrictOn() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Module C Sub Main() Dim x As (a As Short, b As String)? = (e:=1, f:="hello") End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (a As System.Int16, b As System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As System.Nullable(Of (a As System.Int16, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType01insource() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Short, b As String)? = DirectCast((e:=1, f:="hello"), (c As Short, d As String)?) Dim y As Short? = DirectCast(11, Short?) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim l11 = nodes.OfType(Of LiteralExpressionSyntax)().ElementAt(2) Assert.Equal("11", l11.ToString()) Assert.Equal("System.Int32", model.GetTypeInfo(l11).Type.ToTestDisplayString()) Assert.Equal("System.Int32", model.GetTypeInfo(l11).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(l11).Kind) Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (c As System.Int16, d As System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Assert.Equal("System.Nullable(Of (c As System.Int16, d As System.String))", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (c As System.Int16, d As System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As System.Nullable(Of (a As System.Int16, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType01insourceImplicit() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Short, b As String)? = (1, "hello") End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(1, ""hello"")", node.ToString()) Dim typeInfo As TypeInfo = model.GetTypeInfo(node) Assert.Equal("(System.Int32, System.String)", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (a As System.Int16, b As System.String))", typeInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) CompileAndVerify(comp) End Sub <Fact> Public Sub TupleConvertedType02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Short, b As String)? = (e:=1, f:="hello") End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Dim typeInfo As TypeInfo = model.GetTypeInfo(node) Assert.Equal("(e As System.Int32, f As System.String)", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (a As System.Int16, b As System.String))", typeInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Dim e = node.Arguments(0).Expression Assert.Equal("1", e.ToString()) typeInfo = model.GetTypeInfo(e) Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.Int16", typeInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(e).Kind) Dim f = node.Arguments(1).Expression Assert.Equal("""hello""", f.ToString()) typeInfo = model.GetTypeInfo(f) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.String", typeInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(f).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As System.Nullable(Of (a As System.Int16, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType02insource00() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Short, b As String)? = DirectCast((e:=1, f:="hello"), (c As Short, d As String)) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Assert.Equal("DirectCast((e:=1, f:=""hello""), (c As Short, d As String))", node.Parent.ToString()) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (a As System.Int16, b As System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As System.Nullable(Of (a As System.Int16, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType02insource00_StrictOn() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Module C Sub Main() Dim x As (a As Short, b As String)? = DirectCast((e:=1, f:="hello"), (c As Short, d As String)) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (a As System.Int16, b As System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As System.Nullable(Of (a As System.Int16, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType02insource01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x = (e:=1, f:="hello") Dim x1 As (a As Object, b As String) = DirectCast((x), (c As Long, d As String)) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of ParenthesizedExpressionSyntax)().Single().Parent Assert.Equal("DirectCast((x), (c As Long, d As String))", node.ToString()) Assert.Equal("(c As System.Int64, d As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(a As System.Object, b As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of ParenthesizedExpressionSyntax)().Single() Assert.Equal("(x)", x.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(x).Type.ToTestDisplayString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(x).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(x).Kind) End Sub <Fact> Public Sub TupleConvertedType02insource01_StrictOn() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Module C Sub Main() Dim x = (e:=1, f:="hello") Dim x1 As (a As Object, b As String) = DirectCast((x), (c As Long, d As String)) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of ParenthesizedExpressionSyntax)().Single().Parent Assert.Equal("DirectCast((x), (c As Long, d As String))", node.ToString()) Assert.Equal("(c As System.Int64, d As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(a As System.Object, b As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of ParenthesizedExpressionSyntax)().Single() Assert.Equal("(x)", x.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(x).Type.ToTestDisplayString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(x).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(x).Kind) End Sub <Fact> Public Sub TupleConvertedType02insource02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x = (e:=1, f:="hello") Dim x1 As (a As Object, b As String)? = DirectCast((x), (c As Long, d As String)) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of ParenthesizedExpressionSyntax)().Single().Parent Assert.Equal("DirectCast((x), (c As Long, d As String))", node.ToString()) Assert.Equal("(c As System.Int64, d As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (a As System.Object, b As System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of ParenthesizedExpressionSyntax)().Single() Assert.Equal("(x)", x.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(x).Type.ToTestDisplayString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(x).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(x).Kind) End Sub <Fact> Public Sub TupleConvertedType03() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Integer, b As String)? = (e:=1, f:="hello") End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (a As System.Int32, b As System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As System.Nullable(Of (a As System.Int32, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType03insource() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Integer, b As String)? = DirectCast((e:=1, f:="hello"), (c As Integer, d As String)?) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (c As System.Int32, d As System.String))", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(node).Kind) Assert.Equal("DirectCast((e:=1, f:=""hello""), (c As Integer, d As String)?)", node.Parent.ToString()) Assert.Equal("System.Nullable(Of (c As System.Int32, d As System.String))", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (c As System.Int32, d As System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(node.Parent).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As System.Nullable(Of (a As System.Int32, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType04() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Integer, b As String)? = DirectCast((e:=1, f:="hello"), (c As Integer, d As String)) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(c As System.Int32, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(node).Kind) Assert.Equal("(c As System.Int32, d As System.String)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("System.Nullable(Of (a As System.Int32, b As System.String))", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNullable, model.GetConversion(node.Parent).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As System.Nullable(Of (a As System.Int32, b As System.String))", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType05() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Integer, b As String) = (e:=1, f:="hello") End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(a As System.Int32, b As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As (a As System.Int32, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType05insource() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Integer, b As String) = DirectCast((e:=1, f:="hello"), (c As Integer, d As String)) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(c As System.Int32, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As (a As System.Int32, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType05insource_StrictOn() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Module C Sub Main() Dim x As (a As Integer, b As String) = DirectCast((e:=1, f:="hello"), (c As Integer, d As String)) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(c As System.Int32, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As (a As System.Int32, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType06() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Short, b As String) = (e:=1, f:="hello") End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(a As System.Int16, b As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Dim e = node.Arguments(0).Expression Assert.Equal("1", e.ToString()) Dim typeInfo = model.GetTypeInfo(e) Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.Int16", typeInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(e).Kind) Dim f = node.Arguments(1).Expression Assert.Equal("""hello""", f.ToString()) typeInfo = model.GetTypeInfo(f) Assert.Equal("System.String", typeInfo.Type.ToTestDisplayString()) Assert.Equal("System.String", typeInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(f).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As (a As System.Int16, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedType06insource() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Short, b As String) = DirectCast((e:=1, f:="hello"), (c As Short, d As String)) Dim y As Short = DirectCast(11, short) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim l11 = nodes.OfType(Of LiteralExpressionSyntax)().ElementAt(2) Assert.Equal("11", l11.ToString()) Assert.Equal("System.Int32", model.GetTypeInfo(l11).Type.ToTestDisplayString()) Assert.Equal("System.Int32", model.GetTypeInfo(l11).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(l11).Kind) Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=""hello"")", node.ToString()) Assert.Equal("(e As System.Int32, f As System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(node.Parent).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As (a As System.Int16, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedTypeNull01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Short, b As String) = (e:=1, f:=Nothing) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Assert.Equal("(a As System.Int16, b As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As (a As System.Int16, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedTypeNull01insource() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module C Sub Main() Dim x As (a As Short, b As String) = DirectCast((e:=1, f:=Nothing), (c As Short, d As String)) Dim y As String = DirectCast(Nothing, String) End Sub End Module <%= s_trivial2uple %> </file> </compilation>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim lnothing = nodes.OfType(Of LiteralExpressionSyntax)().ElementAt(2) Assert.Equal("Nothing", lnothing.ToString()) Assert.Null(model.GetTypeInfo(lnothing).Type) Assert.Equal("System.Object", model.GetTypeInfo(lnothing).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningNothingLiteral, model.GetConversion(lnothing).Kind) Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.InvolvesNarrowingFromNumericConstant, model.GetConversion(node).Kind) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(node.Parent).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As (a As System.Int16, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString()) End Sub <Fact> Public Sub TupleConvertedTypeUDC01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x As (a As Short, b As String) = (e:=1, f:=New C1("qq")) System.Console.Write(x.ToString()) End Sub Class C1 Public Dim s As String Public Sub New(ByVal arg As String) s = arg + "1" End Sub Public Shared Narrowing Operator CType(ByVal arg As C1) As String Return arg.s End Operator End Class End Class <%= s_trivial2uple %> </file> </compilation>, options:=TestOptions.DebugExe) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=New C1(""qq""))", node.ToString()) Assert.Equal("(e As System.Int32, f As C.C1)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(a As System.Int16, b As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.NarrowingTuple, model.GetConversion(node).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As (a As System.Int16, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString()) CompileAndVerify(comp, expectedOutput:="{1, qq1}") End Sub <Fact> Public Sub TupleConvertedTypeUDC01_StrictOn() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Class C Shared Sub Main() Dim x As (a As Short, b As String) = (e:=1, f:=New C1("qq")) System.Console.Write(x.ToString()) End Sub Class C1 Public Dim s As String Public Sub New(ByVal arg As String) s = arg + "1" End Sub Public Shared Narrowing Operator CType(ByVal arg As C1) As String Return arg.s End Operator End Class End Class <%= s_trivial2uple %> </file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC41009: The tuple element name 'e' is ignored because a different name or no name is specified by the target type '(a As Short, b As String)'. Dim x As (a As Short, b As String) = (e:=1, f:=New C1("qq")) ~~~~ BC41009: The tuple element name 'f' is ignored because a different name or no name is specified by the target type '(a As Short, b As String)'. Dim x As (a As Short, b As String) = (e:=1, f:=New C1("qq")) ~~~~~~~~~~~~~~~ BC30512: Option Strict On disallows implicit conversions from 'C.C1' to 'String'. Dim x As (a As Short, b As String) = (e:=1, f:=New C1("qq")) ~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleConvertedTypeUDC01insource() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x As (a As Short, b As String) = DirectCast((e:=1, f:=New C1("qq")), (c As Short, d As String)) System.Console.Write(x.ToString()) End Sub Class C1 Public Dim s As String Public Sub New(ByVal arg As String) s = arg + "1" End Sub Public Shared Narrowing Operator CType(ByVal arg As C1) As String Return arg.s End Operator End Class End Class <%= s_trivial2uple %> </file> </compilation>, options:=TestOptions.DebugExe) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e:=1, f:=New C1(""qq""))", node.ToString()) Assert.Equal("(e As System.Int32, f As C.C1)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.NarrowingTuple, model.GetConversion(node).Kind) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).Type.ToTestDisplayString()) Assert.Equal("(c As System.Int16, d As System.String)", model.GetTypeInfo(node.Parent).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Identity, model.GetConversion(node.Parent).Kind) Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x As (a As System.Int16, b As System.String)", model.GetDeclaredSymbol(x).ToTestDisplayString()) CompileAndVerify(comp, expectedOutput:="{1, qq1}") End Sub <Fact> <WorkItem(11289, "https://github.com/dotnet/roslyn/issues/11289")> Public Sub TupleConvertedTypeUDC02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x As C1 = (1, "qq") System.Console.Write(x.ToString()) End Sub Class C1 Public Dim val As (Byte, String) Public Sub New(ByVal arg As (Byte, String)) val = arg End Sub Public Shared Narrowing Operator CType(ByVal arg As (Byte, String)) As C1 Return New C1(arg) End Operator Public Overrides Function ToString() As String Return val.ToString() End Function End Class End Class <%= s_trivial2uple %> </file> </compilation>, options:=TestOptions.DebugExe) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(1, ""qq"")", node.ToString()) Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("C.C1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Narrowing Or ConversionKind.UserDefined, model.GetConversion(node).Kind) CompileAndVerify(comp, expectedOutput:="{1, qq}") End Sub <Fact> Public Sub TupleConvertedTypeUDC03() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim x As C1 = ("1", "qq") System.Console.Write(x.ToString()) End Sub Class C1 Public Dim val As (Byte, String) Public Sub New(ByVal arg As (Byte, String)) val = arg End Sub Public Shared Narrowing Operator CType(ByVal arg As (Byte, String)) As C1 Return New C1(arg) End Operator Public Overrides Function ToString() As String Return val.ToString() End Function End Class End Class </file> </compilation>, options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> </errors>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(""1"", ""qq"")", node.ToString()) Assert.Equal("(System.String, System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("C.C1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Narrowing Or ConversionKind.UserDefined, model.GetConversion(node).Kind) CompileAndVerify(comp, expectedOutput:="(1, qq)") End Sub <Fact> Public Sub TupleConvertedTypeUDC03_StrictOn() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Class C Shared Sub Main() Dim x As C1 = ("1", "qq") System.Console.Write(x.ToString()) End Sub Class C1 Public Dim val As (Byte, String) Public Sub New(ByVal arg As (Byte, String)) val = arg End Sub Public Shared Narrowing Operator CType(ByVal arg As (Byte, String)) As C1 Return New C1(arg) End Operator Public Overrides Function ToString() As String Return val.ToString() End Function End Class End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30512: Option Strict On disallows implicit conversions from '(String, String)' to 'C.C1'. Dim x As C1 = ("1", "qq") ~~~~~~~~~~~ </errors>) Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(""1"", ""qq"")", node.ToString()) Assert.Equal("(System.String, System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("C.C1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Narrowing Or ConversionKind.UserDefined, model.GetConversion(node).Kind) End Sub <Fact> <WorkItem(11289, "https://github.com/dotnet/roslyn/issues/11289")> Public Sub TupleConvertedTypeUDC04() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Dim x As C1 = (1, "qq") System.Console.Write(x.ToString()) End Sub Public Class C1 Public Dim val As (Byte, String) Public Sub New(ByVal arg As (Byte, String)) val = arg End Sub Public Overrides Function ToString() As String Return val.ToString() End Function End Class End Class Namespace System Public Structure ValueTuple(Of T1, T2) Public Dim Item1 As T1 Public Dim Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}" End Function Public Shared Narrowing Operator CType(ByVal arg As (T1, T2)) As C.C1 Return New C.C1((CType(DirectCast(DirectCast(arg.Item1, Object), Integer), Byte), DirectCast(DirectCast(arg.Item2, Object), String))) End Operator End Structure End Namespace </file> </compilation>, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics() Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().First() Assert.Equal("(1, ""qq"")", node.ToString()) Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("C.C1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Narrowing Or ConversionKind.UserDefined, model.GetConversion(node).Kind) CompileAndVerify(comp, expectedOutput:="{1, qq}") End Sub <Fact> <WorkItem(11289, "https://github.com/dotnet/roslyn/issues/11289")> Public Sub TupleConvertedTypeUDC05() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Dim x As C1 = (1, "qq") System.Console.Write(x.ToString()) End Sub Public Class C1 Public Dim val As (Byte, String) Public Sub New(ByVal arg As (Byte, String)) val = arg End Sub Public Shared Narrowing Operator CType(ByVal arg As (Byte, String)) As C1 System.Console.Write("C1") Return New C1(arg) End Operator Public Overrides Function ToString() As String Return val.ToString() End Function End Class End Class Namespace System Public Structure ValueTuple(Of T1, T2) Public Dim Item1 As T1 Public Dim Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}" End Function Public Shared Narrowing Operator CType(ByVal arg As (T1, T2)) As C.C1 System.Console.Write("VT ") Return New C.C1((CType(DirectCast(DirectCast(arg.Item1, Object), Integer), Byte), DirectCast(DirectCast(arg.Item2, Object), String))) End Operator End Structure End Namespace </file> </compilation>, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics() Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().First() Assert.Equal("(1, ""qq"")", node.ToString()) Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("C.C1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Narrowing Or ConversionKind.UserDefined, model.GetConversion(node).Kind) CompileAndVerify(comp, expectedOutput:="VT {1, qq}") End Sub <Fact> <WorkItem(11289, "https://github.com/dotnet/roslyn/issues/11289")> Public Sub TupleConvertedTypeUDC06() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Dim x As C1 = (1, Nothing) System.Console.Write(x.ToString()) End Sub Public Class C1 Public Dim val As (Byte, String) Public Sub New(ByVal arg As (Byte, String)) val = arg End Sub Public Shared Narrowing Operator CType(ByVal arg As (Byte, String)) As C1 System.Console.Write("C1") Return New C1(arg) End Operator Public Overrides Function ToString() As String Return val.ToString() End Function End Class End Class Namespace System Public Structure ValueTuple(Of T1, T2) Public Dim Item1 As T1 Public Dim Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return "{" + Item1?.ToString() + ", " + Item2?.ToString() + "}" End Function Public Shared Narrowing Operator CType(ByVal arg As (T1, T2)) As C.C1 System.Console.Write("VT ") Return New C.C1((CType(DirectCast(DirectCast(arg.Item1, Object), Integer), Byte), DirectCast(DirectCast(arg.Item2, Object), String))) End Operator End Structure End Namespace </file> </compilation>, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics() Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().First() Assert.Equal("(1, Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Assert.Equal("C.C1", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.Narrowing Or ConversionKind.UserDefined, model.GetConversion(node).Kind) CompileAndVerify(comp, expectedOutput:="VT {1, }") End Sub <Fact> Public Sub TupleConvertedTypeUDC07_StrictOff_Narrowing() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Dim x As C1 = M1() System.Console.Write(x.ToString()) End Sub Shared Function M1() As (Integer, String) Return (1, "qq") End Function Public Class C1 Public Dim val As (Byte, String) Public Sub New(ByVal arg As (Byte, String)) val = arg End Sub Public Shared Narrowing Operator CType(ByVal arg As (Byte, String)) As C1 System.Console.Write("C1 ") Return New C1(arg) End Operator End Class End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics() Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() CompileAndVerify(comp, expectedOutput:="C1 C+C1") End Sub <Fact> Public Sub TupleConvertedTypeUDC07() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class C Shared Sub Main() Dim x As C1 = M1() System.Console.Write(x.ToString()) End Sub Shared Function M1() As (Integer, String) Return (1, "qq") End Function Public Class C1 Public Dim val As (Byte, String) Public Sub New(ByVal arg As (Byte, String)) val = arg End Sub Public Shared Widening Operator CType(ByVal arg As (Byte, String)) As C1 System.Console.Write("C1 ") Return New C1(arg) End Operator End Class End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30512: Option Strict On disallows implicit conversions from '(Integer, String)' to 'C.C1'. Dim x As C1 = M1() ~~~~ </errors>) End Sub <Fact> Public Sub Inference01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Test((Nothing, Nothing)) Test((1, 1)) Test((Function() 7, Function() 8), 2) End Sub Shared Sub Test(Of T)(x As (T, T)) System.Console.WriteLine("first") End Sub Shared Sub Test(x As (Object, Object)) System.Console.WriteLine("second") End Sub Shared Sub Test(Of T)(x As (System.Func(Of T), System.Func(Of T)), y As T) System.Console.WriteLine("third") System.Console.WriteLine(x.Item1().ToString()) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" second first third 7 ") End Sub <Fact> Public Sub Inference02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Test1((Function() 7, Function() 8)) Test2(Function() 7, Function() 8) Test3((Function() 7, Function() 8)) End Sub Shared Sub Test1(Of T)(x As (T, T)) System.Console.WriteLine("first") End Sub Shared Sub Test1(x As (Object, Object)) System.Console.WriteLine("second") End Sub Shared Sub Test1(Of T)(x As (System.Func(Of T), System.Func(Of T))) System.Console.WriteLine("third") End Sub Shared Sub Test2(Of T)(x As T, y As T) System.Console.WriteLine("first") End Sub Shared Sub Test2(x As Object, y As Object) System.Console.WriteLine("second") End Sub Shared Sub Test2(Of T)(x As System.Func(Of T), y As System.Func(Of T)) System.Console.WriteLine("third") End Sub Shared Sub Test3(Of T)(x As (T, T)?) System.Console.WriteLine("first") End Sub Shared Sub Test3(x As (Object, Object)?) System.Console.WriteLine("second") End Sub Shared Sub Test3(Of T)(x As (System.Func(Of T), System.Func(Of T))?) System.Console.WriteLine("third") End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" first first first") End Sub <Fact> Public Sub DelegateRelaxationLevel_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Test1((Function() 7, Function() 8)) Test2(Function() 7, Function() 8) Test3((Function() 7, Function() 8)) End Sub Shared Sub Test1(x As (System.Func(Of Integer), System.Func(Of Integer))) System.Console.WriteLine("second") End Sub Shared Sub Test1(x As (System.Func(Of Integer, Integer), System.Func(Of Integer, Integer))) System.Console.WriteLine("third") End Sub Shared Sub Test2(x As System.Func(Of Integer), y As System.Func(Of Integer)) System.Console.WriteLine("second") End Sub Shared Sub Test2(x As System.Func(Of Integer, Integer), y As System.Func(Of Integer, Integer)) System.Console.WriteLine("third") End Sub Shared Sub Test3(x As (System.Func(Of Integer), System.Func(Of Integer))?) System.Console.WriteLine("second") End Sub Shared Sub Test3(x As (System.Func(Of Integer, Integer), System.Func(Of Integer, Integer))?) System.Console.WriteLine("third") End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" second second second") End Sub <Fact> Public Sub DelegateRelaxationLevel_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Dim int = 1 Dim a = Function(x as Integer) x Test1(a, int) Test2((a, int)) Test3((a, int)) Dim b = (a, int) Test2(b) Test3(b) End Sub Shared Sub Test1(x As System.Action(Of Integer), y As Integer) System.Console.WriteLine("second") End Sub Shared Sub Test1(x As System.Func(Of Integer, Integer), y As Integer) System.Console.WriteLine("third") End Sub Shared Sub Test2(x As (System.Action(Of Integer), Integer)) System.Console.WriteLine("second") End Sub Shared Sub Test2(x As (System.Func(Of Integer, Integer), Integer)) System.Console.WriteLine("third") End Sub Shared Sub Test3(x As (System.Action(Of Integer), Integer)?) System.Console.WriteLine("second") End Sub Shared Sub Test3(x As (System.Func(Of Integer, Integer), Integer)?) System.Console.WriteLine("third") End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" third third third third third") End Sub <Fact> Public Sub DelegateRelaxationLevel_03() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Imports System Public Class C Shared Sub Main() Dim int as integer = 1 Dim x00 As (Integer, Func(Of Integer)) = (int, Function() int) Dim x01 As (Integer, Func(Of Long)) = (int, Function() int) Dim x02 As (Integer, Action) = (int, Function() int) Dim x03 As (Integer, Object) = (int, Function() int) Dim x04 As (Integer, Func(Of Short)) = (int, Function() int) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ToArray() AssertConversions(model, nodes(0), ConversionKind.WideningTuple, ConversionKind.Identity, ConversionKind.Widening Or ConversionKind.Lambda) AssertConversions(model, nodes(1), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWidening, ConversionKind.Identity, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWidening) AssertConversions(model, nodes(2), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs, ConversionKind.Identity, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs) AssertConversions(model, nodes(3), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda, ConversionKind.Identity, ConversionKind.WideningReference Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda) AssertConversions(model, nodes(4), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, ConversionKind.Identity, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelNarrowing) End Sub <Fact> Public Sub DelegateRelaxationLevel_04() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Imports System Public Class C Shared Sub Main() Dim int as integer = 1 Dim x00 As (Func(Of Integer), Integer) = (Function() int, int) Dim x01 As (Func(Of Long), Integer) = (Function() int, int) Dim x02 As (Action, Integer) = (Function() int, int) Dim x03 As (Object, Integer) = (Function() int, int) Dim x04 As (Func(Of Short), Integer) = (Function() int, int) Dim x05 As (Func(Of Short), Func(Of Long)) = (Function() int, Function() int) Dim x06 As (Func(Of Long), Func(Of Short)) = (Function() int, Function() int) Dim x07 As (Short, (Func(Of Long), Func(Of Short))) = (int, (Function() int, Function() int)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ToArray() AssertConversions(model, nodes(0), ConversionKind.WideningTuple, ConversionKind.Widening Or ConversionKind.Lambda, ConversionKind.Identity) AssertConversions(model, nodes(1), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWidening, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWidening, ConversionKind.Identity) AssertConversions(model, nodes(2), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs, ConversionKind.Identity) AssertConversions(model, nodes(3), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda, ConversionKind.WideningReference Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda, ConversionKind.Identity) AssertConversions(model, nodes(4), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelNarrowing, ConversionKind.Identity) AssertConversions(model, nodes(5), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelNarrowing, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWidening) AssertConversions(model, nodes(6), ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWidening, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelNarrowing) AssertConversions(model, nodes(7), ConversionKind.NarrowingTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, ConversionKind.NarrowingNumeric, ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelNarrowing) End Sub <Fact> Public Sub DelegateRelaxationLevel_05() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Imports System Public Class C Shared Sub Main() Dim int as integer = 1 Dim x00 As (Integer, Func(Of Integer))? = (int, Function() int) Dim x01 As (Short, Func(Of Long))? = (int, Function() int) Dim x02 As (Integer, Action)? = (int, Function() int) Dim x03 As (Integer, Object)? = (int, Function() int) Dim x04 As (Integer, Func(Of Short))? = (int, Function() int) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().ToArray() AssertConversions(model, nodes(0), ConversionKind.WideningNullableTuple, ConversionKind.Identity, ConversionKind.Widening Or ConversionKind.Lambda) AssertConversions(model, nodes(1), ConversionKind.NarrowingNullableTuple Or ConversionKind.DelegateRelaxationLevelWidening, ConversionKind.NarrowingNumeric, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWidening) AssertConversions(model, nodes(2), ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs, ConversionKind.Identity, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs) AssertConversions(model, nodes(3), ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda, ConversionKind.Identity, ConversionKind.WideningReference Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda) AssertConversions(model, nodes(4), ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, ConversionKind.Identity, ConversionKind.Widening Or ConversionKind.Lambda Or ConversionKind.DelegateRelaxationLevelNarrowing) End Sub <Fact> Public Sub DelegateRelaxationLevel_06() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Imports System Public Class C Shared Sub Main() Dim int as integer = 1 Dim t = (int, Function() int) Dim x00 As (Integer, Func(Of Integer)) = t Dim x01 As (Integer, Func(Of Long)) = t Dim x02 As (Integer, Action) = t Dim x03 As (Integer, Object) = t Dim x04 As (Integer, Func(Of Short)) = t End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(id) id.Identifier.ValueText = "t").ToArray() Assert.Equal(ConversionKind.WideningTuple, model.GetConversion(nodes(0)).Kind) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWidening, model.GetConversion(nodes(1)).Kind) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs, model.GetConversion(nodes(2)).Kind) Assert.Equal(ConversionKind.WideningTuple Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda, model.GetConversion(nodes(3)).Kind) Assert.Equal(ConversionKind.NarrowingTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, model.GetConversion(nodes(4)).Kind) End Sub <Fact> Public Sub DelegateRelaxationLevel_07() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Imports System Public Class C Shared Sub Main() Dim int as integer = 1 Dim t = (int, Function() int) Dim x00 As (Integer, Func(Of Integer))? = t Dim x01 As (Integer, Func(Of Long))? = t Dim x02 As (Integer, Action)? = t Dim x03 As (Integer, Object)? = t Dim x04 As (Integer, Func(Of Short))? = t End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(id) id.Identifier.ValueText = "t").ToArray() Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(nodes(0)).Kind) Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWidening, model.GetConversion(nodes(1)).Kind) Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs, model.GetConversion(nodes(2)).Kind) Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda, model.GetConversion(nodes(3)).Kind) Assert.Equal(ConversionKind.NarrowingNullableTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, model.GetConversion(nodes(4)).Kind) End Sub <Fact> Public Sub DelegateRelaxationLevel_08() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Imports System Public Class C Shared Sub Main() Dim int as integer = 1 Dim t? = (int, Function() int) Dim x00 As (Integer, Func(Of Integer))? = t Dim x01 As (Integer, Func(Of Long))? = t Dim x02 As (Integer, Action)? = t Dim x03 As (Integer, Object)? = t Dim x04 As (Integer, Func(Of Short))? = t End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(id) id.Identifier.ValueText = "t").ToArray() Assert.Equal(ConversionKind.WideningNullableTuple, model.GetConversion(nodes(0)).Kind) Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWidening, model.GetConversion(nodes(1)).Kind) Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs, model.GetConversion(nodes(2)).Kind) Assert.Equal(ConversionKind.WideningNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda, model.GetConversion(nodes(3)).Kind) Assert.Equal(ConversionKind.NarrowingNullableTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, model.GetConversion(nodes(4)).Kind) End Sub <Fact> Public Sub DelegateRelaxationLevel_09() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Imports System Public Class C Shared Sub Main() Dim int as integer = 1 Dim t? = (int, Function() int) Dim x00 As (Integer, Func(Of Integer)) = t Dim x01 As (Integer, Func(Of Long)) = t Dim x02 As (Integer, Action) = t Dim x03 As (Integer, Object) = t Dim x04 As (Integer, Func(Of Short)) = t End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(id) id.Identifier.ValueText = "t").ToArray() Assert.Equal(ConversionKind.NarrowingNullableTuple, model.GetConversion(nodes(0)).Kind) Assert.Equal(ConversionKind.NarrowingNullableTuple Or ConversionKind.DelegateRelaxationLevelWidening, model.GetConversion(nodes(1)).Kind) Assert.Equal(ConversionKind.NarrowingNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningDropReturnOrArgs, model.GetConversion(nodes(2)).Kind) Assert.Equal(ConversionKind.NarrowingNullableTuple Or ConversionKind.DelegateRelaxationLevelWideningToNonLambda, model.GetConversion(nodes(3)).Kind) Assert.Equal(ConversionKind.NarrowingNullableTuple Or ConversionKind.DelegateRelaxationLevelNarrowing, model.GetConversion(nodes(4)).Kind) End Sub <Fact> Public Sub AnonymousDelegate_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Dim int = 1 Dim a = Function(x as Integer) x Test1(a) Test2((a, int)) Test3((a, int)) Dim b = (a, int) Test2(b) Test3(b) End Sub Shared Sub Test1(x As Object) System.Console.WriteLine("second") End Sub Shared Sub Test2(x As (Object, Integer)) System.Console.WriteLine("second") End Sub Shared Sub Test3(x As (Object, Integer)?) System.Console.WriteLine("second") End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" second second second second second") End Sub <Fact> <WorkItem(14529, "https://github.com/dotnet/roslyn/issues/14529")> <WorkItem(14530, "https://github.com/dotnet/roslyn/issues/14530")> Public Sub AnonymousDelegate_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Dim int = 1 Dim a = Function(x as Integer) x Test1(a) Test2((a, int)) Test3((a, int)) Dim b = (a, int) Test2(b) Test3(b) Test4({a}) End Sub Shared Sub Test1(Of T)(x As System.Func(Of T, T)) System.Console.WriteLine("third") End Sub Shared Sub Test2(Of T)(x As (System.Func(Of T, T), Integer)) System.Console.WriteLine("third") End Sub Shared Sub Test3(Of T)(x As (System.Func(Of T, T), Integer)?) System.Console.WriteLine("third") End Sub Shared Sub Test4(Of T)(x As System.Func(Of T, T)()) System.Console.WriteLine("third") End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" third third third third third third") End Sub <Fact> Public Sub UserDefinedConversions_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Public Class C Shared Sub Main() Dim int = 1 Dim tuple = (int, int) Dim a as (A, Integer) = tuple Dim b as (A, Integer) = (int, int) Dim c as (A, Integer)? = tuple Dim d as (A, Integer)? = (int, int) System.Console.WriteLine(a) System.Console.WriteLine(b) System.Console.WriteLine(c) System.Console.WriteLine(d) End Sub End Class Class A Public Shared Widening Operator CType(val As String) As A System.Console.WriteLine(val) Return New A() End Operator End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" 1 1 1 1 (A, 1) (A, 1) (A, 1) (A, 1)") End Sub <Fact> Public Sub UserDefinedConversions_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Public Class C Shared Sub Main() Dim int = 1 Dim val as new B() Dim tuple = (val, int) Dim a as (Integer, Integer) = tuple Dim b as (Integer, Integer) = (val, int) Dim c as (Integer, Integer)? = tuple Dim d as (Integer, Integer)? = (val, int) System.Console.WriteLine(a) System.Console.WriteLine(b) System.Console.WriteLine(c) System.Console.WriteLine(d) End Sub End Class Class B Public Shared Widening Operator CType(val As B) As String System.Console.WriteLine(val Is Nothing) Return "2" End Operator End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" False False False False (2, 1) (2, 1) (2, 1) (2, 1)") End Sub <Fact> <WorkItem(14530, "https://github.com/dotnet/roslyn/issues/14530")> Public Sub UserDefinedConversions_03() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict Off Public Class C Shared Sub Main() Dim int = 1 Dim ad = Function() 2 Dim tuple = (ad, int) Dim a as (A, Integer) = tuple Dim b as (A, Integer) = (ad, int) Dim c as (A, Integer)? = tuple Dim d as (A, Integer)? = (ad, int) System.Console.WriteLine(a) System.Console.WriteLine(b) System.Console.WriteLine(c) System.Console.WriteLine(d) End Sub End Class Class A Public Shared Widening Operator CType(val As System.Func(Of Integer, Integer)) As A System.Console.WriteLine(val) Return New A() End Operator End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" System.Func`2[System.Int32,System.Int32] System.Func`2[System.Int32,System.Int32] System.Func`2[System.Int32,System.Int32] System.Func`2[System.Int32,System.Int32] (A, 1) (A, 1) (A, 1) (A, 1)") End Sub <Fact> Public Sub Inference02_Addressof() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Function M() As Integer Return 7 End Function Shared Sub Main() Test((AddressOf M, AddressOf M)) End Sub Shared Sub Test(Of T)(x As (T, T)) System.Console.WriteLine("first") End Sub Shared Sub Test(x As (Object, Object)) System.Console.WriteLine("second") End Sub Shared Sub Test(Of T)(x As (System.Func(Of T), System.Func(Of T))) System.Console.WriteLine("third") System.Console.WriteLine(x.Item1().ToString()) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" third 7 ") End Sub <Fact> Public Sub Inference03_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Test((Function(x) x, Function(x) x)) End Sub Shared Sub Test(Of T)(x As (T, T)) End Sub Shared Sub Test(x As (Object, Object)) End Sub Shared Sub Test(Of T)(x As (System.Func(Of Integer, T), System.Func(Of T, T))) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected><![CDATA[ BC30521: Overload resolution failed because no accessible 'Test' is most specific for these arguments: 'Public Shared Sub Test(Of <generated method>)(x As (<generated method>, <generated method>))': Not most specific. 'Public Shared Sub Test(Of Integer)(x As (Func(Of Integer, Integer), Func(Of Integer, Integer)))': Not most specific. Test((Function(x) x, Function(x) x)) ~~~~ ]]></expected>) End Sub <Fact> Public Sub Inference03_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Test((Function(x) x, Function(x) x)) End Sub Shared Sub Test(x As (Object, Object)) System.Console.WriteLine("second") End Sub Shared Sub Test(Of T)(x As (System.Func(Of Integer, T), System.Func(Of T, T))) System.Console.WriteLine("third") System.Console.WriteLine(x.Item1(5).ToString()) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" third 5 ") End Sub <Fact> Public Sub Inference03_03() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Test((Function(x) x, Function(x) x)) End Sub Shared Sub Test(Of T)(x As T, y As T) System.Console.WriteLine("first") End Sub Shared Sub Test(x As (Object, Object)) System.Console.WriteLine("second") End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" second ") End Sub <Fact> Public Sub Inference05() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Test((Function(x) x.x, Function(x) x.Item2)) Test((Function(x) x.bob, Function(x) x.Item1)) End Sub Shared Sub Test(Of T)(x As (f1 As Func(Of (x As Byte, y As Byte), T), f2 As Func(Of (Integer, Integer), T))) Console.WriteLine("first") Console.WriteLine(x.f1((2, 3)).ToString()) Console.WriteLine(x.f2((2, 3)).ToString()) End Sub Shared Sub Test(Of T)(x As (f1 As Func(Of (alice As Integer, bob As Integer), T), f2 As Func(Of (Integer, Integer), T))) Console.WriteLine("second") Console.WriteLine(x.f1((4, 5)).ToString()) Console.WriteLine(x.f2((4, 5)).ToString()) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:="first 2 3 second 5 4 ") End Sub <Fact> Public Sub Inference08() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Test1((a:=1, b:=2), (c:=3, d:=4)) Test2((a:=1, b:=2), (c:=3, d:=4), Function(t) t.Item2) Test2((a:=1, b:=2), (a:=3, b:=4), Function(t) t.a) Test2((a:=1, b:=2), (c:=3, d:=4), Function(t) t.a) End Sub Shared Sub Test1(Of T)(x As T, y As T) Console.WriteLine("test1") Console.WriteLine(x) End Sub Shared Sub Test2(Of T)(x As T, y As T, f As Func(Of T, Integer)) Console.WriteLine("test2_1") Console.WriteLine(f(x)) End Sub Shared Sub Test2(Of T)(x As T, y As Object, f As Func(Of T, Integer)) Console.WriteLine("test2_2") Console.WriteLine(f(x)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" test1 (1, 2) test2_1 2 test2_1 1 test2_2 1 ") End Sub <Fact> Public Sub Inference08t() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim ab = (a:=1, b:=2) Dim cd = (c:=3, d:=4) Test1(ab, cd) Test2(ab, cd, Function(t) t.Item2) Test2(ab, ab, Function(t) t.a) Test2(ab, cd, Function(t) t.a) End Sub Shared Sub Test1(Of T)(x As T, y As T) Console.WriteLine("test1") Console.WriteLine(x) End Sub Shared Sub Test2(Of T)(x As T, y As T, f As Func(Of T, Integer)) Console.WriteLine("test2_1") Console.WriteLine(f(x)) End Sub Shared Sub Test2(Of T)(x As T, y As Object, f As Func(Of T, Integer)) Console.WriteLine("test2_2") Console.WriteLine(f(x)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" test1 (1, 2) test2_1 2 test2_1 1 test2_2 1 ") End Sub <Fact> Public Sub Inference09() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Test1((a:=1, b:=2), DirectCast(1, ValueType)) End Sub Shared Sub Test1(Of T)(x As T, y As T) Console.Write(GetType(T)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:="System.ValueType") End Sub <Fact> Public Sub Inference10() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim t = (a:=1, b:=2) Test1(t, DirectCast(1, ValueType)) End Sub Shared Sub Test1(Of T)(ByRef x As T, y As T) Console.Write(GetType(T)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC36651: Data type(s) of the type parameter(s) in method 'Public Shared Sub Test1(Of T)(ByRef x As T, y As T)' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error. Test1(t, DirectCast(1, ValueType)) ~~~~~ </errors>) End Sub <Fact> Public Sub Inference11() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim ab = (a:=1, b:=2) Dim cd = (c:=1, d:=2) Test3(ab, cd) Test1(ab, cd) Test2(ab, cd) End Sub Shared Sub Test1(Of T)(ByRef x As T, y As T) Console.Write(GetType(T)) End Sub Shared Sub Test2(Of T)(x As T, ByRef y As T) Console.Write(GetType(T)) End Sub Shared Sub Test3(Of T)(ByRef x As T, ByRef y As T) Console.Write(GetType(T)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> </errors>) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim test3 = tree.GetRoot().DescendantNodes().OfType(Of InvocationExpressionSyntax)().First() Assert.Equal("Sub C.Test3(Of (System.Int32, System.Int32))(ByRef x As (System.Int32, System.Int32), ByRef y As (System.Int32, System.Int32))", model.GetSymbolInfo(test3).Symbol.ToTestDisplayString()) End Sub <Fact> Public Sub Inference12() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=DirectCast(1, Object))) Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(c:=1, d:=2))) Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(1, 2))) Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(a:=1, b:=2))) End Sub Shared Sub Test1(Of T, U)(x As (T, U), y As (T, U)) Console.WriteLine(GetType(U)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" System.Object System.ValueTuple`2[System.Int32,System.Int32] System.ValueTuple`2[System.Int32,System.Int32] System.ValueTuple`2[System.Int32,System.Int32] ") End Sub <Fact> <WorkItem(14152, "https://github.com/dotnet/roslyn/issues/14152")> Public Sub Inference13() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=DirectCast(1, Object))) Test1(Nullable((a:=1, b:=(a:=1, b:=2))), (a:=1, b:=DirectCast(1, Object))) Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(c:=1, d:=2))) Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(1, 2))) Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(a:=1, b:=2))) End Sub Shared Function Nullable(Of T as structure)(x as T) as T? return x End Function Shared Sub Test1(Of T, U)(x As (T, U)?, y As (T, U)) Console.WriteLine(GetType(U)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" System.Object System.Object System.ValueTuple`2[System.Int32,System.Int32] System.ValueTuple`2[System.Int32,System.Int32] System.ValueTuple`2[System.Int32,System.Int32] ") End Sub <Fact> <WorkItem(22329, "https://github.com/dotnet/roslyn/issues/22329")> <WorkItem(14152, "https://github.com/dotnet/roslyn/issues/14152")> Public Sub Inference13a() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Test2(Nullable((a:=1, b:=(a:=1, b:=2))), (a:=1, b:=DirectCast(1, Object))) Test2((a:=1, b:=(a:=1, b:=2)), Nullable((a:=1, b:=DirectCast((a:=1, b:=2), Object)))) End Sub Shared Function Nullable(Of T as structure)(x as T) as T? return x End Function Shared Sub Test2(Of T, U)(x As (T, U), y As (T, U)) Console.WriteLine(GetType(U)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) AssertTheseDiagnostics(comp, <expected> BC36645: Data type(s) of the type parameter(s) in method 'Public Shared Sub Test2(Of T, U)(x As (T, U), y As (T, U))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. Test2(Nullable((a:=1, b:=(a:=1, b:=2))), (a:=1, b:=DirectCast(1, Object))) ~~~~~ BC36645: Data type(s) of the type parameter(s) in method 'Public Shared Sub Test2(Of T, U)(x As (T, U), y As (T, U))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. Test2((a:=1, b:=(a:=1, b:=2)), Nullable((a:=1, b:=DirectCast((a:=1, b:=2), Object)))) ~~~~~ </expected>) End Sub <Fact> Public Sub Inference14() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(c:=1, d:=2))) Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(1, 2))) Test1((a:=1, b:=(a:=1, b:=2)), (a:=1, b:=(a:=1, b:=2))) End Sub Shared Sub Test1(Of T, U As Structure)(x As (T, U)?, y As (T, U)?) Console.WriteLine(GetType(U)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" System.ValueTuple`2[System.Int32,System.Int32] System.ValueTuple`2[System.Int32,System.Int32] System.ValueTuple`2[System.Int32,System.Int32] ") ' In C#, there are errors because names matter during best type inference ' This should get fixed after issue https://github.com/dotnet/roslyn/issues/13938 is fixed End Sub <Fact> Public Sub Inference15() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Test1((a:="1", b:=Nothing), (a:=Nothing, b:="w"), Function(x) x.z) End Sub Shared Sub Test1(Of T, U)(x As (T, U), y As (T, U), f As Func(Of (x As T, z As U), T)) Console.WriteLine(GetType(U)) Console.WriteLine(f(y)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" System.String w ") End Sub <Fact> Public Sub Inference16() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim x = (1, 2, 3) Test(x) Dim x1 = (1, 2, CType(3, Long)) Test(x1) Dim x2 = (1, DirectCast(2, Object), CType(3, Long)) Test(x2) End Sub Shared Sub Test(Of T)(x As (T, T, T)) Console.WriteLine(GetType(T)) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" System.Int32 System.Int64 System.Object ") End Sub <Fact()> Public Sub Constraints_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Namespace System Public Structure ValueTuple(Of T1 As Class, T2) Sub New(_1 As T1, _2 As T2) End Sub End Structure End Namespace Class C Sub M(p As (Integer, Integer)) Dim t0 = (1, 2) Dim t1 As (Integer, Integer) = t0 End Sub End Class ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T1'. Sub M(p As (Integer, Integer)) ~ BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T1'. Dim t0 = (1, 2) ~ BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T1'. Dim t1 As (Integer, Integer) = t0 ~~~~~~~ </errors>) End Sub <Fact()> Public Sub Constraints_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C Sub M(p As (Integer, ArgIterator), q As ValueTuple(Of Integer, ArgIterator)) Dim t0 As (Integer, ArgIterator) = p Dim t1 = (1, New ArgIterator()) Dim t2 = New ValueTuple(Of Integer, ArgIterator)(1, Nothing) Dim t3 As ValueTuple(Of Integer, ArgIterator) = t2 End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Sub M(p As (Integer, ArgIterator), q As ValueTuple(Of Integer, ArgIterator)) ~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Sub M(p As (Integer, ArgIterator), q As ValueTuple(Of Integer, ArgIterator)) ~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim t0 As (Integer, ArgIterator) = p ~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim t1 = (1, New ArgIterator()) ~~~~~~~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim t2 = New ValueTuple(Of Integer, ArgIterator)(1, Nothing) ~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim t3 As ValueTuple(Of Integer, ArgIterator) = t2 ~~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub Constraints_03() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System.Collections.Generic Namespace System Public Structure ValueTuple(Of T1, T2 As Class) Sub New(_1 As T1, _2 As T2) End Sub End Structure End Namespace Class C(Of T) Dim field As List(Of (T, T)) Function M(Of U)(x As U) As (U, U) Dim t0 = New C(Of Integer)() Dim t1 = M(1) Return (Nothing, Nothing) End Function End Class ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC32106: Type argument 'T' does not satisfy the 'Class' constraint for type parameter 'T2'. Dim field As List(Of (T, T)) ~ BC32106: Type argument 'U' does not satisfy the 'Class' constraint for type parameter 'T2'. Function M(Of U)(x As U) As (U, U) ~~~~~~ </errors>) End Sub <Fact()> Public Sub Constraints_04() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System.Collections.Generic Namespace System Public Structure ValueTuple(Of T1, T2 As Class) Sub New(_1 As T1, _2 As T2) End Sub End Structure End Namespace Class C(Of T As Class) Dim field As List(Of (T, T)) Function M(Of U As Class)(x As U) As (U, U) Dim t0 = New C(Of Integer)() Dim t1 = M(1) Return (Nothing, Nothing) End Function End Class ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T'. Dim t0 = New C(Of Integer)() ~~~~~~~ BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'U'. Dim t1 = M(1) ~ </errors>) End Sub <Fact()> Public Sub Constraints_05() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System.Collections.Generic Namespace System Public Structure ValueTuple(Of T1, T2 As Structure) Sub New(_1 As T1, _2 As T2) End Sub End Structure End Namespace Class C(Of T As Class) Dim field As List(Of (T, T)) Function M(Of U As Class)(x As (U, U)) As (U, U) Dim t0 = New C(Of Integer)() Dim t1 = M((1, 2)) Return (Nothing, Nothing) End Function End Class ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC32105: Type argument 'T' does not satisfy the 'Structure' constraint for type parameter 'T2'. Dim field As List(Of (T, T)) ~ BC32105: Type argument 'U' does not satisfy the 'Structure' constraint for type parameter 'T2'. Function M(Of U As Class)(x As (U, U)) As (U, U) ~ BC32105: Type argument 'U' does not satisfy the 'Structure' constraint for type parameter 'T2'. Function M(Of U As Class)(x As (U, U)) As (U, U) ~~~~~~ BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T'. Dim t0 = New C(Of Integer)() ~~~~~~~ BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'U'. Dim t1 = M((1, 2)) ~ BC32105: Type argument 'Object' does not satisfy the 'Structure' constraint for type parameter 'T2'. Return (Nothing, Nothing) ~~~~~~~ </errors>) End Sub <Fact()> Public Sub Constraints_06() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Namespace System Public Structure ValueTuple(Of T1 As Class) Public Sub New(item1 As T1) End Sub End Structure Public Structure ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest As Class) Public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6, item7 As T7, rest As TRest) End Sub End Structure End Namespace Class C Sub M(p As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)) Dim t0 = (1, 2, 3, 4, 5, 6, 7, 8) Dim t1 As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = t0 End Sub End Class ]]></file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T1'. Sub M(p As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)) ~ BC32106: Type argument 'ValueTuple(Of Integer)' does not satisfy the 'Class' constraint for type parameter 'TRest'. Sub M(p As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)) ~ BC32106: Type argument 'ValueTuple(Of Integer)' does not satisfy the 'Class' constraint for type parameter 'TRest'. Dim t0 = (1, 2, 3, 4, 5, 6, 7, 8) ~~~~~~~~~~~~~~~~~~~~~~~~ BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T1'. Dim t0 = (1, 2, 3, 4, 5, 6, 7, 8) ~ BC32106: Type argument 'ValueTuple(Of Integer)' does not satisfy the 'Class' constraint for type parameter 'TRest'. Dim t1 As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = t0 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32106: Type argument 'Integer' does not satisfy the 'Class' constraint for type parameter 'T1'. Dim t1 As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = t0 ~~~~~~~ </errors>) End Sub <Fact()> Public Sub LongTupleConstraints() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C Sub M0(p As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator)) Dim t1 As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator) = p Dim t2 = (1, 2, 3, 4, 5, 6, 7, New ArgIterator()) Dim t3 = New ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer, ArgIterator))() Dim t4 = New ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, ArgIterator))() Dim t5 As ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer, ArgIterator)) = t3 Dim t6 As ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, ArgIterator)) = t4 End Sub Sub M1(q As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator)) Dim v1 As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator) = q Dim v2 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, New ArgIterator()) End Sub End Class]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Sub M0(p As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator)) ~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim t1 As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator) = p ~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim t2 = (1, 2, 3, 4, 5, 6, 7, New ArgIterator()) ~~~~~~~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim t3 = New ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer, ArgIterator))() ~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim t4 = New ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, ArgIterator))() ~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim t5 As ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer, ArgIterator)) = t3 ~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim t6 As ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, ArgIterator)) = t4 ~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Sub M1(q As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator)) ~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim v1 As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, ArgIterator) = q ~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim v2 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, New ArgIterator()) ~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub RestrictedTypes1() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim x = (1, 2, New ArgIterator()) Dim y As (x As Integer, y As Object) = (1, 2, New ArgIterator()) Dim z As (x As Integer, y As ArgIterator) = (1, 2, New ArgIterator()) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x = (1, 2, New ArgIterator()) ~~~~~~~~~~~~~~~~~ BC30311: Value of type '(Integer, Integer, ArgIterator)' cannot be converted to '(x As Integer, y As Object)'. Dim y As (x As Integer, y As Object) = (1, 2, New ArgIterator()) ~~~~~~~~~~~~~~~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim y As (x As Integer, y As Object) = (1, 2, New ArgIterator()) ~~~~~~~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim z As (x As Integer, y As ArgIterator) = (1, 2, New ArgIterator()) ~ BC30311: Value of type '(Integer, Integer, ArgIterator)' cannot be converted to '(x As Integer, y As ArgIterator)'. Dim z As (x As Integer, y As ArgIterator) = (1, 2, New ArgIterator()) ~~~~~~~~~~~~~~~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim z As (x As Integer, y As ArgIterator) = (1, 2, New ArgIterator()) ~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub RestrictedTypes2() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim y As (x As Integer, y As ArgIterator) End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC42024: Unused local variable: 'y'. Dim y As (x As Integer, y As ArgIterator) ~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim y As (x As Integer, y As ArgIterator) ~ </errors>) End Sub <Fact> Public Sub ImplementInterface() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Interface I Function M(value As (x As Integer, y As String)) As (Alice As Integer, Bob As String) ReadOnly Property P1 As (Alice As Integer, Bob As String) End Interface Public Class C Implements I Shared Sub Main() Dim c = New C() Dim x = c.M(c.P1) Console.Write(x) End Sub Public Function M(value As (x As Integer, y As String)) As (Alice As Integer, Bob As String) Implements I.M Return value End Function ReadOnly Property P1 As (Alice As Integer, Bob As String) Implements I.P1 Get Return (r:=1, s:="hello") End Get End Property End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:="(1, hello)") End Sub <Fact> Public Sub TupleTypeArguments() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Interface I(Of TA, TB As TA) Function M(a As TA, b As TB) As (TA, TB) End Interface Public Class C Implements I(Of (Integer, String), (Alice As Integer, Bob As String)) Shared Sub Main() Dim c = New C() Dim x = c.M((1, "Australia"), (2, "Brazil")) Console.Write(x) End Sub Public Function M(x As (Integer, String), y As (Alice As Integer, Bob As String)) As ((Integer, String), (Alice As Integer, Bob As String)) Implements I(Of (Integer, String), (Alice As Integer, Bob As String)).M Return (x, y) End Function End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:="((1, Australia), (2, Brazil))") End Sub <Fact> Public Sub OverrideGenericInterfaceWithDifferentNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Interface I(Of TA, TB As TA) Function M(paramA As TA, paramB As TB) As (returnA As TA, returnB As TB) End Interface Public Class C Implements I(Of (a As Integer, b As String), (Integer, String)) Public Overridable Function M(x As ((Integer, Integer), (Integer, Integer))) As (x As (Integer, Integer), y As (Integer, Integer)) Implements I(Of (b As Integer, a As Integer), (a As Integer, b As Integer)).M Throw New Exception() End Function End Class </file> </compilation>, options:=TestOptions.DebugDll, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30149: Class 'C' must implement 'Function M(paramA As (a As Integer, b As String), paramB As (Integer, String)) As (returnA As (a As Integer, b As String), returnB As (Integer, String))' for interface 'I(Of (a As Integer, b As String), (Integer, String))'. Implements I(Of (a As Integer, b As String), (Integer, String)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31035: Interface 'I(Of (b As Integer, a As Integer), (a As Integer, b As Integer))' is not implemented by this class. Public Overridable Function M(x As ((Integer, Integer), (Integer, Integer))) As (x As (Integer, Integer), y As (Integer, Integer)) Implements I(Of (b As Integer, a As Integer), (a As Integer, b As Integer)).M ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub TupleWithoutFeatureFlag() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim x As (Integer, Integer) = (1, 1) Else End Sub End Class </file> </compilation>, options:=TestOptions.DebugDll, additionalRefs:=s_valueTupleRefs, parseOptions:=TestOptions.Regular.WithLanguageVersion(LanguageVersion.VisualBasic14)) comp.AssertTheseDiagnostics( <errors> BC36716: Visual Basic 14.0 does not support tuples. Dim x As (Integer, Integer) = (1, 1) ~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 14.0 does not support tuples. Dim x As (Integer, Integer) = (1, 1) ~~~~~~ BC30086: 'Else' must be preceded by a matching 'If' or 'ElseIf'. Else ~~~~ </errors>) Dim x = comp.GetDiagnostics() Assert.Equal("15", Compilation.GetRequiredLanguageVersion(comp.GetDiagnostics()(0))) Assert.Null(Compilation.GetRequiredLanguageVersion(comp.GetDiagnostics()(2))) Assert.Throws(Of ArgumentNullException)(Sub() Compilation.GetRequiredLanguageVersion(Nothing)) End Sub <Fact> Public Sub DefaultAndFriendlyElementNames_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim v1 = M1() Console.WriteLine($"{v1.Item1} {v1.Item2}") Dim v2 = M2() Console.WriteLine($"{v2.Item1} {v2.Item2} {v2.a2} {v2.b2}") Dim v6 = M6() Console.WriteLine($"{v6.Item1} {v6.Item2} {v6.item1} {v6.item2}") Console.WriteLine(v1.ToString()) Console.WriteLine(v2.ToString()) Console.WriteLine(v6.ToString()) End Sub Shared Function M1() As (Integer, Integer) Return (1, 11) End Function Shared Function M2() As (a2 As Integer, b2 As Integer) Return (2, 22) End Function Shared Function M6() As (item1 As Integer, item2 As Integer) Return (6, 66) End Function End Class </file> </compilation>, options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" 1 11 2 22 2 22 6 66 6 66 (1, 11) (2, 22) (6, 66) ") Dim c = comp.GetTypeByMetadataName("C") Dim m1Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M1").ReturnType, NamedTypeSymbol) Dim m2Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M2").ReturnType, NamedTypeSymbol) Dim m6Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M6").ReturnType, NamedTypeSymbol) AssertTestDisplayString(m1Tuple.GetMembers(), "(System.Int32, System.Int32).Item1 As System.Int32", "(System.Int32, System.Int32).Item2 As System.Int32", "Sub (System.Int32, System.Int32)..ctor()", "Sub (System.Int32, System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)", "Function (System.Int32, System.Int32).Equals(obj As System.Object) As System.Boolean", "Function (System.Int32, System.Int32).Equals(other As (System.Int32, System.Int32)) As System.Boolean", "Function (System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function (System.Int32, System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function (System.Int32, System.Int32).CompareTo(other As (System.Int32, System.Int32)) As System.Int32", "Function (System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function (System.Int32, System.Int32).GetHashCode() As System.Int32", "Function (System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32).ToString() As System.String", "Function (System.Int32, System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function (System.Int32, System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property (System.Int32, System.Int32).System.ITupleInternal.Size As System.Int32" ) Assert.Equal({ ".ctor", ".ctor", "CompareTo", "Equals", "Equals", "GetHashCode", "Item1", "Item2", "System.Collections.IStructuralComparable.CompareTo", "System.Collections.IStructuralEquatable.Equals", "System.Collections.IStructuralEquatable.GetHashCode", "System.IComparable.CompareTo", "System.ITupleInternal.get_Size", "System.ITupleInternal.GetHashCode", "System.ITupleInternal.Size", "System.ITupleInternal.ToStringEnd", "ToString"}, DirectCast(m1Tuple, TupleTypeSymbol).UnderlyingDefinitionToMemberMap.Values.Select(Function(s) s.Name).OrderBy(Function(s) s).ToArray() ) AssertTestDisplayString(m2Tuple.GetMembers(), "(a2 As System.Int32, b2 As System.Int32).Item1 As System.Int32", "(a2 As System.Int32, b2 As System.Int32).a2 As System.Int32", "(a2 As System.Int32, b2 As System.Int32).Item2 As System.Int32", "(a2 As System.Int32, b2 As System.Int32).b2 As System.Int32", "Sub (a2 As System.Int32, b2 As System.Int32)..ctor()", "Sub (a2 As System.Int32, b2 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)", "Function (a2 As System.Int32, b2 As System.Int32).Equals(obj As System.Object) As System.Boolean", "Function (a2 As System.Int32, b2 As System.Int32).Equals(other As (System.Int32, System.Int32)) As System.Boolean", "Function (a2 As System.Int32, b2 As System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function (a2 As System.Int32, b2 As System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function (a2 As System.Int32, b2 As System.Int32).CompareTo(other As (System.Int32, System.Int32)) As System.Int32", "Function (a2 As System.Int32, b2 As System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function (a2 As System.Int32, b2 As System.Int32).GetHashCode() As System.Int32", "Function (a2 As System.Int32, b2 As System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (a2 As System.Int32, b2 As System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (a2 As System.Int32, b2 As System.Int32).ToString() As System.String", "Function (a2 As System.Int32, b2 As System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function (a2 As System.Int32, b2 As System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property (a2 As System.Int32, b2 As System.Int32).System.ITupleInternal.Size As System.Int32" ) Assert.Equal({ ".ctor", ".ctor", "CompareTo", "Equals", "Equals", "GetHashCode", "Item1", "Item2", "System.Collections.IStructuralComparable.CompareTo", "System.Collections.IStructuralEquatable.Equals", "System.Collections.IStructuralEquatable.GetHashCode", "System.IComparable.CompareTo", "System.ITupleInternal.get_Size", "System.ITupleInternal.GetHashCode", "System.ITupleInternal.Size", "System.ITupleInternal.ToStringEnd", "ToString"}, DirectCast(m2Tuple, TupleTypeSymbol).UnderlyingDefinitionToMemberMap.Values.Select(Function(s) s.Name).OrderBy(Function(s) s).ToArray() ) AssertTestDisplayString(m6Tuple.GetMembers(), "(Item1 As System.Int32, Item2 As System.Int32).Item1 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32).Item2 As System.Int32", "Sub (Item1 As System.Int32, Item2 As System.Int32)..ctor()", "Sub (Item1 As System.Int32, Item2 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)", "Function (Item1 As System.Int32, Item2 As System.Int32).Equals(obj As System.Object) As System.Boolean", "Function (Item1 As System.Int32, Item2 As System.Int32).Equals(other As (System.Int32, System.Int32)) As System.Boolean", "Function (Item1 As System.Int32, Item2 As System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function (Item1 As System.Int32, Item2 As System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32).CompareTo(other As (System.Int32, System.Int32)) As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32).GetHashCode() As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32).ToString() As System.String", "Function (Item1 As System.Int32, Item2 As System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function (Item1 As System.Int32, Item2 As System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property (Item1 As System.Int32, Item2 As System.Int32).System.ITupleInternal.Size As System.Int32" ) Assert.Equal({ ".ctor", ".ctor", "CompareTo", "Equals", "Equals", "GetHashCode", "Item1", "Item2", "System.Collections.IStructuralComparable.CompareTo", "System.Collections.IStructuralEquatable.Equals", "System.Collections.IStructuralEquatable.GetHashCode", "System.IComparable.CompareTo", "System.ITupleInternal.get_Size", "System.ITupleInternal.GetHashCode", "System.ITupleInternal.Size", "System.ITupleInternal.ToStringEnd", "ToString"}, DirectCast(m6Tuple, TupleTypeSymbol).UnderlyingDefinitionToMemberMap.Values.Select(Function(s) s.Name).OrderBy(Function(s) s).ToArray() ) Assert.Equal("", m1Tuple.Name) Assert.Equal(SymbolKind.NamedType, m1Tuple.Kind) Assert.Equal(TypeKind.Struct, m1Tuple.TypeKind) Assert.False(m1Tuple.IsImplicitlyDeclared) Assert.True(m1Tuple.IsTupleType) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32)", m1Tuple.TupleUnderlyingType.ToTestDisplayString()) Assert.Same(m1Tuple, m1Tuple.ConstructedFrom) Assert.Same(m1Tuple, m1Tuple.OriginalDefinition) AssertTupleTypeEquality(m1Tuple) Assert.Same(m1Tuple.TupleUnderlyingType.ContainingSymbol, m1Tuple.ContainingSymbol) Assert.Null(m1Tuple.EnumUnderlyingType) Assert.Equal({ "Item1", "Item2", ".ctor", "Equals", "System.Collections.IStructuralEquatable.Equals", "System.IComparable.CompareTo", "CompareTo", "System.Collections.IStructuralComparable.CompareTo", "GetHashCode", "System.Collections.IStructuralEquatable.GetHashCode", "System.ITupleInternal.GetHashCode", "ToString", "System.ITupleInternal.ToStringEnd", "System.ITupleInternal.get_Size", "System.ITupleInternal.Size"}, m1Tuple.MemberNames.ToArray()) Assert.Equal({ "Item1", "a2", "Item2", "b2", ".ctor", "Equals", "System.Collections.IStructuralEquatable.Equals", "System.IComparable.CompareTo", "CompareTo", "System.Collections.IStructuralComparable.CompareTo", "GetHashCode", "System.Collections.IStructuralEquatable.GetHashCode", "System.ITupleInternal.GetHashCode", "ToString", "System.ITupleInternal.ToStringEnd", "System.ITupleInternal.get_Size", "System.ITupleInternal.Size"}, m2Tuple.MemberNames.ToArray()) Assert.Equal(0, m1Tuple.Arity) Assert.True(m1Tuple.TypeParameters.IsEmpty) Assert.Equal("System.ValueType", m1Tuple.BaseType.ToTestDisplayString()) Assert.False(m1Tuple.HasTypeArgumentsCustomModifiers) Assert.False(m1Tuple.IsComImport) Assert.True(m1Tuple.TypeArgumentsNoUseSiteDiagnostics.IsEmpty) Assert.True(m1Tuple.GetAttributes().IsEmpty) Assert.Equal("(a2 As System.Int32, b2 As System.Int32).Item1 As System.Int32", m2Tuple.GetMembers("Item1").Single().ToTestDisplayString()) Assert.Equal("(a2 As System.Int32, b2 As System.Int32).a2 As System.Int32", m2Tuple.GetMembers("a2").Single().ToTestDisplayString()) Assert.True(m1Tuple.GetTypeMembers().IsEmpty) Assert.True(m1Tuple.GetTypeMembers("C9").IsEmpty) Assert.True(m1Tuple.GetTypeMembers("C9", 0).IsEmpty) Assert.Equal(6, m1Tuple.Interfaces.Length) Assert.True(m1Tuple.GetTypeMembersUnordered().IsEmpty) Assert.Equal(1, m1Tuple.Locations.Length) Assert.Equal("(Integer, Integer)", m1Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.Equal("(a2 As Integer, b2 As Integer)", m2Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) AssertTupleTypeEquality(m2Tuple) AssertTupleTypeEquality(m6Tuple) Assert.False(m1Tuple.Equals(m2Tuple)) Assert.False(m1Tuple.Equals(m6Tuple)) Assert.False(m6Tuple.Equals(m2Tuple)) AssertTupleTypeMembersEquality(m1Tuple, m2Tuple) AssertTupleTypeMembersEquality(m1Tuple, m6Tuple) AssertTupleTypeMembersEquality(m2Tuple, m6Tuple) Dim m1Item1 = DirectCast(m1Tuple.GetMembers()(0), FieldSymbol) Dim m2Item1 = DirectCast(m2Tuple.GetMembers()(0), FieldSymbol) Dim m2a2 = DirectCast(m2Tuple.GetMembers()(1), FieldSymbol) AssertNonvirtualTupleElementField(m1Item1) AssertNonvirtualTupleElementField(m2Item1) AssertVirtualTupleElementField(m2a2) Assert.True(m1Item1.IsTupleField) Assert.Same(m1Item1, m1Item1.OriginalDefinition) Assert.True(m1Item1.Equals(m1Item1)) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m1Item1.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m1Item1.AssociatedSymbol) Assert.Same(m1Tuple, m1Item1.ContainingSymbol) Assert.Same(m1Tuple.TupleUnderlyingType, m1Item1.TupleUnderlyingField.ContainingSymbol) Assert.True(m1Item1.CustomModifiers.IsEmpty) Assert.True(m1Item1.GetAttributes().IsEmpty) Assert.Null(m1Item1.GetUseSiteErrorInfo()) Assert.False(m1Item1.Locations.IsEmpty) Assert.True(m1Item1.DeclaringSyntaxReferences.IsEmpty) Assert.Equal("Item1", m1Item1.TupleUnderlyingField.Name) Assert.True(m1Item1.IsImplicitlyDeclared) Assert.Null(m1Item1.TypeLayoutOffset) Assert.True(m2Item1.IsTupleField) Assert.Same(m2Item1, m2Item1.OriginalDefinition) Assert.True(m2Item1.Equals(m2Item1)) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m2Item1.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m2Item1.AssociatedSymbol) Assert.Same(m2Tuple, m2Item1.ContainingSymbol) Assert.Same(m2Tuple.TupleUnderlyingType, m2Item1.TupleUnderlyingField.ContainingSymbol) Assert.True(m2Item1.CustomModifiers.IsEmpty) Assert.True(m2Item1.GetAttributes().IsEmpty) Assert.Null(m2Item1.GetUseSiteErrorInfo()) Assert.False(m2Item1.Locations.IsEmpty) Assert.Equal("Item1", m2Item1.Name) Assert.Equal("Item1", m2Item1.TupleUnderlyingField.Name) Assert.NotEqual(m2Item1.Locations.Single(), m2Item1.TupleUnderlyingField.Locations.Single()) Assert.Equal("MetadataFile(System.ValueTuple.dll)", m2Item1.TupleUnderlyingField.Locations.Single().ToString()) Assert.Equal("SourceFile(a.vb[589..591))", m2Item1.Locations.Single().ToString()) Assert.True(m2Item1.IsImplicitlyDeclared) Assert.Null(m2Item1.TypeLayoutOffset) Assert.True(m2a2.IsTupleField) Assert.Same(m2a2, m2a2.OriginalDefinition) Assert.True(m2a2.Equals(m2a2)) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m2a2.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m2a2.AssociatedSymbol) Assert.Same(m2Tuple, m2a2.ContainingSymbol) Assert.Same(m2Tuple.TupleUnderlyingType, m2a2.TupleUnderlyingField.ContainingSymbol) Assert.True(m2a2.CustomModifiers.IsEmpty) Assert.True(m2a2.GetAttributes().IsEmpty) Assert.Null(m2a2.GetUseSiteErrorInfo()) Assert.False(m2a2.Locations.IsEmpty) Assert.Equal("a2 As Integer", m2a2.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.Equal("Item1", m2a2.TupleUnderlyingField.Name) Assert.False(m2a2.IsImplicitlyDeclared) Assert.Null(m2a2.TypeLayoutOffset) End Sub Private Sub AssertTupleTypeEquality(tuple As NamedTypeSymbol) Assert.True(tuple.Equals(tuple)) Dim members = tuple.GetMembers() For i = 0 To members.Length - 1 For j = 0 To members.Length - 1 If i <> j Then Assert.NotSame(members(i), members(j)) Assert.False(members(i).Equals(members(j))) Assert.False(members(j).Equals(members(i))) End If Next Next Dim underlyingMembers = tuple.TupleUnderlyingType.GetMembers() For Each m In members Assert.False(underlyingMembers.Any(Function(u) u.Equals(m))) Assert.False(underlyingMembers.Any(Function(u) m.Equals(u))) Next End Sub Private Sub AssertTupleTypeMembersEquality(tuple1 As NamedTypeSymbol, tuple2 As NamedTypeSymbol) Assert.NotSame(tuple1, tuple2) If tuple1.Equals(tuple2) Then Assert.True(tuple2.Equals(tuple1)) Dim members1 = tuple1.GetMembers() Dim members2 = tuple2.GetMembers() Assert.Equal(members1.Length, members2.Length) For i = 0 To members1.Length - 1 Assert.NotSame(members1(i), members2(i)) Assert.True(members1(i).Equals(members2(i))) Assert.True(members2(i).Equals(members1(i))) Assert.Equal(members2(i).GetHashCode(), members1(i).GetHashCode()) If members1(i).Kind = SymbolKind.Method Then Dim parameters1 = DirectCast(members1(i), MethodSymbol).Parameters Dim parameters2 = DirectCast(members2(i), MethodSymbol).Parameters AssertTupleMembersParametersEquality(parameters1, parameters2) Dim typeParameters1 = DirectCast(members1(i), MethodSymbol).TypeParameters Dim typeParameters2 = DirectCast(members2(i), MethodSymbol).TypeParameters Assert.Equal(typeParameters1.Length, typeParameters2.Length) For j = 0 To typeParameters1.Length - 1 Assert.NotSame(typeParameters1(j), typeParameters2(j)) Assert.True(typeParameters1(j).Equals(typeParameters2(j))) Assert.True(typeParameters2(j).Equals(typeParameters1(j))) Assert.Equal(typeParameters2(j).GetHashCode(), typeParameters1(j).GetHashCode()) Next ElseIf members1(i).Kind = SymbolKind.Property Then Dim parameters1 = DirectCast(members1(i), PropertySymbol).Parameters Dim parameters2 = DirectCast(members2(i), PropertySymbol).Parameters AssertTupleMembersParametersEquality(parameters1, parameters2) End If Next For i = 0 To members1.Length - 1 For j = 0 To members2.Length - 1 If i <> j Then Assert.NotSame(members1(i), members2(j)) Assert.False(members1(i).Equals(members2(j))) End If Next Next Else Assert.False(tuple2.Equals(tuple1)) Dim members1 = tuple1.GetMembers() Dim members2 = tuple2.GetMembers() For Each m In members1 Assert.False(members2.Any(Function(u) u.Equals(m))) Assert.False(members2.Any(Function(u) m.Equals(u))) Next End If End Sub Private Sub AssertTupleMembersParametersEquality(parameters1 As ImmutableArray(Of ParameterSymbol), parameters2 As ImmutableArray(Of ParameterSymbol)) Assert.Equal(parameters1.Length, parameters2.Length) For j = 0 To parameters1.Length - 1 Assert.NotSame(parameters1(j), parameters2(j)) Assert.True(parameters1(j).Equals(parameters2(j))) Assert.True(parameters2(j).Equals(parameters1(j))) Assert.Equal(parameters2(j).GetHashCode(), parameters1(j).GetHashCode()) Next End Sub Private Sub AssertVirtualTupleElementField(sym As FieldSymbol) Assert.True(sym.IsTupleField) Assert.True(sym.IsVirtualTupleField) ' it is an element so must have nonnegative index Assert.True(sym.TupleElementIndex >= 0) End Sub Private Sub AssertNonvirtualTupleElementField(sym As FieldSymbol) Assert.True(sym.IsTupleField) Assert.False(sym.IsVirtualTupleField) ' it is an element so must have nonnegative index Assert.True(sym.TupleElementIndex >= 0) ' if it was 8th or after, it would be virtual Assert.True(sym.TupleElementIndex < TupleTypeSymbol.RestPosition - 1) End Sub Private Shared Sub AssertTestDisplayString(symbols As ImmutableArray(Of Symbol), ParamArray baseLine As String()) ' Re-ordering arguments because expected is usually first. AssertEx.Equal(baseLine, symbols.Select(Function(s) s.ToTestDisplayString())) End Sub <Fact> Public Sub DefaultAndFriendlyElementNames_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim v3 = M3() Console.WriteLine(v3.Item1) Console.WriteLine(v3.Item2) Console.WriteLine(v3.Item3) Console.WriteLine(v3.Item4) Console.WriteLine(v3.Item5) Console.WriteLine(v3.Item6) Console.WriteLine(v3.Item7) Console.WriteLine(v3.Item8) Console.WriteLine(v3.Item9) Console.WriteLine(v3.Rest.Item1) Console.WriteLine(v3.Rest.Item2) Console.WriteLine(v3.ToString()) End Sub Shared Function M3() As (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) Return (31, 32, 33, 34, 35, 36, 37, 38, 39) End Function End Class </file> </compilation>, options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" 31 32 33 34 35 36 37 38 39 38 39 (31, 32, 33, 34, 35, 36, 37, 38, 39) ") Dim c = comp.GetTypeByMetadataName("C") Dim m3Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M3").ReturnType, NamedTypeSymbol) AssertTestDisplayString(m3Tuple.GetMembers(), "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item1 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item2 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item3 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item4 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item5 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item6 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item7 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Rest As (System.Int32, System.Int32)", "Sub (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor()", "Sub (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32, item3 As System.Int32, item4 As System.Int32, item5 As System.Int32, item6 As System.Int32, item7 As System.Int32, rest As (System.Int32, System.Int32))", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(obj As System.Object) As System.Boolean", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Boolean", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).CompareTo(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).GetHashCode() As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).ToString() As System.String", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.Size As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item8 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item9 As System.Int32" ) Dim m3Item8 = DirectCast(m3Tuple.GetMembers("Item8").Single(), FieldSymbol) AssertVirtualTupleElementField(m3Item8) Assert.True(m3Item8.IsTupleField) Assert.Same(m3Item8, m3Item8.OriginalDefinition) Assert.True(m3Item8.Equals(m3Item8)) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m3Item8.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m3Item8.AssociatedSymbol) Assert.Same(m3Tuple, m3Item8.ContainingSymbol) Assert.NotEqual(m3Tuple.TupleUnderlyingType, m3Item8.TupleUnderlyingField.ContainingSymbol) Assert.True(m3Item8.CustomModifiers.IsEmpty) Assert.True(m3Item8.GetAttributes().IsEmpty) Assert.Null(m3Item8.GetUseSiteErrorInfo()) Assert.False(m3Item8.Locations.IsEmpty) Assert.True(m3Item8.DeclaringSyntaxReferences.IsEmpty) Assert.Equal("Item1", m3Item8.TupleUnderlyingField.Name) Assert.True(m3Item8.IsImplicitlyDeclared) Assert.Null(m3Item8.TypeLayoutOffset) Assert.False(DirectCast(m3Item8, IFieldSymbol).IsExplicitlyNamedTupleElement) Dim m3TupleRestTuple = DirectCast(DirectCast(m3Tuple.GetMembers("Rest").Single(), FieldSymbol).Type, NamedTypeSymbol) AssertTestDisplayString(m3TupleRestTuple.GetMembers(), "(System.Int32, System.Int32).Item1 As System.Int32", "(System.Int32, System.Int32).Item2 As System.Int32", "Sub (System.Int32, System.Int32)..ctor()", "Sub (System.Int32, System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)", "Function (System.Int32, System.Int32).Equals(obj As System.Object) As System.Boolean", "Function (System.Int32, System.Int32).Equals(other As (System.Int32, System.Int32)) As System.Boolean", "Function (System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function (System.Int32, System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function (System.Int32, System.Int32).CompareTo(other As (System.Int32, System.Int32)) As System.Int32", "Function (System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function (System.Int32, System.Int32).GetHashCode() As System.Int32", "Function (System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32).ToString() As System.String", "Function (System.Int32, System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function (System.Int32, System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property (System.Int32, System.Int32).System.ITupleInternal.Size As System.Int32" ) Assert.True(m3TupleRestTuple.IsTupleType) AssertTupleTypeEquality(m3TupleRestTuple) Assert.True(m3TupleRestTuple.Locations.IsEmpty) Assert.True(m3TupleRestTuple.DeclaringSyntaxReferences.IsEmpty) For Each m In m3TupleRestTuple.GetMembers().OfType(Of FieldSymbol)() Assert.True(m.Locations.IsEmpty) Next End Sub <Fact> Public Sub DefaultAndFriendlyElementNames_03() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim v4 = M4() Console.WriteLine(v4.Item1) Console.WriteLine(v4.Item2) Console.WriteLine(v4.Item3) Console.WriteLine(v4.Item4) Console.WriteLine(v4.Item5) Console.WriteLine(v4.Item6) Console.WriteLine(v4.Item7) Console.WriteLine(v4.Item8) Console.WriteLine(v4.Item9) Console.WriteLine(v4.Rest.Item1) Console.WriteLine(v4.Rest.Item2) Console.WriteLine(v4.a4) Console.WriteLine(v4.b4) Console.WriteLine(v4.c4) Console.WriteLine(v4.d4) Console.WriteLine(v4.e4) Console.WriteLine(v4.f4) Console.WriteLine(v4.g4) Console.WriteLine(v4.h4) Console.WriteLine(v4.i4) Console.WriteLine(v4.ToString()) End Sub Shared Function M4() As (a4 As Integer, b4 As Integer, c4 As Integer, d4 As Integer, e4 As Integer, f4 As Integer, g4 As Integer, h4 As Integer, i4 As Integer) Return (41, 42, 43, 44, 45, 46, 47, 48, 49) End Function End Class </file> </compilation>, options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" 41 42 43 44 45 46 47 48 49 48 49 41 42 43 44 45 46 47 48 49 (41, 42, 43, 44, 45, 46, 47, 48, 49) ") Dim c = comp.GetTypeByMetadataName("C") Dim m4Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M4").ReturnType, NamedTypeSymbol) AssertTupleTypeEquality(m4Tuple) AssertTestDisplayString(m4Tuple.GetMembers(), "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item1 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).a4 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item2 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).b4 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item3 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).c4 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item4 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).d4 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item5 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).e4 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item6 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).f4 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item7 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).g4 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Rest As (System.Int32, System.Int32)", "Sub (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32)..ctor()", "Sub (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32, item3 As System.Int32, item4 As System.Int32, item5 As System.Int32, item6 As System.Int32, item7 As System.Int32, rest As (System.Int32, System.Int32))", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Equals(obj As System.Object) As System.Boolean", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Equals(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Boolean", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).CompareTo(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Int32", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).GetHashCode() As System.Int32", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).ToString() As System.String", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property (a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).System.ITupleInternal.Size As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item8 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).h4 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).Item9 As System.Int32", "(a4 As System.Int32, b4 As System.Int32, c4 As System.Int32, d4 As System.Int32, e4 As System.Int32, f4 As System.Int32, g4 As System.Int32, h4 As System.Int32, i4 As System.Int32).i4 As System.Int32" ) Dim m4Item8 = DirectCast(m4Tuple.GetMembers("Item8").Single(), FieldSymbol) AssertVirtualTupleElementField(m4Item8) Assert.True(m4Item8.IsTupleField) Assert.Same(m4Item8, m4Item8.OriginalDefinition) Assert.True(m4Item8.Equals(m4Item8)) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m4Item8.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m4Item8.AssociatedSymbol) Assert.Same(m4Tuple, m4Item8.ContainingSymbol) Assert.NotEqual(m4Tuple.TupleUnderlyingType, m4Item8.TupleUnderlyingField.ContainingSymbol) Assert.True(m4Item8.CustomModifiers.IsEmpty) Assert.True(m4Item8.GetAttributes().IsEmpty) Assert.Null(m4Item8.GetUseSiteErrorInfo()) Assert.False(m4Item8.Locations.IsEmpty) Assert.Equal("Item1", m4Item8.TupleUnderlyingField.Name) Assert.True(m4Item8.IsImplicitlyDeclared) Assert.Null(m4Item8.TypeLayoutOffset) Assert.False(DirectCast(m4Item8, IFieldSymbol).IsExplicitlyNamedTupleElement) Dim m4h4 = DirectCast(m4Tuple.GetMembers("h4").Single(), FieldSymbol) AssertVirtualTupleElementField(m4h4) Assert.True(m4h4.IsTupleField) Assert.Same(m4h4, m4h4.OriginalDefinition) Assert.True(m4h4.Equals(m4h4)) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m4h4.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m4h4.AssociatedSymbol) Assert.Same(m4Tuple, m4h4.ContainingSymbol) Assert.NotEqual(m4Tuple.TupleUnderlyingType, m4h4.TupleUnderlyingField.ContainingSymbol) Assert.True(m4h4.CustomModifiers.IsEmpty) Assert.True(m4h4.GetAttributes().IsEmpty) Assert.Null(m4h4.GetUseSiteErrorInfo()) Assert.False(m4h4.Locations.IsEmpty) Assert.Equal("Item1", m4h4.TupleUnderlyingField.Name) Assert.False(m4h4.IsImplicitlyDeclared) Assert.Null(m4h4.TypeLayoutOffset) Assert.True(DirectCast(m4h4, IFieldSymbol).IsExplicitlyNamedTupleElement) Dim m4TupleRestTuple = DirectCast(DirectCast(m4Tuple.GetMembers("Rest").Single(), FieldSymbol).Type, NamedTypeSymbol) AssertTestDisplayString(m4TupleRestTuple.GetMembers(), "(System.Int32, System.Int32).Item1 As System.Int32", "(System.Int32, System.Int32).Item2 As System.Int32", "Sub (System.Int32, System.Int32)..ctor()", "Sub (System.Int32, System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)", "Function (System.Int32, System.Int32).Equals(obj As System.Object) As System.Boolean", "Function (System.Int32, System.Int32).Equals(other As (System.Int32, System.Int32)) As System.Boolean", "Function (System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function (System.Int32, System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function (System.Int32, System.Int32).CompareTo(other As (System.Int32, System.Int32)) As System.Int32", "Function (System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function (System.Int32, System.Int32).GetHashCode() As System.Int32", "Function (System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32).ToString() As System.String", "Function (System.Int32, System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function (System.Int32, System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property (System.Int32, System.Int32).System.ITupleInternal.Size As System.Int32" ) For Each m In m4TupleRestTuple.GetMembers().OfType(Of FieldSymbol)() Assert.True(m.Locations.IsEmpty) Next End Sub <Fact> Public Sub DefaultAndFriendlyElementNames_04() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim v4 = M4() Console.WriteLine(v4.Rest.a4) Console.WriteLine(v4.Rest.b4) Console.WriteLine(v4.Rest.c4) Console.WriteLine(v4.Rest.d4) Console.WriteLine(v4.Rest.e4) Console.WriteLine(v4.Rest.f4) Console.WriteLine(v4.Rest.g4) Console.WriteLine(v4.Rest.h4) Console.WriteLine(v4.Rest.i4) Console.WriteLine(v4.ToString()) End Sub Shared Function M4() As (a4 As Integer, b4 As Integer, c4 As Integer, d4 As Integer, e4 As Integer, f4 As Integer, g4 As Integer, h4 As Integer, i4 As Integer) Return (41, 42, 43, 44, 45, 46, 47, 48, 49) End Function End Class </file> </compilation>, options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30456: 'a4' is not a member of '(Integer, Integer)'. Console.WriteLine(v4.Rest.a4) ~~~~~~~~~~ BC30456: 'b4' is not a member of '(Integer, Integer)'. Console.WriteLine(v4.Rest.b4) ~~~~~~~~~~ BC30456: 'c4' is not a member of '(Integer, Integer)'. Console.WriteLine(v4.Rest.c4) ~~~~~~~~~~ BC30456: 'd4' is not a member of '(Integer, Integer)'. Console.WriteLine(v4.Rest.d4) ~~~~~~~~~~ BC30456: 'e4' is not a member of '(Integer, Integer)'. Console.WriteLine(v4.Rest.e4) ~~~~~~~~~~ BC30456: 'f4' is not a member of '(Integer, Integer)'. Console.WriteLine(v4.Rest.f4) ~~~~~~~~~~ BC30456: 'g4' is not a member of '(Integer, Integer)'. Console.WriteLine(v4.Rest.g4) ~~~~~~~~~~ BC30456: 'h4' is not a member of '(Integer, Integer)'. Console.WriteLine(v4.Rest.h4) ~~~~~~~~~~ BC30456: 'i4' is not a member of '(Integer, Integer)'. Console.WriteLine(v4.Rest.i4) ~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub DefaultAndFriendlyElementNames_05() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim v5 = M5() Console.WriteLine(v5.Item1) Console.WriteLine(v5.Item2) Console.WriteLine(v5.Item3) Console.WriteLine(v5.Item4) Console.WriteLine(v5.Item5) Console.WriteLine(v5.Item6) Console.WriteLine(v5.Item7) Console.WriteLine(v5.Item8) Console.WriteLine(v5.Item9) Console.WriteLine(v5.Item10) Console.WriteLine(v5.Item11) Console.WriteLine(v5.Item12) Console.WriteLine(v5.Item13) Console.WriteLine(v5.Item14) Console.WriteLine(v5.Item15) Console.WriteLine(v5.Item16) Console.WriteLine(v5.Rest.Item1) Console.WriteLine(v5.Rest.Item2) Console.WriteLine(v5.Rest.Item3) Console.WriteLine(v5.Rest.Item4) Console.WriteLine(v5.Rest.Item5) Console.WriteLine(v5.Rest.Item6) Console.WriteLine(v5.Rest.Item7) Console.WriteLine(v5.Rest.Item8) Console.WriteLine(v5.Rest.Item9) Console.WriteLine(v5.Rest.Rest.Item1) Console.WriteLine(v5.Rest.Rest.Item2) Console.WriteLine(v5.ToString()) End Sub Shared Function M5() As (Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer, Item9 As Integer, Item10 As Integer, Item11 As Integer, Item12 As Integer, Item13 As Integer, Item14 As Integer, Item15 As Integer, Item16 As Integer) Return (501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516) End Function End Class </file> </compilation>, options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 508 509 510 511 512 513 514 515 516 515 516 (501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516) ") Dim c = comp.GetTypeByMetadataName("C") Dim m5Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M5").ReturnType, NamedTypeSymbol) AssertTupleTypeEquality(m5Tuple) AssertTestDisplayString(m5Tuple.GetMembers(), "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item1 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item2 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item3 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item4 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item5 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item6 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item7 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Rest As (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)", "Sub (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32)..ctor()", "Sub (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32, item3 As System.Int32, item4 As System.Int32, item5 As System.Int32, item6 As System.Int32, item7 As System.Int32, rest As (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32))", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Equals(obj As System.Object) As System.Boolean", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Equals(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32))) As System.Boolean", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).CompareTo(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32))) As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).GetHashCode() As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).ToString() As System.String", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property (Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).System.ITupleInternal.Size As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item8 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item9 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item10 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item11 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item12 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item13 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item14 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item15 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32, Item9 As System.Int32, Item10 As System.Int32, Item11 As System.Int32, Item12 As System.Int32, Item13 As System.Int32, Item14 As System.Int32, Item15 As System.Int32, Item16 As System.Int32).Item16 As System.Int32" ) Dim m5Item8 = DirectCast(m5Tuple.GetMembers("Item8").Single(), FieldSymbol) AssertVirtualTupleElementField(m5Item8) Assert.True(m5Item8.IsTupleField) Assert.Same(m5Item8, m5Item8.OriginalDefinition) Assert.True(m5Item8.Equals(m5Item8)) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32)).Item1 As System.Int32", m5Item8.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m5Item8.AssociatedSymbol) Assert.Same(m5Tuple, m5Item8.ContainingSymbol) Assert.NotEqual(m5Tuple.TupleUnderlyingType, m5Item8.TupleUnderlyingField.ContainingSymbol) Assert.True(m5Item8.CustomModifiers.IsEmpty) Assert.True(m5Item8.GetAttributes().IsEmpty) Assert.Null(m5Item8.GetUseSiteErrorInfo()) Assert.False(m5Item8.Locations.IsEmpty) Assert.Equal("Item8 As Integer", m5Item8.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.Equal("Item1", m5Item8.TupleUnderlyingField.Name) Assert.False(m5Item8.IsImplicitlyDeclared) Assert.True(DirectCast(m5Item8, IFieldSymbol).IsExplicitlyNamedTupleElement) Assert.Null(m5Item8.TypeLayoutOffset) Dim m5TupleRestTuple = DirectCast(DirectCast(m5Tuple.GetMembers("Rest").Single(), FieldSymbol).Type, NamedTypeSymbol) AssertVirtualTupleElementField(m5Item8) AssertTestDisplayString(m5TupleRestTuple.GetMembers(), "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item1 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item2 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item3 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item4 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item5 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item6 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item7 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Rest As (System.Int32, System.Int32)", "Sub (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor()", "Sub (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32, item3 As System.Int32, item4 As System.Int32, item5 As System.Int32, item6 As System.Int32, item7 As System.Int32, rest As (System.Int32, System.Int32))", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(obj As System.Object) As System.Boolean", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Boolean", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).CompareTo(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).GetHashCode() As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).ToString() As System.String", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.Size As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item8 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item9 As System.Int32" ) For Each m In m5TupleRestTuple.GetMembers().OfType(Of FieldSymbol)() If m.Name <> "Rest" Then Assert.True(m.Locations.IsEmpty) Else Assert.Equal("Rest", m.Name) End If Next Dim m5TupleRestTupleRestTuple = DirectCast(DirectCast(m5TupleRestTuple.GetMembers("Rest").Single(), FieldSymbol).Type, NamedTypeSymbol) AssertTupleTypeEquality(m5TupleRestTupleRestTuple) AssertTestDisplayString(m5TupleRestTuple.GetMembers(), "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item1 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item2 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item3 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item4 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item5 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item6 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item7 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Rest As (System.Int32, System.Int32)", "Sub (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor()", "Sub (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32, item3 As System.Int32, item4 As System.Int32, item5 As System.Int32, item6 As System.Int32, item7 As System.Int32, rest As (System.Int32, System.Int32))", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(obj As System.Object) As System.Boolean", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Equals(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Boolean", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).CompareTo(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, (System.Int32, System.Int32))) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).GetHashCode() As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).ToString() As System.String", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property (System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).System.ITupleInternal.Size As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item8 As System.Int32", "(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32).Item9 As System.Int32" ) For Each m In m5TupleRestTupleRestTuple.GetMembers().OfType(Of FieldSymbol)() Assert.True(m.Locations.IsEmpty) Next End Sub <Fact> Public Sub DefaultAndFriendlyElementNames_06() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim v5 = M5() Console.WriteLine(v5.Rest.Item10) Console.WriteLine(v5.Rest.Item11) Console.WriteLine(v5.Rest.Item12) Console.WriteLine(v5.Rest.Item13) Console.WriteLine(v5.Rest.Item14) Console.WriteLine(v5.Rest.Item15) Console.WriteLine(v5.Rest.Item16) Console.WriteLine(v5.Rest.Rest.Item3) Console.WriteLine(v5.Rest.Rest.Item4) Console.WriteLine(v5.Rest.Rest.Item5) Console.WriteLine(v5.Rest.Rest.Item6) Console.WriteLine(v5.Rest.Rest.Item7) Console.WriteLine(v5.Rest.Rest.Item8) Console.WriteLine(v5.Rest.Rest.Item9) Console.WriteLine(v5.Rest.Rest.Item10) Console.WriteLine(v5.Rest.Rest.Item11) Console.WriteLine(v5.Rest.Rest.Item12) Console.WriteLine(v5.Rest.Rest.Item13) Console.WriteLine(v5.Rest.Rest.Item14) Console.WriteLine(v5.Rest.Rest.Item15) Console.WriteLine(v5.Rest.Rest.Item16) End Sub Shared Function M5() As (Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer, Item9 As Integer, Item10 As Integer, Item11 As Integer, Item12 As Integer, Item13 As Integer, Item14 As Integer, Item15 As Integer, Item16 As Integer) Return (501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516) End Function End Class </file> </compilation>, options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30456: 'Item10' is not a member of '(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'. Console.WriteLine(v5.Rest.Item10) ~~~~~~~~~~~~~~ BC30456: 'Item11' is not a member of '(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'. Console.WriteLine(v5.Rest.Item11) ~~~~~~~~~~~~~~ BC30456: 'Item12' is not a member of '(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'. Console.WriteLine(v5.Rest.Item12) ~~~~~~~~~~~~~~ BC30456: 'Item13' is not a member of '(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'. Console.WriteLine(v5.Rest.Item13) ~~~~~~~~~~~~~~ BC30456: 'Item14' is not a member of '(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'. Console.WriteLine(v5.Rest.Item14) ~~~~~~~~~~~~~~ BC30456: 'Item15' is not a member of '(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'. Console.WriteLine(v5.Rest.Item15) ~~~~~~~~~~~~~~ BC30456: 'Item16' is not a member of '(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)'. Console.WriteLine(v5.Rest.Item16) ~~~~~~~~~~~~~~ BC30456: 'Item3' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item3) ~~~~~~~~~~~~~~~~~~ BC30456: 'Item4' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item4) ~~~~~~~~~~~~~~~~~~ BC30456: 'Item5' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item5) ~~~~~~~~~~~~~~~~~~ BC30456: 'Item6' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item6) ~~~~~~~~~~~~~~~~~~ BC30456: 'Item7' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item7) ~~~~~~~~~~~~~~~~~~ BC30456: 'Item8' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item8) ~~~~~~~~~~~~~~~~~~ BC30456: 'Item9' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item9) ~~~~~~~~~~~~~~~~~~ BC30456: 'Item10' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item10) ~~~~~~~~~~~~~~~~~~~ BC30456: 'Item11' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item11) ~~~~~~~~~~~~~~~~~~~ BC30456: 'Item12' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item12) ~~~~~~~~~~~~~~~~~~~ BC30456: 'Item13' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item13) ~~~~~~~~~~~~~~~~~~~ BC30456: 'Item14' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item14) ~~~~~~~~~~~~~~~~~~~ BC30456: 'Item15' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item15) ~~~~~~~~~~~~~~~~~~~ BC30456: 'Item16' is not a member of '(Integer, Integer)'. Console.WriteLine(v5.Rest.Rest.Item16) ~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub DefaultAndFriendlyElementNames_07() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() End Sub Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer) Return (701, 702, 703, 704, 705, 706, 707, 708, 709) End Function End Class <%= s_trivial2uple %><%= s_trivial3uple %><%= s_trivialRemainingTuples %> </file> </compilation>, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics( <errors> BC37261: Tuple element name 'Item9' is only allowed at position 9. Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer) ~~~~~ BC37261: Tuple element name 'Item1' is only allowed at position 1. Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer) ~~~~~ BC37261: Tuple element name 'Item2' is only allowed at position 2. Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer) ~~~~~ BC37261: Tuple element name 'Item3' is only allowed at position 3. Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer) ~~~~~ BC37261: Tuple element name 'Item4' is only allowed at position 4. Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer) ~~~~~ BC37261: Tuple element name 'Item5' is only allowed at position 5. Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer) ~~~~~ BC37261: Tuple element name 'Item6' is only allowed at position 6. Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer) ~~~~~ BC37261: Tuple element name 'Item7' is only allowed at position 7. Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer) ~~~~~ BC37261: Tuple element name 'Item8' is only allowed at position 8. Shared Function M7() As (Item9 As Integer, Item1 As Integer, Item2 As Integer, Item3 As Integer, Item4 As Integer, Item5 As Integer, Item6 As Integer, Item7 As Integer, Item8 As Integer) ~~~~~ </errors>) Dim c = comp.GetTypeByMetadataName("C") Dim m7Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M7").ReturnType, NamedTypeSymbol) AssertTupleTypeEquality(m7Tuple) AssertTestDisplayString(m7Tuple.GetMembers(), "Sub (Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32)..ctor()", "Sub (Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32, item3 As System.Int32, item4 As System.Int32, item5 As System.Int32, item6 As System.Int32, item7 As System.Int32, rest As (System.Int32, System.Int32))", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item8 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item7 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item9 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item8 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item1 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item9 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item2 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item1 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item3 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item2 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item4 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item3 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item5 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item4 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item6 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item5 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item7 As System.Int32", "(Item9 As System.Int32, Item1 As System.Int32, Item2 As System.Int32, Item3 As System.Int32, Item4 As System.Int32, Item5 As System.Int32, Item6 As System.Int32, Item7 As System.Int32, Item8 As System.Int32).Item6 As System.Int32" ) End Sub <Fact> Public Sub DefaultAndFriendlyElementNames_08() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() End Sub Shared Function M8() As (a1 As Integer, a2 As Integer, a3 As Integer, a4 As Integer, a5 As Integer, a6 As Integer, a7 As Integer, Item1 As Integer) Return (801, 802, 803, 804, 805, 806, 807, 808) End Function End Class </file> </compilation>, options:=TestOptions.DebugExe, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37261: Tuple element name 'Item1' is only allowed at position 1. Shared Function M8() As (a1 As Integer, a2 As Integer, a3 As Integer, a4 As Integer, a5 As Integer, a6 As Integer, a7 As Integer, Item1 As Integer) ~~~~~ </errors>) Dim c = comp.GetTypeByMetadataName("C") Dim m8Tuple = DirectCast(c.GetMember(Of MethodSymbol)("M8").ReturnType, NamedTypeSymbol) AssertTupleTypeEquality(m8Tuple) AssertTestDisplayString(m8Tuple.GetMembers(), "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item1 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).a1 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item2 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).a2 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item3 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).a3 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item4 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).a4 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item5 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).a5 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item6 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).a6 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item7 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).a7 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Rest As ValueTuple(Of System.Int32)", "Sub (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32)..ctor()", "Sub (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32, item3 As System.Int32, item4 As System.Int32, item5 As System.Int32, item6 As System.Int32, item7 As System.Int32, rest As ValueTuple(Of System.Int32))", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Equals(obj As System.Object) As System.Boolean", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Equals(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, ValueTuple(Of System.Int32))) As System.Boolean", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).CompareTo(other As System.ValueTuple(Of System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, ValueTuple(Of System.Int32))) As System.Int32", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).GetHashCode() As System.Int32", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).ToString() As System.String", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property (a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).System.ITupleInternal.Size As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item8 As System.Int32", "(a1 As System.Int32, a2 As System.Int32, a3 As System.Int32, a4 As System.Int32, a5 As System.Int32, a6 As System.Int32, a7 As System.Int32, Item1 As System.Int32).Item1 As System.Int32" ) Dim m8Item8 = DirectCast(m8Tuple.GetMembers("Item8").Single(), FieldSymbol) AssertVirtualTupleElementField(m8Item8) Assert.True(m8Item8.IsTupleField) Assert.Same(m8Item8, m8Item8.OriginalDefinition) Assert.True(m8Item8.Equals(m8Item8)) Assert.Equal("System.ValueTuple(Of System.Int32).Item1 As System.Int32", m8Item8.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m8Item8.AssociatedSymbol) Assert.Same(m8Tuple, m8Item8.ContainingSymbol) Assert.NotEqual(m8Tuple.TupleUnderlyingType, m8Item8.TupleUnderlyingField.ContainingSymbol) Assert.True(m8Item8.CustomModifiers.IsEmpty) Assert.True(m8Item8.GetAttributes().IsEmpty) Assert.Null(m8Item8.GetUseSiteErrorInfo()) Assert.False(m8Item8.Locations.IsEmpty) Assert.Equal("Item1", m8Item8.TupleUnderlyingField.Name) Assert.True(m8Item8.IsImplicitlyDeclared) Assert.False(DirectCast(m8Item8, IFieldSymbol).IsExplicitlyNamedTupleElement) Assert.Null(m8Item8.TypeLayoutOffset) Dim m8Item1 = DirectCast(m8Tuple.GetMembers("Item1").Last(), FieldSymbol) AssertVirtualTupleElementField(m8Item1) Assert.True(m8Item1.IsTupleField) Assert.Same(m8Item1, m8Item1.OriginalDefinition) Assert.True(m8Item1.Equals(m8Item1)) Assert.Equal("System.ValueTuple(Of System.Int32).Item1 As System.Int32", m8Item1.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m8Item1.AssociatedSymbol) Assert.Same(m8Tuple, m8Item1.ContainingSymbol) Assert.NotEqual(m8Tuple.TupleUnderlyingType, m8Item1.TupleUnderlyingField.ContainingSymbol) Assert.True(m8Item1.CustomModifiers.IsEmpty) Assert.True(m8Item1.GetAttributes().IsEmpty) Assert.Null(m8Item1.GetUseSiteErrorInfo()) Assert.False(m8Item1.Locations.IsEmpty) Assert.Equal("Item1", m8Item1.TupleUnderlyingField.Name) Assert.False(m8Item1.IsImplicitlyDeclared) Assert.True(DirectCast(m8Item1, IFieldSymbol).IsExplicitlyNamedTupleElement) Assert.Null(m8Item1.TypeLayoutOffset) Dim m8TupleRestTuple = DirectCast(DirectCast(m8Tuple.GetMembers("Rest").Single(), FieldSymbol).Type, NamedTypeSymbol) AssertTupleTypeEquality(m8TupleRestTuple) AssertTestDisplayString(m8TupleRestTuple.GetMembers(), "ValueTuple(Of System.Int32).Item1 As System.Int32", "Sub ValueTuple(Of System.Int32)..ctor()", "Sub ValueTuple(Of System.Int32)..ctor(item1 As System.Int32)", "Function ValueTuple(Of System.Int32).Equals(obj As System.Object) As System.Boolean", "Function ValueTuple(Of System.Int32).Equals(other As ValueTuple(Of System.Int32)) As System.Boolean", "Function ValueTuple(Of System.Int32).System.Collections.IStructuralEquatable.Equals(other As System.Object, comparer As System.Collections.IEqualityComparer) As System.Boolean", "Function ValueTuple(Of System.Int32).System.IComparable.CompareTo(other As System.Object) As System.Int32", "Function ValueTuple(Of System.Int32).CompareTo(other As ValueTuple(Of System.Int32)) As System.Int32", "Function ValueTuple(Of System.Int32).System.Collections.IStructuralComparable.CompareTo(other As System.Object, comparer As System.Collections.IComparer) As System.Int32", "Function ValueTuple(Of System.Int32).GetHashCode() As System.Int32", "Function ValueTuple(Of System.Int32).System.Collections.IStructuralEquatable.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function ValueTuple(Of System.Int32).System.ITupleInternal.GetHashCode(comparer As System.Collections.IEqualityComparer) As System.Int32", "Function ValueTuple(Of System.Int32).ToString() As System.String", "Function ValueTuple(Of System.Int32).System.ITupleInternal.ToStringEnd() As System.String", "Function ValueTuple(Of System.Int32).System.ITupleInternal.get_Size() As System.Int32", "ReadOnly Property ValueTuple(Of System.Int32).System.ITupleInternal.Size As System.Int32" ) End Sub <Fact> Public Sub DefaultAndFriendlyElementNames_09() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Shared Sub Main() Dim v1 = (1, 11) Console.WriteLine(v1.Item1) Console.WriteLine(v1.Item2) Dim v2 = (a2:=2, b2:=22) Console.WriteLine(v2.Item1) Console.WriteLine(v2.Item2) Console.WriteLine(v2.a2) Console.WriteLine(v2.b2) Dim v6 = (item1:=6, item2:=66) Console.WriteLine(v6.Item1) Console.WriteLine(v6.Item2) Console.WriteLine(v6.item1) Console.WriteLine(v6.item2) Console.WriteLine(v1.ToString()) Console.WriteLine(v2.ToString()) Console.WriteLine(v6.ToString()) End Sub End Class <%= s_trivial2uple %> </file> </compilation>, options:=TestOptions.DebugExe) CompileAndVerify(comp, expectedOutput:=" 1 11 2 22 2 22 6 66 6 66 {1, 11} {2, 22} {6, 66} ") Dim c = comp.GetTypeByMetadataName("C") Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes().OfType(Of TupleExpressionSyntax)().First() Dim m1Tuple = DirectCast(model.LookupSymbols(node.SpanStart, name:="v1").OfType(Of LocalSymbol)().Single().Type, NamedTypeSymbol) Dim m2Tuple = DirectCast(model.LookupSymbols(node.SpanStart, name:="v2").OfType(Of LocalSymbol)().Single().Type, NamedTypeSymbol) Dim m6Tuple = DirectCast(model.LookupSymbols(node.SpanStart, name:="v6").OfType(Of LocalSymbol)().Single().Type, NamedTypeSymbol) AssertTestDisplayString(m1Tuple.GetMembers(), "Sub (System.Int32, System.Int32)..ctor()", "(System.Int32, System.Int32).Item1 As System.Int32", "(System.Int32, System.Int32).Item2 As System.Int32", "Sub (System.Int32, System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)", "Function (System.Int32, System.Int32).ToString() As System.String" ) AssertTestDisplayString(m2Tuple.GetMembers(), "Sub (a2 As System.Int32, b2 As System.Int32)..ctor()", "(a2 As System.Int32, b2 As System.Int32).Item1 As System.Int32", "(a2 As System.Int32, b2 As System.Int32).a2 As System.Int32", "(a2 As System.Int32, b2 As System.Int32).Item2 As System.Int32", "(a2 As System.Int32, b2 As System.Int32).b2 As System.Int32", "Sub (a2 As System.Int32, b2 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)", "Function (a2 As System.Int32, b2 As System.Int32).ToString() As System.String" ) AssertTestDisplayString(m6Tuple.GetMembers(), "Sub (Item1 As System.Int32, Item2 As System.Int32)..ctor()", "(Item1 As System.Int32, Item2 As System.Int32).Item1 As System.Int32", "(Item1 As System.Int32, Item2 As System.Int32).Item2 As System.Int32", "Sub (Item1 As System.Int32, Item2 As System.Int32)..ctor(item1 As System.Int32, item2 As System.Int32)", "Function (Item1 As System.Int32, Item2 As System.Int32).ToString() As System.String" ) Assert.Equal("", m1Tuple.Name) Assert.Equal(SymbolKind.NamedType, m1Tuple.Kind) Assert.Equal(TypeKind.Struct, m1Tuple.TypeKind) Assert.False(m1Tuple.IsImplicitlyDeclared) Assert.True(m1Tuple.IsTupleType) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32)", m1Tuple.TupleUnderlyingType.ToTestDisplayString()) Assert.Same(m1Tuple, m1Tuple.ConstructedFrom) Assert.Same(m1Tuple, m1Tuple.OriginalDefinition) AssertTupleTypeEquality(m1Tuple) Assert.Same(m1Tuple.TupleUnderlyingType.ContainingSymbol, m1Tuple.ContainingSymbol) Assert.Null(m1Tuple.GetUseSiteErrorInfo()) Assert.Null(m1Tuple.EnumUnderlyingType) Assert.Equal({".ctor", "Item1", "Item2", "ToString"}, m1Tuple.MemberNames.ToArray()) Assert.Equal({".ctor", "Item1", "a2", "Item2", "b2", "ToString"}, m2Tuple.MemberNames.ToArray()) Assert.Equal(0, m1Tuple.Arity) Assert.True(m1Tuple.TypeParameters.IsEmpty) Assert.Equal("System.ValueType", m1Tuple.BaseType.ToTestDisplayString()) Assert.False(m1Tuple.HasTypeArgumentsCustomModifiers) Assert.False(m1Tuple.IsComImport) Assert.True(m1Tuple.TypeArgumentsNoUseSiteDiagnostics.IsEmpty) Assert.True(m1Tuple.GetAttributes().IsEmpty) Assert.Equal("(a2 As System.Int32, b2 As System.Int32).Item1 As System.Int32", m2Tuple.GetMembers("Item1").Single().ToTestDisplayString()) Assert.Equal("(a2 As System.Int32, b2 As System.Int32).a2 As System.Int32", m2Tuple.GetMembers("a2").Single().ToTestDisplayString()) Assert.True(m1Tuple.GetTypeMembers().IsEmpty) Assert.True(m1Tuple.GetTypeMembers("C9").IsEmpty) Assert.True(m1Tuple.GetTypeMembers("C9", 0).IsEmpty) Assert.True(m1Tuple.Interfaces.IsEmpty) Assert.True(m1Tuple.GetTypeMembersUnordered().IsEmpty) Assert.Equal(1, m1Tuple.Locations.Length) Assert.Equal("(1, 11)", m1Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.Equal("(a2:=2, b2:=22)", m2Tuple.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.Equal("Public Structure ValueTuple(Of T1, T2)", m1Tuple.TupleUnderlyingType.DeclaringSyntaxReferences.Single().GetSyntax().ToString().Substring(0, 38)) AssertTupleTypeEquality(m2Tuple) AssertTupleTypeEquality(m6Tuple) Assert.False(m1Tuple.Equals(m2Tuple)) Assert.False(m1Tuple.Equals(m6Tuple)) Assert.False(m6Tuple.Equals(m2Tuple)) AssertTupleTypeMembersEquality(m1Tuple, m2Tuple) AssertTupleTypeMembersEquality(m1Tuple, m6Tuple) AssertTupleTypeMembersEquality(m2Tuple, m6Tuple) Dim m1Item1 = DirectCast(m1Tuple.GetMembers()(1), FieldSymbol) AssertNonvirtualTupleElementField(m1Item1) Assert.True(m1Item1.IsTupleField) Assert.Same(m1Item1, m1Item1.OriginalDefinition) Assert.True(m1Item1.Equals(m1Item1)) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m1Item1.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m1Item1.AssociatedSymbol) Assert.Same(m1Tuple, m1Item1.ContainingSymbol) Assert.Same(m1Tuple.TupleUnderlyingType, m1Item1.TupleUnderlyingField.ContainingSymbol) Assert.True(m1Item1.CustomModifiers.IsEmpty) Assert.True(m1Item1.GetAttributes().IsEmpty) Assert.Null(m1Item1.GetUseSiteErrorInfo()) Assert.False(m1Item1.Locations.IsEmpty) Assert.True(m1Item1.DeclaringSyntaxReferences.IsEmpty) Assert.Equal("Item1", m1Item1.TupleUnderlyingField.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.True(m1Item1.IsImplicitlyDeclared) Assert.False(DirectCast(m1Item1, IFieldSymbol).IsExplicitlyNamedTupleElement) Assert.Null(m1Item1.TypeLayoutOffset) Dim m2Item1 = DirectCast(m2Tuple.GetMembers()(1), FieldSymbol) AssertNonvirtualTupleElementField(m2Item1) Assert.True(m2Item1.IsTupleField) Assert.Same(m2Item1, m2Item1.OriginalDefinition) Assert.True(m2Item1.Equals(m2Item1)) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m2Item1.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m2Item1.AssociatedSymbol) Assert.Same(m2Tuple, m2Item1.ContainingSymbol) Assert.Same(m2Tuple.TupleUnderlyingType, m2Item1.TupleUnderlyingField.ContainingSymbol) Assert.True(m2Item1.CustomModifiers.IsEmpty) Assert.True(m2Item1.GetAttributes().IsEmpty) Assert.Null(m2Item1.GetUseSiteErrorInfo()) Assert.False(m2Item1.Locations.IsEmpty) Assert.True(m2Item1.DeclaringSyntaxReferences.IsEmpty) Assert.Equal("Item1", m2Item1.TupleUnderlyingField.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.NotEqual(m2Item1.Locations.Single(), m2Item1.TupleUnderlyingField.Locations.Single()) Assert.Equal("SourceFile(a.vb[760..765))", m2Item1.TupleUnderlyingField.Locations.Single().ToString()) Assert.Equal("SourceFile(a.vb[175..177))", m2Item1.Locations.Single().ToString()) Assert.True(m2Item1.IsImplicitlyDeclared) Assert.False(DirectCast(m2Item1, IFieldSymbol).IsExplicitlyNamedTupleElement) Assert.Null(m2Item1.TypeLayoutOffset) Dim m2a2 = DirectCast(m2Tuple.GetMembers()(2), FieldSymbol) AssertVirtualTupleElementField(m2a2) Assert.True(m2a2.IsTupleField) Assert.Same(m2a2, m2a2.OriginalDefinition) Assert.True(m2a2.Equals(m2a2)) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32).Item1 As System.Int32", m2a2.TupleUnderlyingField.ToTestDisplayString()) Assert.Null(m2a2.AssociatedSymbol) Assert.Same(m2Tuple, m2a2.ContainingSymbol) Assert.Same(m2Tuple.TupleUnderlyingType, m2a2.TupleUnderlyingField.ContainingSymbol) Assert.True(m2a2.CustomModifiers.IsEmpty) Assert.True(m2a2.GetAttributes().IsEmpty) Assert.Null(m2a2.GetUseSiteErrorInfo()) Assert.False(m2a2.Locations.IsEmpty) Assert.Equal("a2", m2a2.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.Equal("Item1", m2a2.TupleUnderlyingField.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) Assert.False(m2a2.IsImplicitlyDeclared) Assert.True(DirectCast(m2a2, IFieldSymbol).IsExplicitlyNamedTupleElement) Assert.Null(m2a2.TypeLayoutOffset) Dim m1ToString = m1Tuple.GetMember(Of MethodSymbol)("ToString") Assert.True(m1ToString.IsTupleMethod) Assert.Same(m1ToString, m1ToString.OriginalDefinition) Assert.Same(m1ToString, m1ToString.ConstructedFrom) Assert.Equal("Function System.ValueTuple(Of System.Int32, System.Int32).ToString() As System.String", m1ToString.TupleUnderlyingMethod.ToTestDisplayString()) Assert.Same(m1ToString.TupleUnderlyingMethod, m1ToString.TupleUnderlyingMethod.ConstructedFrom) Assert.Same(m1Tuple, m1ToString.ContainingSymbol) Assert.Same(m1Tuple.TupleUnderlyingType, m1ToString.TupleUnderlyingMethod.ContainingType) Assert.Null(m1ToString.AssociatedSymbol) Assert.True(m1ToString.ExplicitInterfaceImplementations.IsEmpty) Assert.False(m1ToString.ReturnType.SpecialType = SpecialType.System_Void) Assert.True(m1ToString.TypeArguments.IsEmpty) Assert.True(m1ToString.TypeParameters.IsEmpty) Assert.True(m1ToString.GetAttributes().IsEmpty) Assert.Null(m1ToString.GetUseSiteErrorInfo()) Assert.Equal("Function System.ValueType.ToString() As System.String", m1ToString.OverriddenMethod.ToTestDisplayString()) Assert.False(m1ToString.Locations.IsEmpty) Assert.Equal("Public Overrides Function ToString()", m1ToString.DeclaringSyntaxReferences.Single().GetSyntax().ToString().Substring(0, 36)) Assert.Equal(m1ToString.Locations.Single(), m1ToString.TupleUnderlyingMethod.Locations.Single()) End Sub <Fact> Public Sub OverriddenMethodWithDifferentTupleNamesInReturn() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Base Public Overridable Function M1() As (a As Integer, b As Integer) Return (1, 2) End Function Public Overridable Function M2() As (a As Integer, b As Integer) Return (1, 2) End Function Public Overridable Function M3() As (a As Integer, b As Integer)() Return {(1, 2)} End Function Public Overridable Function M4() As (a As Integer, b As Integer)? Return (1, 2) End Function Public Overridable Function M5() As (c As (a As Integer, b As Integer), d As Integer) Return ((1, 2), 3) End Function End Class Public Class Derived Inherits Base Public Overrides Function M1() As (A As Integer, B As Integer) Return (1, 2) End Function Public Overrides Function M2() As (notA As Integer, notB As Integer) Return (1, 2) End Function Public Overrides Function M3() As (notA As Integer, notB As Integer)() Return {(1, 2)} End Function Public Overrides Function M4() As (notA As Integer, notB As Integer)? Return (1, 2) End Function Public Overrides Function M5() As (c As (notA As Integer, notB As Integer), d As Integer) Return ((1, 2), 3) End Function End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC40001: 'Public Overrides Function M2() As (notA As Integer, notB As Integer)' cannot override 'Public Overridable Function M2() As (a As Integer, b As Integer)' because they differ by their tuple element names. Public Overrides Function M2() As (notA As Integer, notB As Integer) ~~ BC40001: 'Public Overrides Function M3() As (notA As Integer, notB As Integer)()' cannot override 'Public Overridable Function M3() As (a As Integer, b As Integer)()' because they differ by their tuple element names. Public Overrides Function M3() As (notA As Integer, notB As Integer)() ~~ BC40001: 'Public Overrides Function M4() As (notA As Integer, notB As Integer)?' cannot override 'Public Overridable Function M4() As (a As Integer, b As Integer)?' because they differ by their tuple element names. Public Overrides Function M4() As (notA As Integer, notB As Integer)? ~~ BC40001: 'Public Overrides Function M5() As (c As (notA As Integer, notB As Integer), d As Integer)' cannot override 'Public Overridable Function M5() As (c As (a As Integer, b As Integer), d As Integer)' because they differ by their tuple element names. Public Overrides Function M5() As (c As (notA As Integer, notB As Integer), d As Integer) ~~ </errors>) Dim m3 = comp.GetMember(Of MethodSymbol)("Derived.M3").ReturnType Assert.Equal("(notA As System.Int32, notB As System.Int32)()", m3.ToTestDisplayString()) Assert.Equal({"System.Collections.Generic.IList(Of (notA As System.Int32, notB As System.Int32))"}, m3.Interfaces.SelectAsArray(Function(t) t.ToTestDisplayString())) End Sub <Fact> Public Sub OverriddenMethodWithNoTupleNamesInReturn() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Base Public Overridable Function M6() As (a As Integer, b As Integer) Return (1, 2) End Function End Class Public Class Derived Inherits Base Public Overrides Function M6() As (Integer, Integer) Return (1, 2) End Function Sub M() Dim result = Me.M6() Dim result2 = MyBase.M6() System.Console.Write(result.a) System.Console.Write(result2.a) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30456: 'a' is not a member of '(Integer, Integer)'. System.Console.Write(result.a) ~~~~~~~~ </errors>) Dim m6 = comp.GetMember(Of MethodSymbol)("Derived.M6").ReturnType Assert.Equal("(System.Int32, System.Int32)", m6.ToTestDisplayString()) Dim tree = comp.SyntaxTrees.First() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim invocation = nodes.OfType(Of InvocationExpressionSyntax)().ElementAt(0) Assert.Equal("Me.M6()", invocation.ToString()) Assert.Equal("Function Derived.M6() As (System.Int32, System.Int32)", model.GetSymbolInfo(invocation).Symbol.ToTestDisplayString()) Dim invocation2 = nodes.OfType(Of InvocationExpressionSyntax)().ElementAt(1) Assert.Equal("MyBase.M6()", invocation2.ToString()) Assert.Equal("Function Base.M6() As (a As System.Int32, b As System.Int32)", model.GetSymbolInfo(invocation2).Symbol.ToTestDisplayString()) End Sub <Fact> Public Sub OverriddenMethodWithDifferentTupleNamesInReturnUsingTypeArg() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Base Public Overridable Function M1(Of T)() As (a As T, b As T) Return (Nothing, Nothing) End Function Public Overridable Function M2(Of T)() As (a As T, b As T) Return (Nothing, Nothing) End Function Public Overridable Function M3(Of T)() As (a As T, b As T)() Return {(Nothing, Nothing)} End Function Public Overridable Function M4(Of T)() As (a As T, b As T)? Return (Nothing, Nothing) End Function Public Overridable Function M5(Of T)() As (c As (a As T, b As T), d As T) Return ((Nothing, Nothing), Nothing) End Function End Class Public Class Derived Inherits Base Public Overrides Function M1(Of T)() As (A As T, B As T) Return (Nothing, Nothing) End Function Public Overrides Function M2(Of T)() As (notA As T, notB As T) Return (Nothing, Nothing) End Function Public Overrides Function M3(Of T)() As (notA As T, notB As T)() Return {(Nothing, Nothing)} End Function Public Overrides Function M4(Of T)() As (notA As T, notB As T)? Return (Nothing, Nothing) End Function Public Overrides Function M5(Of T)() As (c As (notA As T, notB As T), d As T) Return ((Nothing, Nothing), Nothing) End Function End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC40001: 'Public Overrides Function M2(Of T)() As (notA As T, notB As T)' cannot override 'Public Overridable Function M2(Of T)() As (a As T, b As T)' because they differ by their tuple element names. Public Overrides Function M2(Of T)() As (notA As T, notB As T) ~~ BC40001: 'Public Overrides Function M3(Of T)() As (notA As T, notB As T)()' cannot override 'Public Overridable Function M3(Of T)() As (a As T, b As T)()' because they differ by their tuple element names. Public Overrides Function M3(Of T)() As (notA As T, notB As T)() ~~ BC40001: 'Public Overrides Function M4(Of T)() As (notA As T, notB As T)?' cannot override 'Public Overridable Function M4(Of T)() As (a As T, b As T)?' because they differ by their tuple element names. Public Overrides Function M4(Of T)() As (notA As T, notB As T)? ~~ BC40001: 'Public Overrides Function M5(Of T)() As (c As (notA As T, notB As T), d As T)' cannot override 'Public Overridable Function M5(Of T)() As (c As (a As T, b As T), d As T)' because they differ by their tuple element names. Public Overrides Function M5(Of T)() As (c As (notA As T, notB As T), d As T) ~~ </errors>) End Sub <Fact> Public Sub OverriddenMethodWithDifferentTupleNamesInParameters() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Base Public Overridable Sub M1(x As (a As Integer, b As Integer)) End Sub Public Overridable Sub M2(x As (a As Integer, b As Integer)) End Sub Public Overridable Sub M3(x As (a As Integer, b As Integer)()) End Sub Public Overridable Sub M4(x As (a As Integer, b As Integer)?) End Sub Public Overridable Sub M5(x As (c As (a As Integer, b As Integer), d As Integer)) End Sub End Class Public Class Derived Inherits Base Public Overrides Sub M1(x As (A As Integer, B As Integer)) End Sub Public Overrides Sub M2(x As (notA As Integer, notB As Integer)) End Sub Public Overrides Sub M3(x As (notA As Integer, notB As Integer)()) End Sub Public Overrides Sub M4(x As (notA As Integer, notB As Integer)?) End Sub Public Overrides Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer)) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC40001: 'Public Overrides Sub M2(x As (notA As Integer, notB As Integer))' cannot override 'Public Overridable Sub M2(x As (a As Integer, b As Integer))' because they differ by their tuple element names. Public Overrides Sub M2(x As (notA As Integer, notB As Integer)) ~~ BC40001: 'Public Overrides Sub M3(x As (notA As Integer, notB As Integer)())' cannot override 'Public Overridable Sub M3(x As (a As Integer, b As Integer)())' because they differ by their tuple element names. Public Overrides Sub M3(x As (notA As Integer, notB As Integer)()) ~~ BC40001: 'Public Overrides Sub M4(x As (notA As Integer, notB As Integer)?)' cannot override 'Public Overridable Sub M4(x As (a As Integer, b As Integer)?)' because they differ by their tuple element names. Public Overrides Sub M4(x As (notA As Integer, notB As Integer)?) ~~ BC40001: 'Public Overrides Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer))' cannot override 'Public Overridable Sub M5(x As (c As (a As Integer, b As Integer), d As Integer))' because they differ by their tuple element names. Public Overrides Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer)) ~~ </errors>) End Sub <Fact> Public Sub OverriddenMethodWithDifferentTupleNamesInParametersUsingTypeArg() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Base Public Overridable Sub M1(Of T)(x As (a As T, b As T)) End Sub Public Overridable Sub M2(Of T)(x As (a As T, b As T)) End Sub Public Overridable Sub M3(Of T)(x As (a As T, b As T)()) End Sub Public Overridable Sub M4(Of T)(x As (a As T, b As T)?) End Sub Public Overridable Sub M5(Of T)(x As (c As (a As T, b As T), d As T)) End Sub End Class Public Class Derived Inherits Base Public Overrides Sub M1(Of T)(x As (A As T, B As T)) End Sub Public Overrides Sub M2(Of T)(x As (notA As T, notB As T)) End Sub Public Overrides Sub M3(Of T)(x As (notA As T, notB As T)()) End Sub Public Overrides Sub M4(Of T)(x As (notA As T, notB As T)?) End Sub Public Overrides Sub M5(Of T)(x As (c As (notA As T, notB As T), d As T)) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC40001: 'Public Overrides Sub M2(Of T)(x As (notA As T, notB As T))' cannot override 'Public Overridable Sub M2(Of T)(x As (a As T, b As T))' because they differ by their tuple element names. Public Overrides Sub M2(Of T)(x As (notA As T, notB As T)) ~~ BC40001: 'Public Overrides Sub M3(Of T)(x As (notA As T, notB As T)())' cannot override 'Public Overridable Sub M3(Of T)(x As (a As T, b As T)())' because they differ by their tuple element names. Public Overrides Sub M3(Of T)(x As (notA As T, notB As T)()) ~~ BC40001: 'Public Overrides Sub M4(Of T)(x As (notA As T, notB As T)?)' cannot override 'Public Overridable Sub M4(Of T)(x As (a As T, b As T)?)' because they differ by their tuple element names. Public Overrides Sub M4(Of T)(x As (notA As T, notB As T)?) ~~ BC40001: 'Public Overrides Sub M5(Of T)(x As (c As (notA As T, notB As T), d As T))' cannot override 'Public Overridable Sub M5(Of T)(x As (c As (a As T, b As T), d As T))' because they differ by their tuple element names. Public Overrides Sub M5(Of T)(x As (c As (notA As T, notB As T), d As T)) ~~ </errors>) End Sub <Fact> Public Sub HiddenMethodsWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Base Public Overridable Function M1() As (a As Integer, b As Integer) Return (1, 2) End Function Public Overridable Function M2() As (a As Integer, b As Integer) Return (1, 2) End Function Public Overridable Function M3() As (a As Integer, b As Integer)() Return {(1, 2)} End Function Public Overridable Function M4() As (a As Integer, b As Integer)? Return (1, 2) End Function Public Overridable Function M5() As (c As (a As Integer, b As Integer), d As Integer) Return ((1, 2), 3) End Function End Class Public Class Derived Inherits Base Public Function M1() As (A As Integer, B As Integer) Return (1, 2) End Function Public Function M2() As (notA As Integer, notB As Integer) Return (1, 2) End Function Public Function M3() As (notA As Integer, notB As Integer)() Return {(1, 2)} End Function Public Function M4() As (notA As Integer, notB As Integer)? Return (1, 2) End Function Public Function M5() As (c As (notA As Integer, notB As Integer), d As Integer) Return ((1, 2), 3) End Function End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC40005: function 'M1' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'. Public Function M1() As (A As Integer, B As Integer) ~~ BC40005: function 'M2' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'. Public Function M2() As (notA As Integer, notB As Integer) ~~ BC40005: function 'M3' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'. Public Function M3() As (notA As Integer, notB As Integer)() ~~ BC40005: function 'M4' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'. Public Function M4() As (notA As Integer, notB As Integer)? ~~ BC40005: function 'M5' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'. Public Function M5() As (c As (notA As Integer, notB As Integer), d As Integer) ~~ </errors>) End Sub <Fact> Public Sub DuplicateMethodDetectionWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Public Sub M1(x As (A As Integer, B As Integer)) End Sub Public Sub M1(x As (a As Integer, b As Integer)) End Sub Public Sub M2(x As (noIntegerA As Integer, noIntegerB As Integer)) End Sub Public Sub M2(x As (a As Integer, b As Integer)) End Sub Public Sub M3(x As (notA As Integer, notB As Integer)()) End Sub Public Sub M3(x As (a As Integer, b As Integer)()) End Sub Public Sub M4(x As (notA As Integer, notB As Integer)?) End Sub Public Sub M4(x As (a As Integer, b As Integer)?) End Sub Public Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer)) End Sub Public Sub M5(x As (c As (a As Integer, b As Integer), d As Integer)) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30269: 'Public Sub M1(x As (A As Integer, B As Integer))' has multiple definitions with identical signatures. Public Sub M1(x As (A As Integer, B As Integer)) ~~ BC37271: 'Public Sub M2(x As (noIntegerA As Integer, noIntegerB As Integer))' has multiple definitions with identical signatures with different tuple element names, including 'Public Sub M2(x As (a As Integer, b As Integer))'. Public Sub M2(x As (noIntegerA As Integer, noIntegerB As Integer)) ~~ BC37271: 'Public Sub M3(x As (notA As Integer, notB As Integer)())' has multiple definitions with identical signatures with different tuple element names, including 'Public Sub M3(x As (a As Integer, b As Integer)())'. Public Sub M3(x As (notA As Integer, notB As Integer)()) ~~ BC37271: 'Public Sub M4(x As (notA As Integer, notB As Integer)?)' has multiple definitions with identical signatures with different tuple element names, including 'Public Sub M4(x As (a As Integer, b As Integer)?)'. Public Sub M4(x As (notA As Integer, notB As Integer)?) ~~ BC37271: 'Public Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer))' has multiple definitions with identical signatures with different tuple element names, including 'Public Sub M5(x As (c As (a As Integer, b As Integer), d As Integer))'. Public Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer)) ~~ </errors>) End Sub <Fact> Public Sub HiddenMethodParametersWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Base Public Overridable Sub M1(x As (a As Integer, b As Integer)) End Sub Public Overridable Sub M2(x As (a As Integer, b As Integer)) End Sub Public Overridable Sub M3(x As (a As Integer, b As Integer)()) End Sub Public Overridable Sub M4(x As (a As Integer, b As Integer)?) End Sub Public Overridable Sub M5(x As (c As (a As Integer, b As Integer), d As Integer)) End Sub End Class Public Class Derived Inherits Base Public Sub M1(x As (A As Integer, B As Integer)) End Sub Public Sub M2(x As (notA As Integer, notB As Integer)) End Sub Public Sub M3(x As (notA As Integer, notB As Integer)()) End Sub Public Sub M4(x As (notA As Integer, notB As Integer)?) End Sub Public Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer)) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC40005: sub 'M1' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'. Public Sub M1(x As (A As Integer, B As Integer)) ~~ BC40005: sub 'M2' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'. Public Sub M2(x As (notA As Integer, notB As Integer)) ~~ BC40005: sub 'M3' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'. Public Sub M3(x As (notA As Integer, notB As Integer)()) ~~ BC40005: sub 'M4' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'. Public Sub M4(x As (notA As Integer, notB As Integer)?) ~~ BC40005: sub 'M5' shadows an overridable method in the base class 'Base'. To override the base method, this method must be declared 'Overrides'. Public Sub M5(x As (c As (notA As Integer, notB As Integer), d As Integer)) ~~ </errors>) End Sub <Fact> Public Sub ExplicitInterfaceImplementationWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Interface I0 Sub M1(x As (Integer, (Integer, c As Integer))) Sub M2(x As (a As Integer, (b As Integer, c As Integer))) Function MR1() As (Integer, (Integer, c As Integer)) Function MR2() As (a As Integer, (b As Integer, c As Integer)) End Interface Public Class Derived Implements I0 Public Sub M1(x As (notMissing As Integer, (notMissing As Integer, c As Integer))) Implements I0.M1 End Sub Public Sub M2(x As (notA As Integer, (notB As Integer, c As Integer))) Implements I0.M2 End Sub Public Function MR1() As (notMissing As Integer, (notMissing As Integer, c As Integer)) Implements I0.MR1 Return (1, (2, 3)) End Function Public Function MR2() As (notA As Integer, (notB As Integer, c As Integer)) Implements I0.MR2 Return (1, (2, 3)) End Function End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30402: 'M1' cannot implement sub 'M1' on interface 'I0' because the tuple element names in 'Public Sub M1(x As (notMissing As Integer, (notMissing As Integer, c As Integer)))' do not match those in 'Sub M1(x As (Integer, (Integer, c As Integer)))'. Public Sub M1(x As (notMissing As Integer, (notMissing As Integer, c As Integer))) Implements I0.M1 ~~~~~ BC30402: 'M2' cannot implement sub 'M2' on interface 'I0' because the tuple element names in 'Public Sub M2(x As (notA As Integer, (notB As Integer, c As Integer)))' do not match those in 'Sub M2(x As (a As Integer, (b As Integer, c As Integer)))'. Public Sub M2(x As (notA As Integer, (notB As Integer, c As Integer))) Implements I0.M2 ~~~~~ BC30402: 'MR1' cannot implement function 'MR1' on interface 'I0' because the tuple element names in 'Public Function MR1() As (notMissing As Integer, (notMissing As Integer, c As Integer))' do not match those in 'Function MR1() As (Integer, (Integer, c As Integer))'. Public Function MR1() As (notMissing As Integer, (notMissing As Integer, c As Integer)) Implements I0.MR1 ~~~~~~ BC30402: 'MR2' cannot implement function 'MR2' on interface 'I0' because the tuple element names in 'Public Function MR2() As (notA As Integer, (notB As Integer, c As Integer))' do not match those in 'Function MR2() As (a As Integer, (b As Integer, c As Integer))'. Public Function MR2() As (notA As Integer, (notB As Integer, c As Integer)) Implements I0.MR2 ~~~~~~ </errors>) End Sub <Fact> Public Sub InterfaceImplementationOfPropertyWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Interface I0 Property P1 As (a As Integer, b As Integer) Property P2 As (Integer, b As Integer) End Interface Public Class Derived Implements I0 Public Property P1 As (notA As Integer, notB As Integer) Implements I0.P1 Public Property P2 As (notMissing As Integer, b As Integer) Implements I0.P2 End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30402: 'P1' cannot implement property 'P1' on interface 'I0' because the tuple element names in 'Public Property P1 As (notA As Integer, notB As Integer)' do not match those in 'Property P1 As (a As Integer, b As Integer)'. Public Property P1 As (notA As Integer, notB As Integer) Implements I0.P1 ~~~~~ BC30402: 'P2' cannot implement property 'P2' on interface 'I0' because the tuple element names in 'Public Property P2 As (notMissing As Integer, b As Integer)' do not match those in 'Property P2 As (Integer, b As Integer)'. Public Property P2 As (notMissing As Integer, b As Integer) Implements I0.P2 ~~~~~ </errors>) End Sub <Fact> Public Sub InterfaceImplementationOfEventWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Interface I0 Event E1 As Action(Of (a As Integer, b As Integer)) Event E2 As Action(Of (Integer, b As Integer)) End Interface Public Class Derived Implements I0 Public Event E1 As Action(Of (notA As Integer, notB As Integer)) Implements I0.E1 Public Event E2 As Action(Of (notMissing As Integer, notB As Integer)) Implements I0.E2 End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30402: 'E1' cannot implement event 'E1' on interface 'I0' because the tuple element names in 'Public Event E1 As Action(Of (notA As Integer, notB As Integer))' do not match those in 'Event E1 As Action(Of (a As Integer, b As Integer))'. Public Event E1 As Action(Of (notA As Integer, notB As Integer)) Implements I0.E1 ~~~~~ BC30402: 'E2' cannot implement event 'E2' on interface 'I0' because the tuple element names in 'Public Event E2 As Action(Of (notMissing As Integer, notB As Integer))' do not match those in 'Event E2 As Action(Of (Integer, b As Integer))'. Public Event E2 As Action(Of (notMissing As Integer, notB As Integer)) Implements I0.E2 ~~~~~ </errors>) End Sub <Fact> Public Sub InterfaceHidingAnotherInterfaceWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Interface I0 Sub M1(x As (a As Integer, b As Integer)) Sub M2(x As (a As Integer, b As Integer)) Function MR1() As (a As Integer, b As Integer) Function MR2() As (a As Integer, b As Integer) End Interface Public Interface I1 Inherits I0 Sub M1(x As (notA As Integer, b As Integer)) Shadows Sub M2(x As (notA As Integer, b As Integer)) Function MR1() As (notA As Integer, b As Integer) Shadows Function MR2() As (notA As Integer, b As Integer) End Interface </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC40003: sub 'M1' shadows an overloadable member declared in the base interface 'I0'. If you want to overload the base method, this method must be declared 'Overloads'. Sub M1(x As (notA As Integer, b As Integer)) ~~ BC40003: function 'MR1' shadows an overloadable member declared in the base interface 'I0'. If you want to overload the base method, this method must be declared 'Overloads'. Function MR1() As (notA As Integer, b As Integer) ~~~ </errors>) End Sub <Fact> Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Interface I0(Of T) End Interface Public Class C1 Implements I0(Of (a As Integer, b As Integer)), I0(Of (notA As Integer, notB As Integer)) End Class Public Class C2 Implements I0(Of (a As Integer, b As Integer)), I0(Of (a As Integer, b As Integer)) End Class Public Class C3 Implements I0(Of Integer), I0(Of Integer) End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37272: Interface 'I0(Of (notA As Integer, notB As Integer))' can be implemented only once by this type, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))'. Implements I0(Of (a As Integer, b As Integer)), I0(Of (notA As Integer, notB As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31033: Interface 'I0(Of (a As Integer, b As Integer))' can be implemented only once by this type. Implements I0(Of (a As Integer, b As Integer)), I0(Of (a As Integer, b As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31033: Interface 'I0(Of Integer)' can be implemented only once by this type. Implements I0(Of Integer), I0(Of Integer) ~~~~~~~~~~~~~~ </errors>) Dim tree = comp.SyntaxTrees.First() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim c1 = model.GetDeclaredSymbol(nodes.OfType(Of TypeBlockSyntax)().ElementAt(1)) Assert.Equal("C1", c1.Name) Assert.Equal(2, c1.AllInterfaces.Count) Assert.Equal("I0(Of (a As System.Int32, b As System.Int32))", c1.AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I0(Of (notA As System.Int32, notB As System.Int32))", c1.AllInterfaces(1).ToTestDisplayString()) Dim c2 = model.GetDeclaredSymbol(nodes.OfType(Of TypeBlockSyntax)().ElementAt(2)) Assert.Equal("C2", c2.Name) Assert.Equal(1, c2.AllInterfaces.Count) Assert.Equal("I0(Of (a As System.Int32, b As System.Int32))", c2.AllInterfaces(0).ToTestDisplayString()) Dim c3 = model.GetDeclaredSymbol(nodes.OfType(Of TypeBlockSyntax)().ElementAt(3)) Assert.Equal("C3", c3.Name) Assert.Equal(1, c3.AllInterfaces.Count) Assert.Equal("I0(Of System.Int32)", c3.AllInterfaces(0).ToTestDisplayString()) End Sub <Fact> Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames_02() Dim comp = CreateCompilation( <compilation> <file name="a.vb"> public interface I1(Of T) Sub M() end interface public interface I2 Inherits I1(Of (a As Integer, b As Integer)) end interface public interface I3 Inherits I1(Of (c As Integer, d As Integer)) end interface public class C1 Implements I2, I1(Of (c As Integer, d As Integer)) Sub M_1() Implements I1(Of (a As Integer, b As Integer)).M End Sub Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C1 End Sub End class public class C2 Implements I1(Of (c As Integer, d As Integer)), I2 Sub M_1() Implements I1(Of (a As Integer, b As Integer)).M End Sub Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C2 End Sub End class public class C3 Implements I1(Of (a As Integer, b As Integer)), I1(Of (c As Integer, d As Integer)) Sub M_1() Implements I1(Of (a As Integer, b As Integer)).M End Sub Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C3 End Sub End class public class C4 Implements I2, I3 Sub M_1() Implements I1(Of (a As Integer, b As Integer)).M End Sub Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C4 End Sub End class </file> </compilation> ) comp.AssertTheseDiagnostics( <errors> BC37273: Interface 'I1(Of (c As Integer, d As Integer))' can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (a As Integer, b As Integer))' (via 'I2'). Implements I2, I1(Of (c As Integer, d As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30583: 'I1(Of (c As Integer, d As Integer)).M' cannot be implemented more than once. Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37274: Interface 'I1(Of (a As Integer, b As Integer))' (via 'I2') can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (c As Integer, d As Integer))'. Implements I1(Of (c As Integer, d As Integer)), I2 ~~ BC30583: 'I1(Of (c As Integer, d As Integer)).M' cannot be implemented more than once. Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37272: Interface 'I1(Of (c As Integer, d As Integer))' can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (a As Integer, b As Integer))'. Implements I1(Of (a As Integer, b As Integer)), I1(Of (c As Integer, d As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30583: 'I1(Of (c As Integer, d As Integer)).M' cannot be implemented more than once. Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37275: Interface 'I1(Of (c As Integer, d As Integer))' (via 'I3') can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (a As Integer, b As Integer))' (via 'I2'). Implements I2, I3 ~~ BC30583: 'I1(Of (c As Integer, d As Integer)).M' cannot be implemented more than once. Sub M_2() Implements I1(Of (c As Integer, d As Integer)).M ' C4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) Dim c1 As INamedTypeSymbol = comp.GetTypeByMetadataName("C1") Dim c1Interfaces = c1.Interfaces Dim c1AllInterfaces = c1.AllInterfaces Assert.Equal(2, c1Interfaces.Length) Assert.Equal(3, c1AllInterfaces.Length) Assert.Equal("I2", c1Interfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c1Interfaces(1).ToTestDisplayString()) Assert.Equal("I2", c1AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c1AllInterfaces(1).ToTestDisplayString()) Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c1AllInterfaces(2).ToTestDisplayString()) DuplicateInterfaceDetectionWithDifferentTupleNames_02_AssertExplicitInterfaceImplementations(c1) Dim c2 As INamedTypeSymbol = comp.GetTypeByMetadataName("C2") Dim c2Interfaces = c2.Interfaces Dim c2AllInterfaces = c2.AllInterfaces Assert.Equal(2, c2Interfaces.Length) Assert.Equal(3, c2AllInterfaces.Length) Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c2Interfaces(0).ToTestDisplayString()) Assert.Equal("I2", c2Interfaces(1).ToTestDisplayString()) Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c2AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I2", c2AllInterfaces(1).ToTestDisplayString()) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c2AllInterfaces(2).ToTestDisplayString()) DuplicateInterfaceDetectionWithDifferentTupleNames_02_AssertExplicitInterfaceImplementations(c2) Dim c3 As INamedTypeSymbol = comp.GetTypeByMetadataName("C3") Dim c3Interfaces = c3.Interfaces Dim c3AllInterfaces = c3.AllInterfaces Assert.Equal(2, c3Interfaces.Length) Assert.Equal(2, c3AllInterfaces.Length) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c3Interfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c3Interfaces(1).ToTestDisplayString()) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c3AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c3AllInterfaces(1).ToTestDisplayString()) DuplicateInterfaceDetectionWithDifferentTupleNames_02_AssertExplicitInterfaceImplementations(c3) Dim c4 As INamedTypeSymbol = comp.GetTypeByMetadataName("C4") Dim c4Interfaces = c4.Interfaces Dim c4AllInterfaces = c4.AllInterfaces Assert.Equal(2, c4Interfaces.Length) Assert.Equal(4, c4AllInterfaces.Length) Assert.Equal("I2", c4Interfaces(0).ToTestDisplayString()) Assert.Equal("I3", c4Interfaces(1).ToTestDisplayString()) Assert.Equal("I2", c4AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c4AllInterfaces(1).ToTestDisplayString()) Assert.Equal("I3", c4AllInterfaces(2).ToTestDisplayString()) Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c4AllInterfaces(3).ToTestDisplayString()) DuplicateInterfaceDetectionWithDifferentTupleNames_02_AssertExplicitInterfaceImplementations(c4) End Sub Private Shared Sub DuplicateInterfaceDetectionWithDifferentTupleNames_02_AssertExplicitInterfaceImplementations(c As INamedTypeSymbol) Dim cMabImplementations = DirectCast(DirectCast(c, TypeSymbol).GetMember("M_1"), IMethodSymbol).ExplicitInterfaceImplementations Assert.Equal(1, cMabImplementations.Length) Assert.Equal("Sub I1(Of (a As System.Int32, b As System.Int32)).M()", cMabImplementations(0).ToTestDisplayString()) Dim cMcdImplementations = DirectCast(DirectCast(c, TypeSymbol).GetMember("M_2"), IMethodSymbol).ExplicitInterfaceImplementations Assert.Equal(1, cMcdImplementations.Length) Assert.Equal("Sub I1(Of (c As System.Int32, d As System.Int32)).M()", cMcdImplementations(0).ToTestDisplayString()) End Sub <Fact> Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames_03() Dim comp = CreateCompilation( <compilation> <file name="a.vb"> public interface I1(Of T) Sub M() end interface public class C1 Implements I1(Of (a As Integer, b As Integer)) Sub M() Implements I1(Of (a As Integer, b As Integer)).M System.Console.WriteLine("C1.M") End Sub End class public class C2 Inherits C1 Implements I1(Of (c As Integer, d As Integer)) Overloads Sub M() Implements I1(Of (c As Integer, d As Integer)).M System.Console.WriteLine("C2.M") End Sub Shared Sub Main() Dim x As C1 = new C2() Dim y As I1(Of (a As Integer, b As Integer)) = x y.M() End Sub End class </file> </compilation>, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics() Dim validate As Action(Of ModuleSymbol) = Sub(m) Dim isMetadata As Boolean = TypeOf m Is PEModuleSymbol Dim c1 As INamedTypeSymbol = m.GlobalNamespace.GetTypeMember("C1") Dim c1Interfaces = c1.Interfaces Dim c1AllInterfaces = c1.AllInterfaces Assert.Equal(1, c1Interfaces.Length) Assert.Equal(1, c1AllInterfaces.Length) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c1Interfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c1AllInterfaces(0).ToTestDisplayString()) Dim c2 As INamedTypeSymbol = m.GlobalNamespace.GetTypeMember("C2") Dim c2Interfaces = c2.Interfaces Dim c2AllInterfaces = c2.AllInterfaces Assert.Equal(1, c2Interfaces.Length) Assert.Equal(2, c2AllInterfaces.Length) Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c2Interfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c2AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c2AllInterfaces(1).ToTestDisplayString()) Dim m2 = DirectCast(DirectCast(c2, TypeSymbol).GetMember("M"), IMethodSymbol) Dim m2Implementations = m2.ExplicitInterfaceImplementations Assert.Equal(1, m2Implementations.Length) Assert.Equal(If(isMetadata, "Sub I1(Of (System.Int32, System.Int32)).M()", "Sub I1(Of (c As System.Int32, d As System.Int32)).M()"), m2Implementations(0).ToTestDisplayString()) Assert.Same(m2, c2.FindImplementationForInterfaceMember(DirectCast(c2Interfaces(0), TypeSymbol).GetMember("M"))) Assert.Same(m2, c2.FindImplementationForInterfaceMember(DirectCast(c1Interfaces(0), TypeSymbol).GetMember("M"))) End Sub CompileAndVerify(comp, sourceSymbolValidator:=validate, symbolValidator:=validate, expectedOutput:="C2.M") End Sub <Fact> Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames_04() Dim csSource = " public interface I1<T> { void M(); } public class C1 : I1<(int a, int b)> { public void M() => System.Console.WriteLine(""C1.M""); } public class C2 : C1, I1<(int c, int d)> { new public void M() => System.Console.WriteLine(""C2.M""); } " Dim csComp = CreateCSharpCompilation(csSource, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedAssemblies:=TargetFrameworkUtil.GetReferences(TargetFramework.StandardAndVBRuntime)) csComp.VerifyDiagnostics() Dim comp = CreateCompilation( <compilation> <file name="a.vb"> public class C3 Shared Sub Main() Dim x As C1 = new C2() Dim y As I1(Of (a As Integer, b As Integer)) = x y.M() End Sub End class </file> </compilation>, options:=TestOptions.DebugExe, references:={csComp.EmitToImageReference()}) comp.AssertTheseDiagnostics() CompileAndVerify(comp, expectedOutput:="C2.M") Dim c1 As INamedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C1") Dim c1Interfaces = c1.Interfaces Dim c1AllInterfaces = c1.AllInterfaces Assert.Equal(1, c1Interfaces.Length) Assert.Equal(1, c1AllInterfaces.Length) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c1Interfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c1AllInterfaces(0).ToTestDisplayString()) Dim c2 As INamedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C2") Dim c2Interfaces = c2.Interfaces Dim c2AllInterfaces = c2.AllInterfaces Assert.Equal(1, c2Interfaces.Length) Assert.Equal(2, c2AllInterfaces.Length) Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c2Interfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c2AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (c As System.Int32, d As System.Int32))", c2AllInterfaces(1).ToTestDisplayString()) Dim m2 = DirectCast(DirectCast(c2, TypeSymbol).GetMember("M"), IMethodSymbol) Dim m2Implementations = m2.ExplicitInterfaceImplementations Assert.Equal(0, m2Implementations.Length) Assert.Same(m2, c2.FindImplementationForInterfaceMember(DirectCast(c2Interfaces(0), TypeSymbol).GetMember("M"))) Assert.Same(m2, c2.FindImplementationForInterfaceMember(DirectCast(c1Interfaces(0), TypeSymbol).GetMember("M"))) End Sub <Fact> Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames_05() Dim comp = CreateCompilation( <compilation> <file name="a.vb"> public interface I1(Of T) Sub M() end interface public interface I2(Of I2T) Inherits I1(Of (a As I2T, b As I2T)) end interface public interface I3(Of I3T) Inherits I1(Of (c As I3T, d As I3T)) end interface public class C1(Of T) Implements I2(Of T), I1(Of (c As T, d As T)) Sub M_1() Implements I1(Of (a As T, b As T)).M End Sub Sub M_2() Implements I1(Of (c As T, d As T)).M ' C1 End Sub End class public class C2(Of T) Implements I1(Of (c As T, d As T)), I2(Of T) Sub M_1() Implements I1(Of (a As T, b As T)).M End Sub Sub M_2() Implements I1(Of (c As T, d As T)).M ' C2 End Sub End class public class C3(Of T) Implements I1(Of (a As T, b As T)), I1(Of (c As T, d As T)) Sub M_1() Implements I1(Of (a As T, b As T)).M End Sub Sub M_2() Implements I1(Of (c As T, d As T)).M ' C3 End Sub End class public class C4(Of T) Implements I2(Of T), I3(Of T) Sub M_1() Implements I1(Of (a As T, b As T)).M End Sub Sub M_2() Implements I1(Of (c As T, d As T)).M ' C4 End Sub End class </file> </compilation> ) comp.AssertTheseDiagnostics( <errors> BC37273: Interface 'I1(Of (c As T, d As T))' can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (a As T, b As T))' (via 'I2(Of T)'). Implements I2(Of T), I1(Of (c As T, d As T)) ~~~~~~~~~~~~~~~~~~~~~~~ BC30583: 'I1(Of (c As T, d As T)).M' cannot be implemented more than once. Sub M_2() Implements I1(Of (c As T, d As T)).M ' C1 ~~~~~~~~~~~~~~~~~~~~~~~~~ BC37274: Interface 'I1(Of (a As T, b As T))' (via 'I2(Of T)') can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (c As T, d As T))'. Implements I1(Of (c As T, d As T)), I2(Of T) ~~~~~~~~ BC30583: 'I1(Of (c As T, d As T)).M' cannot be implemented more than once. Sub M_2() Implements I1(Of (c As T, d As T)).M ' C2 ~~~~~~~~~~~~~~~~~~~~~~~~~ BC37272: Interface 'I1(Of (c As T, d As T))' can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (a As T, b As T))'. Implements I1(Of (a As T, b As T)), I1(Of (c As T, d As T)) ~~~~~~~~~~~~~~~~~~~~~~~ BC30583: 'I1(Of (c As T, d As T)).M' cannot be implemented more than once. Sub M_2() Implements I1(Of (c As T, d As T)).M ' C3 ~~~~~~~~~~~~~~~~~~~~~~~~~ BC37275: Interface 'I1(Of (c As T, d As T))' (via 'I3(Of T)') can be implemented only once by this type, but already appears with different tuple element names, as 'I1(Of (a As T, b As T))' (via 'I2(Of T)'). Implements I2(Of T), I3(Of T) ~~~~~~~~ BC30583: 'I1(Of (c As T, d As T)).M' cannot be implemented more than once. Sub M_2() Implements I1(Of (c As T, d As T)).M ' C4 ~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) Dim c1 As INamedTypeSymbol = comp.GetTypeByMetadataName("C1`1") Dim c1Interfaces = c1.Interfaces Dim c1AllInterfaces = c1.AllInterfaces Assert.Equal(2, c1Interfaces.Length) Assert.Equal(3, c1AllInterfaces.Length) Assert.Equal("I2(Of T)", c1Interfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (c As T, d As T))", c1Interfaces(1).ToTestDisplayString()) Assert.Equal("I2(Of T)", c1AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (a As T, b As T))", c1AllInterfaces(1).ToTestDisplayString()) Assert.Equal("I1(Of (c As T, d As T))", c1AllInterfaces(2).ToTestDisplayString()) DuplicateInterfaceDetectionWithDifferentTupleNames_05_AssertExplicitInterfaceImplementations(c1) Dim c2 As INamedTypeSymbol = comp.GetTypeByMetadataName("C2`1") Dim c2Interfaces = c2.Interfaces Dim c2AllInterfaces = c2.AllInterfaces Assert.Equal(2, c2Interfaces.Length) Assert.Equal(3, c2AllInterfaces.Length) Assert.Equal("I1(Of (c As T, d As T))", c2Interfaces(0).ToTestDisplayString()) Assert.Equal("I2(Of T)", c2Interfaces(1).ToTestDisplayString()) Assert.Equal("I1(Of (c As T, d As T))", c2AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I2(Of T)", c2AllInterfaces(1).ToTestDisplayString()) Assert.Equal("I1(Of (a As T, b As T))", c2AllInterfaces(2).ToTestDisplayString()) DuplicateInterfaceDetectionWithDifferentTupleNames_05_AssertExplicitInterfaceImplementations(c2) Dim c3 As INamedTypeSymbol = comp.GetTypeByMetadataName("C3`1") Dim c3Interfaces = c3.Interfaces Dim c3AllInterfaces = c3.AllInterfaces Assert.Equal(2, c3Interfaces.Length) Assert.Equal(2, c3AllInterfaces.Length) Assert.Equal("I1(Of (a As T, b As T))", c3Interfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (c As T, d As T))", c3Interfaces(1).ToTestDisplayString()) Assert.Equal("I1(Of (a As T, b As T))", c3AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (c As T, d As T))", c3AllInterfaces(1).ToTestDisplayString()) DuplicateInterfaceDetectionWithDifferentTupleNames_05_AssertExplicitInterfaceImplementations(c3) Dim c4 As INamedTypeSymbol = comp.GetTypeByMetadataName("C4`1") Dim c4Interfaces = c4.Interfaces Dim c4AllInterfaces = c4.AllInterfaces Assert.Equal(2, c4Interfaces.Length) Assert.Equal(4, c4AllInterfaces.Length) Assert.Equal("I2(Of T)", c4Interfaces(0).ToTestDisplayString()) Assert.Equal("I3(Of T)", c4Interfaces(1).ToTestDisplayString()) Assert.Equal("I2(Of T)", c4AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (a As T, b As T))", c4AllInterfaces(1).ToTestDisplayString()) Assert.Equal("I3(Of T)", c4AllInterfaces(2).ToTestDisplayString()) Assert.Equal("I1(Of (c As T, d As T))", c4AllInterfaces(3).ToTestDisplayString()) DuplicateInterfaceDetectionWithDifferentTupleNames_05_AssertExplicitInterfaceImplementations(c4) End Sub Private Shared Sub DuplicateInterfaceDetectionWithDifferentTupleNames_05_AssertExplicitInterfaceImplementations(c As INamedTypeSymbol) Dim cMabImplementations = DirectCast(DirectCast(c, TypeSymbol).GetMember("M_1"), IMethodSymbol).ExplicitInterfaceImplementations Assert.Equal(1, cMabImplementations.Length) Assert.Equal("Sub I1(Of (a As T, b As T)).M()", cMabImplementations(0).ToTestDisplayString()) Dim cMcdImplementations = DirectCast(DirectCast(c, TypeSymbol).GetMember("M_2"), IMethodSymbol).ExplicitInterfaceImplementations Assert.Equal(1, cMcdImplementations.Length) Assert.Equal("Sub I1(Of (c As T, d As T)).M()", cMcdImplementations(0).ToTestDisplayString()) End Sub <Fact> Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames_06() Dim comp = CreateCompilation( <compilation> <file name="a.vb"> public interface I1(Of T) Sub M() end interface public class C3(Of T, U) Implements I1(Of (a As T, b As T)), I1(Of (c As U, d As U)) Sub M_1() Implements I1(Of (a As T, b As T)).M End Sub Sub M_2() Implements I1(Of (c As U, d As U)).M End Sub End class </file> </compilation> ) comp.AssertTheseDiagnostics( <errors> BC32072: Cannot implement interface 'I1(Of (c As U, d As U))' because its implementation could conflict with the implementation of another implemented interface 'I1(Of (a As T, b As T))' for some type arguments. Implements I1(Of (a As T, b As T)), I1(Of (c As U, d As U)) ~~~~~~~~~~~~~~~~~~~~~~~ </errors>) Dim c3 As INamedTypeSymbol = comp.GetTypeByMetadataName("C3`2") Dim c3Interfaces = c3.Interfaces Dim c3AllInterfaces = c3.AllInterfaces Assert.Equal(2, c3Interfaces.Length) Assert.Equal(2, c3AllInterfaces.Length) Assert.Equal("I1(Of (a As T, b As T))", c3Interfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (c As U, d As U))", c3Interfaces(1).ToTestDisplayString()) Assert.Equal("I1(Of (a As T, b As T))", c3AllInterfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (c As U, d As U))", c3AllInterfaces(1).ToTestDisplayString()) Dim cMabImplementations = DirectCast(DirectCast(c3, TypeSymbol).GetMember("M_1"), IMethodSymbol).ExplicitInterfaceImplementations Assert.Equal(1, cMabImplementations.Length) Assert.Equal("Sub I1(Of (a As T, b As T)).M()", cMabImplementations(0).ToTestDisplayString()) Dim cMcdImplementations = DirectCast(DirectCast(c3, TypeSymbol).GetMember("M_2"), IMethodSymbol).ExplicitInterfaceImplementations Assert.Equal(1, cMcdImplementations.Length) Assert.Equal("Sub I1(Of (c As U, d As U)).M()", cMcdImplementations(0).ToTestDisplayString()) End Sub <Fact> Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames_07() Dim comp = CreateCompilation( <compilation> <file name="a.vb"> public interface I1(Of T) Sub M() end interface public class C3 Implements I1(Of (a As Integer, b As Integer)) Sub M() Implements I1(Of (c As Integer, d As Integer)).M End Sub End class public class C4 Implements I1(Of (c As Integer, d As Integer)) Sub M() Implements I1(Of (c As Integer, d As Integer)).M End Sub End class </file> </compilation> ) comp.AssertTheseDiagnostics( <errors> BC31035: Interface 'I1(Of (c As Integer, d As Integer))' is not implemented by this class. Sub M() Implements I1(Of (c As Integer, d As Integer)).M ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) Dim c3 As INamedTypeSymbol = comp.GetTypeByMetadataName("C3") Dim c3Interfaces = c3.Interfaces Dim c3AllInterfaces = c3.AllInterfaces Assert.Equal(1, c3Interfaces.Length) Assert.Equal(1, c3AllInterfaces.Length) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c3Interfaces(0).ToTestDisplayString()) Assert.Equal("I1(Of (a As System.Int32, b As System.Int32))", c3AllInterfaces(0).ToTestDisplayString()) Dim mImplementations = DirectCast(DirectCast(c3, TypeSymbol).GetMember("M"), IMethodSymbol).ExplicitInterfaceImplementations Assert.Equal(1, mImplementations.Length) Assert.Equal("Sub I1(Of (c As System.Int32, d As System.Int32)).M()", mImplementations(0).ToTestDisplayString()) Assert.Equal("Sub C3.M()", c3.FindImplementationForInterfaceMember(DirectCast(c3Interfaces(0), TypeSymbol).GetMember("M")).ToTestDisplayString()) Assert.Equal("Sub C3.M()", c3.FindImplementationForInterfaceMember(comp.GetTypeByMetadataName("C4").InterfacesNoUseSiteDiagnostics()(0).GetMember("M")).ToTestDisplayString()) End Sub <Fact> Public Sub AccessCheckLooksInsideTuples() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Public Function M() As (C2.C3, Integer) Throw New System.Exception() End Function End Class Public Class C2 Private Class C3 End Class End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30389: 'C2.C3' is not accessible in this context because it is 'Private'. Public Function M() As (C2.C3, Integer) ~~~~~ </errors>) End Sub <Fact> Public Sub AccessCheckLooksInsideTuples2() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Public Function M() As (C2, Integer) Throw New System.Exception() End Function Private Class C2 End Class End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) Dim expectedErrors = <errors><![CDATA[ BC30508: 'M' cannot expose type 'C.C2' in namespace '<Default>' through class 'C'. Public Function M() As (C2, Integer) ~~~~~~~~~~~~~ ]]></errors> comp.AssertTheseDiagnostics(expectedErrors) End Sub <Fact> Public Sub DuplicateInterfaceDetectionWithDifferentTupleNames2() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Interface I0(Of T) End Interface Public Class C2 Implements I0(Of (a As Integer, b As Integer)), I0(Of (a As Integer, b As Integer)) End Class Public Class C3 Implements I0(Of Integer), I0(Of Integer) End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC31033: Interface 'I0(Of (a As Integer, b As Integer))' can be implemented only once by this type. Implements I0(Of (a As Integer, b As Integer)), I0(Of (a As Integer, b As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31033: Interface 'I0(Of Integer)' can be implemented only once by this type. Implements I0(Of Integer), I0(Of Integer) ~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub ImplicitAndExplicitInterfaceImplementationWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Interface I0(Of T) Function Pop() As T Sub Push(x As T) End Interface Public Class C1 Implements I0(Of (a As Integer, b As Integer)) Public Function Pop() As (a As Integer, b As Integer) Implements I0(Of (a As Integer, b As Integer)).Pop Throw New Exception() End Function Public Sub Push(x As (a As Integer, b As Integer)) Implements I0(Of (a As Integer, b As Integer)).Push End Sub End Class Public Class C2 Inherits C1 Implements I0(Of (a As Integer, b As Integer)) Public Overloads Function Pop() As (notA As Integer, notB As Integer) Implements I0(Of (a As Integer, b As Integer)).Pop Throw New Exception() End Function Public Overloads Sub Push(x As (notA As Integer, notB As Integer)) Implements I0(Of (a As Integer, b As Integer)).Push End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30402: 'Pop' cannot implement function 'Pop' on interface 'I0(Of (a As Integer, b As Integer))' because the tuple element names in 'Public Overloads Function Pop() As (notA As Integer, notB As Integer)' do not match those in 'Function Pop() As (a As Integer, b As Integer)'. Public Overloads Function Pop() As (notA As Integer, notB As Integer) Implements I0(Of (a As Integer, b As Integer)).Pop ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30402: 'Push' cannot implement sub 'Push' on interface 'I0(Of (a As Integer, b As Integer))' because the tuple element names in 'Public Overloads Sub Push(x As (notA As Integer, notB As Integer))' do not match those in 'Sub Push(x As (a As Integer, b As Integer))'. Public Overloads Sub Push(x As (notA As Integer, notB As Integer)) Implements I0(Of (a As Integer, b As Integer)).Push ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub PartialMethodsWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Partial Class C1 Private Partial Sub M1(x As (a As Integer, b As Integer)) End Sub Private Partial Sub M2(x As (a As Integer, b As Integer)) End Sub Private Partial Sub M3(x As (a As Integer, b As Integer)) End Sub End Class Public Partial Class C1 Private Sub M1(x As (notA As Integer, notB As Integer)) End Sub Private Sub M2(x As (Integer, Integer)) End Sub Private Sub M3(x As (a As Integer, b As Integer)) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37271: 'Private Sub M1(x As (a As Integer, b As Integer))' has multiple definitions with identical signatures with different tuple element names, including 'Private Sub M1(x As (notA As Integer, notB As Integer))'. Private Partial Sub M1(x As (a As Integer, b As Integer)) ~~ BC37271: 'Private Sub M2(x As (a As Integer, b As Integer))' has multiple definitions with identical signatures with different tuple element names, including 'Private Sub M2(x As (Integer, Integer))'. Private Partial Sub M2(x As (a As Integer, b As Integer)) ~~ </errors>) End Sub <Fact> Public Sub PartialClassWithDifferentTupleNamesInBaseInterfaces() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Interface I0(Of T) End Interface Public Partial Class C Implements I0(Of (a As Integer, b As Integer)) End Class Public Partial Class C Implements I0(Of (notA As Integer, notB As Integer)) End Class Public Partial Class C Implements I0(Of (Integer, Integer)) End Class Public Partial Class D Implements I0(Of (a As Integer, b As Integer)) End Class Public Partial Class D Implements I0(Of (a As Integer, b As Integer)) End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37272: Interface 'I0(Of (notA As Integer, notB As Integer))' can be implemented only once by this type, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))'. Implements I0(Of (notA As Integer, notB As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37272: Interface 'I0(Of (Integer, Integer))' can be implemented only once by this type, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))'. Implements I0(Of (Integer, Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub PartialClassWithDifferentTupleNamesInBaseTypes() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Base(Of T) End Class Public Partial Class C1 Inherits Base(Of (a As Integer, b As Integer)) End Class Public Partial Class C1 Inherits Base(Of (notA As Integer, notB As Integer)) End Class Public Partial Class C2 Inherits Base(Of (a As Integer, b As Integer)) End Class Public Partial Class C2 Inherits Base(Of (Integer, Integer)) End Class Public Partial Class C3 Inherits Base(Of (a As Integer, b As Integer)) End Class Public Partial Class C3 Inherits Base(Of (a As Integer, b As Integer)) End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30928: Base class 'Base(Of (notA As Integer, notB As Integer))' specified for class 'C1' cannot be different from the base class 'Base(Of (a As Integer, b As Integer))' of one of its other partial types. Inherits Base(Of (notA As Integer, notB As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30928: Base class 'Base(Of (Integer, Integer))' specified for class 'C2' cannot be different from the base class 'Base(Of (a As Integer, b As Integer))' of one of its other partial types. Inherits Base(Of (Integer, Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub IndirectInterfaceBasesWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Interface I0(Of T) End Interface Public Interface I1 Inherits I0(Of (a As Integer, b As Integer)) End Interface Public Interface I2 Inherits I0(Of (notA As Integer, notB As Integer)) End Interface Public Interface I3 Inherits I0(Of (a As Integer, b As Integer)) End Interface Public Class C1 Implements I1, I3 End Class Public Class C2 Implements I0(Of (a As Integer, b As Integer)), I0(Of (notA As Integer, notB As Integer)) End Class Public Class C3 Implements I2, I0(Of (a As Integer, b As Integer)) End Class Public Class C4 Implements I0(Of (a As Integer, b As Integer)), I2 End Class Public Class C5 Implements I1, I2 End Class Public Interface I11 Inherits I0(Of (a As Integer, b As Integer)), I0(Of (notA As Integer, notB As Integer)) End Interface Public Interface I12 Inherits I2, I0(Of (a As Integer, b As Integer)) End Interface Public Interface I13 Inherits I0(Of (a As Integer, b As Integer)), I2 End Interface Public Interface I14 Inherits I1, I2 End Interface </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC37272: Interface 'I0(Of (notA As Integer, notB As Integer))' can be implemented only once by this type, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))'. Implements I0(Of (a As Integer, b As Integer)), I0(Of (notA As Integer, notB As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37273: Interface 'I0(Of (a As Integer, b As Integer))' can be implemented only once by this type, but already appears with different tuple element names, as 'I0(Of (notA As Integer, notB As Integer))' (via 'I2'). Implements I2, I0(Of (a As Integer, b As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37274: Interface 'I0(Of (notA As Integer, notB As Integer))' (via 'I2') can be implemented only once by this type, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))'. Implements I0(Of (a As Integer, b As Integer)), I2 ~~ BC37275: Interface 'I0(Of (notA As Integer, notB As Integer))' (via 'I2') can be implemented only once by this type, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))' (via 'I1'). Implements I1, I2 ~~ BC37276: Interface 'I0(Of (notA As Integer, notB As Integer))' can be inherited only once by this interface, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))'. Inherits I0(Of (a As Integer, b As Integer)), I0(Of (notA As Integer, notB As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37277: Interface 'I0(Of (a As Integer, b As Integer))' can be inherited only once by this interface, but already appears with different tuple element names, as 'I0(Of (notA As Integer, notB As Integer))' (via 'I2'). Inherits I2, I0(Of (a As Integer, b As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37278: Interface 'I0(Of (notA As Integer, notB As Integer))' (via 'I2') can be inherited only once by this interface, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))'. Inherits I0(Of (a As Integer, b As Integer)), I2 ~~ BC37279: Interface 'I0(Of (notA As Integer, notB As Integer))' (via 'I2') can be inherited only once by this interface, but already appears with different tuple element names, as 'I0(Of (a As Integer, b As Integer))' (via 'I1'). Inherits I1, I2 ~~ </errors>) End Sub <Fact> Public Sub InterfaceUnification() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Interface I0(Of T1) End Interface Public Class C1(Of T2) Implements I0(Of Integer), I0(Of T2) End Class Public Class C2(Of T2) Implements I0(Of (Integer, Integer)), I0(Of System.ValueTuple(Of T2, T2)) End Class Public Class C3(Of T2) Implements I0(Of (a As Integer, b As Integer)), I0(Of (T2, T2)) End Class Public Class C4(Of T2) Implements I0(Of (a As Integer, b As Integer)), I0(Of (a As T2, b As T2)) End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC32072: Cannot implement interface 'I0(Of T2)' because its implementation could conflict with the implementation of another implemented interface 'I0(Of Integer)' for some type arguments. Implements I0(Of Integer), I0(Of T2) ~~~~~~~~~ BC32072: Cannot implement interface 'I0(Of (T2, T2))' because its implementation could conflict with the implementation of another implemented interface 'I0(Of (Integer, Integer))' for some type arguments. Implements I0(Of (Integer, Integer)), I0(Of System.ValueTuple(Of T2, T2)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32072: Cannot implement interface 'I0(Of (T2, T2))' because its implementation could conflict with the implementation of another implemented interface 'I0(Of (a As Integer, b As Integer))' for some type arguments. Implements I0(Of (a As Integer, b As Integer)), I0(Of (T2, T2)) ~~~~~~~~~~~~~~~ BC32072: Cannot implement interface 'I0(Of (a As T2, b As T2))' because its implementation could conflict with the implementation of another implemented interface 'I0(Of (a As Integer, b As Integer))' for some type arguments. Implements I0(Of (a As Integer, b As Integer)), I0(Of (a As T2, b As T2)) ~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub InterfaceUnification2() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Public Interface I0(Of T1) End Interface Public Class Derived(Of T) Implements I0(Of Derived(Of (T, T))), I0(Of T) End Class ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> </errors>) ' Didn't run out of memory in trying to substitute T with Derived(Of (T, T)) in a loop End Sub <Fact> Public Sub AmbiguousExtensionMethodWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Public Module M1 <System.Runtime.CompilerServices.Extension()> Public Sub M(self As String, x As (Integer, Integer)) Throw New Exception() End Sub End Module Public Module M2 <System.Runtime.CompilerServices.Extension()> Public Sub M(self As String, x As (a As Integer, b As Integer)) Throw New Exception() End Sub End Module Public Module M3 <System.Runtime.CompilerServices.Extension()> Public Sub M(self As String, x As (c As Integer, d As Integer)) Throw New Exception() End Sub End Module Public Class C Public Sub M(s As String) s.M((1, 1)) s.M((a:=1, b:=1)) s.M((c:=1, d:=1)) End Sub End Class ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30521: Overload resolution failed because no accessible 'M' is most specific for these arguments: Extension method 'Public Sub M(x As (Integer, Integer))' defined in 'M1': Not most specific. Extension method 'Public Sub M(x As (a As Integer, b As Integer))' defined in 'M2': Not most specific. Extension method 'Public Sub M(x As (c As Integer, d As Integer))' defined in 'M3': Not most specific. s.M((1, 1)) ~ BC30521: Overload resolution failed because no accessible 'M' is most specific for these arguments: Extension method 'Public Sub M(x As (Integer, Integer))' defined in 'M1': Not most specific. Extension method 'Public Sub M(x As (a As Integer, b As Integer))' defined in 'M2': Not most specific. Extension method 'Public Sub M(x As (c As Integer, d As Integer))' defined in 'M3': Not most specific. s.M((a:=1, b:=1)) ~ BC30521: Overload resolution failed because no accessible 'M' is most specific for these arguments: Extension method 'Public Sub M(x As (Integer, Integer))' defined in 'M1': Not most specific. Extension method 'Public Sub M(x As (a As Integer, b As Integer))' defined in 'M2': Not most specific. Extension method 'Public Sub M(x As (c As Integer, d As Integer))' defined in 'M3': Not most specific. s.M((c:=1, d:=1)) ~ </errors>) End Sub <Fact> Public Sub InheritFromMetadataWithDifferentNames() Dim il = " .assembly extern mscorlib { } .assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 } .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object { .method public hidebysig newslot virtual instance class [System.ValueTuple]System.ValueTuple`2<int32,int32> M() cil managed { .param [0] .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = {string[2]('a' 'b')} // Code size 13 (0xd) .maxstack 2 .locals init (class [System.ValueTuple]System.ValueTuple`2<int32,int32> V_0) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj instance void class [System.ValueTuple]System.ValueTuple`2<int32,int32>::.ctor(!0, !1) IL_0008: stloc.0 IL_0009: br.s IL_000b IL_000b: ldloc.0 IL_000c: ret } // end of method Base::M .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method Base::.ctor } // end of class Base .class public auto ansi beforefieldinit Base2 extends Base { .method public hidebysig virtual instance class [System.ValueTuple]System.ValueTuple`2<int32,int32> M() cil managed { .param [0] .custom instance void [System.ValueTuple]System.Runtime.CompilerServices.TupleElementNamesAttribute::.ctor(string[]) = {string[2]('notA' 'notB')} // Code size 13 (0xd) .maxstack 2 .locals init (class [System.ValueTuple]System.ValueTuple`2<int32,int32> V_0) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj instance void class [System.ValueTuple]System.ValueTuple`2<int32,int32>::.ctor(!0, !1) IL_0008: stloc.0 IL_0009: br.s IL_000b IL_000b: ldloc.0 IL_000c: ret } // end of method Base2::M .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void Base::.ctor() IL_0006: nop IL_0007: ret } // end of method Base2::.ctor } // end of class Base2 " Dim compMatching = CreateCompilationWithCustomILSource( <compilation> <file name="a.vb"> Public Class C Inherits Base2 Public Overrides Function M() As (notA As Integer, notB As Integer) Return (1, 2) End Function End Class </file> </compilation>, il, additionalReferences:=s_valueTupleRefs) compMatching.AssertTheseDiagnostics() Dim compDifferent1 = CreateCompilationWithCustomILSource( <compilation> <file name="a.vb"> Public Class C Inherits Base2 Public Overrides Function M() As (a As Integer, b As Integer) Return (1, 2) End Function End Class </file> </compilation>, il, additionalReferences:=s_valueTupleRefs) compDifferent1.AssertTheseDiagnostics( <errors> BC40001: 'Public Overrides Function M() As (a As Integer, b As Integer)' cannot override 'Public Overrides Function M() As (notA As Integer, notB As Integer)' because they differ by their tuple element names. Public Overrides Function M() As (a As Integer, b As Integer) ~ </errors>) Dim compDifferent2 = CreateCompilationWithCustomILSource( <compilation> <file name="a.vb"> Public Class C Inherits Base2 Public Overrides Function M() As (Integer, Integer) Return (1, 2) End Function End Class </file> </compilation>, il, additionalReferences:=s_valueTupleRefs) compDifferent2.AssertTheseDiagnostics( <errors> </errors>) End Sub <Fact> Public Sub TupleNamesInAnonymousTypes() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Public Shared Sub Main() Dim x1 = New With {.Tuple = (a:=1, b:=2) } Dim x2 = New With {.Tuple = (c:=1, 2) } x2 = x1 Console.Write(x1.Tuple.a) End Sub End Class </file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics() Dim model = comp.GetSemanticModel(comp.SyntaxTrees(0)) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().First() Dim x1 = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Assert.Equal("x1 As <anonymous type: Tuple As (a As System.Int32, b As System.Int32)>", model.GetDeclaredSymbol(x1).ToTestDisplayString()) Dim x2 = nodes.OfType(Of VariableDeclaratorSyntax)().Skip(1).First().Names(0) Assert.Equal("x2 As <anonymous type: Tuple As (c As System.Int32, System.Int32)>", model.GetDeclaredSymbol(x2).ToTestDisplayString()) End Sub <Fact> Public Sub OverriddenPropertyWithDifferentTupleNamesInReturn() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Base Public Overridable Property P1 As (a As Integer, b As Integer) Public Overridable Property P2 As (a As Integer, b As Integer) Public Overridable Property P3 As (a As Integer, b As Integer)() Public Overridable Property P4 As (a As Integer, b As Integer)? Public Overridable Property P5 As (c As (a As Integer, b As Integer), d As Integer) End Class Public Class Derived Inherits Base Public Overrides Property P1 As (a As Integer, b As Integer) Public Overrides Property P2 As (notA As Integer, notB As Integer) Public Overrides Property P3 As (notA As Integer, notB As Integer)() Public Overrides Property P4 As (notA As Integer, notB As Integer)? Public Overrides Property P5 As (c As (notA As Integer, notB As Integer), d As Integer) End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC40001: 'Public Overrides Property P2 As (notA As Integer, notB As Integer)' cannot override 'Public Overridable Property P2 As (a As Integer, b As Integer)' because they differ by their tuple element names. Public Overrides Property P2 As (notA As Integer, notB As Integer) ~~ BC40001: 'Public Overrides Property P3 As (notA As Integer, notB As Integer)()' cannot override 'Public Overridable Property P3 As (a As Integer, b As Integer)()' because they differ by their tuple element names. Public Overrides Property P3 As (notA As Integer, notB As Integer)() ~~ BC40001: 'Public Overrides Property P4 As (notA As Integer, notB As Integer)?' cannot override 'Public Overridable Property P4 As (a As Integer, b As Integer)?' because they differ by their tuple element names. Public Overrides Property P4 As (notA As Integer, notB As Integer)? ~~ BC40001: 'Public Overrides Property P5 As (c As (notA As Integer, notB As Integer), d As Integer)' cannot override 'Public Overridable Property P5 As (c As (a As Integer, b As Integer), d As Integer)' because they differ by their tuple element names. Public Overrides Property P5 As (c As (notA As Integer, notB As Integer), d As Integer) ~~ </errors>) End Sub <Fact> Public Sub OverriddenPropertyWithNoTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Base Public Overridable Property P6 As (a As Integer, b As Integer) End Class Public Class Derived Inherits Base Public Overrides Property P6 As (Integer, Integer) Sub M() Dim result = Me.P6 Dim result2 = MyBase.P6 System.Console.Write(result.a) System.Console.Write(result2.a) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> </errors>) Dim tree = comp.SyntaxTrees.First() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim propertyAccess = nodes.OfType(Of MemberAccessExpressionSyntax)().ElementAt(0) Assert.Equal("Me.P6", propertyAccess.ToString()) Assert.Equal("Property Derived.P6 As (System.Int32, System.Int32)", model.GetSymbolInfo(propertyAccess).Symbol.ToTestDisplayString()) Dim propertyAccess2 = nodes.OfType(Of MemberAccessExpressionSyntax)().ElementAt(1) Assert.Equal("MyBase.P6", propertyAccess2.ToString()) Assert.Equal("Property Base.P6 As (a As System.Int32, b As System.Int32)", model.GetSymbolInfo(propertyAccess2).Symbol.ToTestDisplayString()) End Sub <Fact> Public Sub OverriddenPropertyWithNoTupleNamesWithValueTuple() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Base Public Overridable Property P6 As (a As Integer, b As Integer) End Class Public Class Derived Inherits Base Public Overrides Property P6 As System.ValueTuple(Of Integer, Integer) Sub M() Dim result = Me.P6 Dim result2 = MyBase.P6 System.Console.Write(result.a) System.Console.Write(result2.a) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> </errors>) Dim tree = comp.SyntaxTrees.First() Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim propertyAccess = nodes.OfType(Of MemberAccessExpressionSyntax)().ElementAt(0) Assert.Equal("Me.P6", propertyAccess.ToString()) Assert.Equal("Property Derived.P6 As (System.Int32, System.Int32)", model.GetSymbolInfo(propertyAccess).Symbol.ToTestDisplayString()) Dim propertyAccess2 = nodes.OfType(Of MemberAccessExpressionSyntax)().ElementAt(1) Assert.Equal("MyBase.P6", propertyAccess2.ToString()) Assert.Equal("Property Base.P6 As (a As System.Int32, b As System.Int32)", model.GetSymbolInfo(propertyAccess2).Symbol.ToTestDisplayString()) End Sub <Fact> Public Sub OverriddenEventWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class Base Public Overridable Event E1 As Action(Of (a As Integer, b As Integer)) End Class Public Class Derived Inherits Base Public Overrides Event E1 As Action(Of (Integer, Integer)) End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30243: 'Overridable' is not valid on an event declaration. Public Overridable Event E1 As Action(Of (a As Integer, b As Integer)) ~~~~~~~~~~~ BC30243: 'Overrides' is not valid on an event declaration. Public Overrides Event E1 As Action(Of (Integer, Integer)) ~~~~~~~~~ BC40004: event 'E1' conflicts with event 'E1' in the base class 'Base' and should be declared 'Shadows'. Public Overrides Event E1 As Action(Of (Integer, Integer)) ~~ </errors>) End Sub <Fact> Public Sub StructInStruct() Dim comp = CreateCompilationWithMscorlib45AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Public Structure S Public Field As (S, S) End Structure ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30294: Structure 'S' cannot contain an instance of itself: 'S' contains '(S, S)' (variable 'Field'). '(S, S)' contains 'S' (variable 'Item1'). Public Field As (S, S) ~~~~~ </errors>) End Sub <Fact> Public Sub AssignNullWithMissingValueTuple() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class S Dim t As (Integer, Integer) = Nothing End Class </file> </compilation>) comp.AssertTheseDiagnostics( <errors> BC37267: Predefined type 'ValueTuple(Of ,)' is not defined or imported. Dim t As (Integer, Integer) = Nothing ~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub MultipleImplementsWithDifferentTupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Interface I0 Sub M(x As (a0 As Integer, b0 As Integer)) Function MR() As (a0 As Integer, b0 As Integer) End Interface Public Interface I1 Sub M(x As (a1 As Integer, b1 As Integer)) Function MR() As (a1 As Integer, b1 As Integer) End Interface Public Class C1 Implements I0, I1 Public Sub M(x As (a2 As Integer, b2 As Integer)) Implements I0.M, I1.M End Sub Public Function MR() As (a2 As Integer, b2 As Integer) Implements I0.MR, I1.MR Return (1, 2) End Function End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC30402: 'M' cannot implement sub 'M' on interface 'I0' because the tuple element names in 'Public Sub M(x As (a2 As Integer, b2 As Integer))' do not match those in 'Sub M(x As (a0 As Integer, b0 As Integer))'. Public Sub M(x As (a2 As Integer, b2 As Integer)) Implements I0.M, I1.M ~~~~ BC30402: 'M' cannot implement sub 'M' on interface 'I1' because the tuple element names in 'Public Sub M(x As (a2 As Integer, b2 As Integer))' do not match those in 'Sub M(x As (a1 As Integer, b1 As Integer))'. Public Sub M(x As (a2 As Integer, b2 As Integer)) Implements I0.M, I1.M ~~~~ BC30402: 'MR' cannot implement function 'MR' on interface 'I0' because the tuple element names in 'Public Function MR() As (a2 As Integer, b2 As Integer)' do not match those in 'Function MR() As (a0 As Integer, b0 As Integer)'. Public Function MR() As (a2 As Integer, b2 As Integer) Implements I0.MR, I1.MR ~~~~~ BC30402: 'MR' cannot implement function 'MR' on interface 'I1' because the tuple element names in 'Public Function MR() As (a2 As Integer, b2 As Integer)' do not match those in 'Function MR() As (a1 As Integer, b1 As Integer)'. Public Function MR() As (a2 As Integer, b2 As Integer) Implements I0.MR, I1.MR ~~~~~ </errors>) End Sub <Fact> Public Sub MethodSignatureComparerTest() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Public Sub M1(x As (a As Integer, b As Integer)) End Sub Public Sub M2(x As (a As Integer, b As Integer)) End Sub Public Sub M3(x As (notA As Integer, notB As Integer)) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics() Dim m1 = comp.GetMember(Of MethodSymbol)("C.M1") Dim m2 = comp.GetMember(Of MethodSymbol)("C.M2") Dim m3 = comp.GetMember(Of MethodSymbol)("C.M3") Dim comparison12 = MethodSignatureComparer.DetailedCompare(m1, m2, SymbolComparisonResults.TupleNamesMismatch) Assert.Equal(0, comparison12) Dim comparison13 = MethodSignatureComparer.DetailedCompare(m1, m3, SymbolComparisonResults.TupleNamesMismatch) Assert.Equal(SymbolComparisonResults.TupleNamesMismatch, comparison13) End Sub <Fact> Public Sub IsSameTypeTest() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Public Sub M1(x As (Integer, Integer)) End Sub Public Sub M2(x As (a As Integer, b As Integer)) End Sub End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics() Dim m1 = comp.GetMember(Of MethodSymbol)("C.M1") Dim tuple1 As TypeSymbol = m1.Parameters(0).Type Dim underlying1 As NamedTypeSymbol = tuple1.TupleUnderlyingType Assert.True(tuple1.IsSameType(tuple1, TypeCompareKind.ConsiderEverything)) Assert.False(tuple1.IsSameType(underlying1, TypeCompareKind.ConsiderEverything)) Assert.False(underlying1.IsSameType(tuple1, TypeCompareKind.ConsiderEverything)) Assert.True(underlying1.IsSameType(underlying1, TypeCompareKind.ConsiderEverything)) Assert.True(tuple1.IsSameType(tuple1, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) Assert.False(tuple1.IsSameType(underlying1, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) Assert.False(underlying1.IsSameType(tuple1, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) Assert.True(underlying1.IsSameType(underlying1, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) Assert.True(tuple1.IsSameType(tuple1, TypeCompareKind.IgnoreTupleNames)) Assert.True(tuple1.IsSameType(underlying1, TypeCompareKind.IgnoreTupleNames)) Assert.True(underlying1.IsSameType(tuple1, TypeCompareKind.IgnoreTupleNames)) Assert.True(underlying1.IsSameType(underlying1, TypeCompareKind.IgnoreTupleNames)) Assert.False(tuple1.IsSameType(Nothing, TypeCompareKind.ConsiderEverything)) Assert.False(tuple1.IsSameType(Nothing, TypeCompareKind.IgnoreTupleNames)) Dim m2 = comp.GetMember(Of MethodSymbol)("C.M2") Dim tuple2 As TypeSymbol = m2.Parameters(0).Type Dim underlying2 As NamedTypeSymbol = tuple2.TupleUnderlyingType Assert.True(tuple2.IsSameType(tuple2, TypeCompareKind.ConsiderEverything)) Assert.False(tuple2.IsSameType(underlying2, TypeCompareKind.ConsiderEverything)) Assert.False(underlying2.IsSameType(tuple2, TypeCompareKind.ConsiderEverything)) Assert.True(underlying2.IsSameType(underlying2, TypeCompareKind.ConsiderEverything)) Assert.True(tuple2.IsSameType(tuple2, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) Assert.False(tuple2.IsSameType(underlying2, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) Assert.False(underlying2.IsSameType(tuple2, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) Assert.True(underlying2.IsSameType(underlying2, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) Assert.True(tuple2.IsSameType(tuple2, TypeCompareKind.IgnoreTupleNames)) Assert.True(tuple2.IsSameType(underlying2, TypeCompareKind.IgnoreTupleNames)) Assert.True(underlying2.IsSameType(tuple2, TypeCompareKind.IgnoreTupleNames)) Assert.True(underlying2.IsSameType(underlying2, TypeCompareKind.IgnoreTupleNames)) Assert.False(tuple1.IsSameType(tuple2, TypeCompareKind.ConsiderEverything)) Assert.False(tuple2.IsSameType(tuple1, TypeCompareKind.ConsiderEverything)) Assert.False(tuple1.IsSameType(tuple2, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) Assert.False(tuple2.IsSameType(tuple1, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) Assert.True(tuple1.IsSameType(tuple2, TypeCompareKind.IgnoreTupleNames)) Assert.True(tuple2.IsSameType(tuple1, TypeCompareKind.IgnoreTupleNames)) End Sub <Fact> Public Sub PropertySignatureComparer_TupleNames() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Public Property P1 As (a As Integer, b As Integer) Public Property P2 As (a As Integer, b As Integer) Public Property P3 As (notA As Integer, notB As Integer) End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics() Dim p1 = comp.GetMember(Of PropertySymbol)("C.P1") Dim p2 = comp.GetMember(Of PropertySymbol)("C.P2") Dim p3 = comp.GetMember(Of PropertySymbol)("C.P3") Dim comparison12 = PropertySignatureComparer.DetailedCompare(p1, p2, SymbolComparisonResults.TupleNamesMismatch) Assert.Equal(0, comparison12) Dim comparison13 = PropertySignatureComparer.DetailedCompare(p1, p3, SymbolComparisonResults.TupleNamesMismatch) Assert.Equal(SymbolComparisonResults.TupleNamesMismatch, comparison13) End Sub <Fact> Public Sub PropertySignatureComparer_TypeCustomModifiers() Dim il = <![CDATA[ .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern System.Core {} .assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 } .assembly '<<GeneratedFileName>>' { } .class public auto ansi beforefieldinit CL1`1<T1> extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method CL1`1::.ctor .property instance !T1 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) Test() { .get instance !T1 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) CL1`1::get_Test() .set instance void CL1`1::set_Test(!T1 modopt([mscorlib]System.Runtime.CompilerServices.IsConst)) } // end of property CL1`1::Test .method public hidebysig newslot specialname virtual instance !T1 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) get_Test() cil managed { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: throw } // end of method CL1`1::get_Test .method public hidebysig newslot specialname virtual instance void set_Test(!T1 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) x) cil managed { // Code size 3 (0x3) .maxstack 1 IL_0000: ldarg.0 IL_0001: throw IL_0002: ret } // end of method CL1`1::set_Test } // end of class CL1`1 ]]>.Value Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class CL2(Of T1) Public Property Test As T1 End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithCustomILSource(source1, il, appendDefaultHeader:=False, additionalReferences:={ValueTupleRef, SystemRuntimeFacadeRef}) comp1.AssertTheseDiagnostics() Dim property1 = comp1.GlobalNamespace.GetMember(Of PropertySymbol)("CL1.Test") Assert.Equal("Property CL1(Of T1).Test As T1 modopt(System.Runtime.CompilerServices.IsConst)", property1.ToTestDisplayString()) Dim property2 = comp1.GlobalNamespace.GetMember(Of PropertySymbol)("CL2.Test") Assert.Equal("Property CL2(Of T1).Test As T1", property2.ToTestDisplayString()) Assert.False(PropertySignatureComparer.RuntimePropertySignatureComparer.Equals(property1, property2)) End Sub <Fact> Public Sub EventSignatureComparerTest() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Class C Public Event E1 As Action(Of (a As Integer, b As Integer)) Public Event E2 As Action(Of (a As Integer, b As Integer)) Public Event E3 As Action(Of (notA As Integer, notB As Integer)) End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics() Dim e1 = comp.GetMember(Of EventSymbol)("C.E1") Dim e2 = comp.GetMember(Of EventSymbol)("C.E2") Dim e3 = comp.GetMember(Of EventSymbol)("C.E3") Assert.True(EventSignatureComparer.ExplicitEventImplementationWithTupleNamesComparer.Equals(e1, e2)) Assert.False(EventSignatureComparer.ExplicitEventImplementationWithTupleNamesComparer.Equals(e1, e3)) End Sub <Fact> Public Sub OperatorOverloadingWithDifferentTupleNames() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Class B1 Shared Operator >=(x1 As (a As B1, b As B1), x2 As B1) As Boolean Return Nothing End Operator Shared Operator <=(x1 As (notA As B1, notB As B1), x2 As B1) As Boolean Return Nothing End Operator End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() End Sub <Fact> Public Sub Shadowing() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C0 Public Function M(x As (a As Integer, (b As Integer, c As Integer))) As (a As Integer, (b As Integer, c As Integer)) Return (1, (2, 3)) End Function End Class Public Class C1 Inherits C0 Public Function M(x As (a As Integer, (notB As Integer, c As Integer))) As (a As Integer, (notB As Integer, c As Integer)) Return (1, (2, 3)) End Function End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC40003: function 'M' shadows an overloadable member declared in the base class 'C0'. If you want to overload the base method, this method must be declared 'Overloads'. Public Function M(x As (a As Integer, (notB As Integer, c As Integer))) As (a As Integer, (notB As Integer, c As Integer)) ~ </errors>) End Sub <Fact> Public Sub UnifyDifferentTupleName() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Interface I0(Of T1) End Interface Class C(Of T2) Implements I0(Of (a As Integer, b As Integer)), I0(Of (notA As T2, notB As T2)) End Class </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC32072: Cannot implement interface 'I0(Of (notA As T2, notB As T2))' because its implementation could conflict with the implementation of another implemented interface 'I0(Of (a As Integer, b As Integer))' for some type arguments. Implements I0(Of (a As Integer, b As Integer)), I0(Of (notA As T2, notB As T2)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub BC31407ERR_MultipleEventImplMismatch3() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Interface I1 Event evtTest1(x As (A As Integer, B As Integer)) Event evtTest2(x As (A As Integer, notB As Integer)) End Interface Class C1 Implements I1 Event evtTest3(x As (A As Integer, stilNotB As Integer)) Implements I1.evtTest1, I1.evtTest2 End Class ]]></file> </compilation>, references:=s_valueTupleRefs) Dim expectedErrors1 = <errors><![CDATA[ BC30402: 'evtTest3' cannot implement event 'evtTest1' on interface 'I1' because the tuple element names in 'Public Event evtTest3 As I1.evtTest1EventHandler' do not match those in 'Event evtTest1(x As (A As Integer, B As Integer))'. Event evtTest3(x As (A As Integer, stilNotB As Integer)) Implements I1.evtTest1, I1.evtTest2 ~~~~~~~~~~~ BC30402: 'evtTest3' cannot implement event 'evtTest2' on interface 'I1' because the tuple element names in 'Public Event evtTest3 As I1.evtTest1EventHandler' do not match those in 'Event evtTest2(x As (A As Integer, notB As Integer))'. Event evtTest3(x As (A As Integer, stilNotB As Integer)) Implements I1.evtTest1, I1.evtTest2 ~~~~~~~~~~~ BC31407: Event 'Public Event evtTest3 As I1.evtTest1EventHandler' cannot implement event 'I1.Event evtTest2(x As (A As Integer, notB As Integer))' because its delegate type does not match the delegate type of another event implemented by 'Public Event evtTest3 As I1.evtTest1EventHandler'. Event evtTest3(x As (A As Integer, stilNotB As Integer)) Implements I1.evtTest1, I1.evtTest2 ~~~~~~~~~~~ ]]></errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub ImplementingEventWithDifferentTupleNames() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Interface I1 Event evtTest1 As Action(Of (A As Integer, B As Integer)) Event evtTest2 As Action(Of (A As Integer, notB As Integer)) End Interface Class C1 Implements I1 Event evtTest3 As Action(Of (A As Integer, stilNotB As Integer)) Implements I1.evtTest1, I1.evtTest2 End Class ]]></file> </compilation>, references:=s_valueTupleRefs) Dim expectedErrors1 = <errors><![CDATA[ BC30402: 'evtTest3' cannot implement event 'evtTest1' on interface 'I1' because the tuple element names in 'Public Event evtTest3 As Action(Of (A As Integer, stilNotB As Integer))' do not match those in 'Event evtTest1 As Action(Of (A As Integer, B As Integer))'. Event evtTest3 As Action(Of (A As Integer, stilNotB As Integer)) Implements I1.evtTest1, I1.evtTest2 ~~~~~~~~~~~ BC30402: 'evtTest3' cannot implement event 'evtTest2' on interface 'I1' because the tuple element names in 'Public Event evtTest3 As Action(Of (A As Integer, stilNotB As Integer))' do not match those in 'Event evtTest2 As Action(Of (A As Integer, notB As Integer))'. Event evtTest3 As Action(Of (A As Integer, stilNotB As Integer)) Implements I1.evtTest1, I1.evtTest2 ~~~~~~~~~~~ ]]></errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation1, expectedErrors1) End Sub <Fact()> Public Sub ImplementingEventWithNoTupleNames() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Interface I1 Event evtTest1 As Action(Of (A As Integer, B As Integer)) Event evtTest2 As Action(Of (A As Integer, notB As Integer)) End Interface Class C1 Implements I1 Event evtTest3 As Action(Of (Integer, Integer)) Implements I1.evtTest1, I1.evtTest2 End Class ]]></file> </compilation>, references:=s_valueTupleRefs) CompilationUtils.AssertNoDiagnostics(compilation1) End Sub <Fact()> Public Sub ImplementingPropertyWithDifferentTupleNames() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Interface I1 Property P(x As (a As Integer, b As Integer)) As Boolean End Interface Class C1 Implements I1 Property P(x As (notA As Integer, notB As Integer)) As Boolean Implements I1.P Get Return True End Get Set End Set End Property End Class ]]></file> </compilation>, references:=s_valueTupleRefs) compilation.AssertTheseDiagnostics(<errors> BC30402: 'P' cannot implement property 'P' on interface 'I1' because the tuple element names in 'Public Property P(x As (notA As Integer, notB As Integer)) As Boolean' do not match those in 'Property P(x As (a As Integer, b As Integer)) As Boolean'. Property P(x As (notA As Integer, notB As Integer)) As Boolean Implements I1.P ~~~~ </errors>) End Sub <Fact()> Public Sub ImplementingPropertyWithNoTupleNames() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Interface I1 Property P(x As (a As Integer, b As Integer)) As Boolean End Interface Class C1 Implements I1 Property P(x As (Integer, Integer)) As Boolean Implements I1.P Get Return True End Get Set End Set End Property End Class ]]></file> </compilation>, references:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() End Sub <Fact()> Public Sub ImplementingPropertyWithNoTupleNames2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Interface I1 Property P As (a As Integer, b As Integer) End Interface Class C1 Implements I1 Property P As (Integer, Integer) Implements I1.P End Class ]]></file> </compilation>, references:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() End Sub <Fact()> Public Sub ImplementingMethodWithNoTupleNames() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Interface I1 Sub M(x As (a As Integer, b As Integer)) Function M2 As (a As Integer, b As Integer) End Interface Class C1 Implements I1 Sub M(x As (Integer, Integer)) Implements I1.M End Sub Function M2 As (Integer, Integer) Implements I1.M2 Return (1, 2) End Function End Class ]]></file> </compilation>, references:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() End Sub <Fact> Public Sub BC31407ERR_MultipleEventImplMismatch3_2() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Interface I1 Event evtTest1 As Action(Of (A As Integer, B As Integer)) Event evtTest2 As Action(Of (A As Integer, notB As Integer)) End Interface Class C1 Implements I1 Event evtTest3(x As (A As Integer, stillNotB As Integer)) Implements I1.evtTest1, I1.evtTest2 End Class ]]></file> </compilation>, references:=s_valueTupleRefs) compilation1.AssertTheseDiagnostics( <errors> BC30402: 'evtTest3' cannot implement event 'evtTest1' on interface 'I1' because the tuple element names in 'Public Event evtTest3 As Action(Of (A As Integer, B As Integer))' do not match those in 'Event evtTest1 As Action(Of (A As Integer, B As Integer))'. Event evtTest3(x As (A As Integer, stillNotB As Integer)) Implements I1.evtTest1, I1.evtTest2 ~~~~~~~~~~~ BC30402: 'evtTest3' cannot implement event 'evtTest2' on interface 'I1' because the tuple element names in 'Public Event evtTest3 As Action(Of (A As Integer, B As Integer))' do not match those in 'Event evtTest2 As Action(Of (A As Integer, notB As Integer))'. Event evtTest3(x As (A As Integer, stillNotB As Integer)) Implements I1.evtTest1, I1.evtTest2 ~~~~~~~~~~~ </errors>) End Sub <WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")> <Fact> Public Sub ValueTupleNotStruct0() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Tuples"> <file name="a.vb"> class C Shared Sub Main() Dim x as (a As Integer, b As String) x.Item1 = 1 x.b = "2" ' by the language rules tuple x is definitely assigned ' since all its elements are definitely assigned System.Console.WriteLine(x) end sub end class namespace System public class ValueTuple(Of T1, T2) public Item1 as T1 public Item2 as T2 public Sub New(item1 as T1 , item2 as T2 ) Me.Item1 = item1 Me.Item2 = item2 end sub End class end Namespace <%= s_tupleattributes %> </file> </compilation>, options:=TestOptions.DebugExe) comp.AssertTheseEmitDiagnostics( <errors> BC37281: Predefined type 'ValueTuple`2' must be a structure. Dim x as (a As Integer, b As String) ~ </errors>) End Sub <WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")> <Fact> Public Sub ValueTupleNotStruct1() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Tuples"> <file name="a.vb"> class C Shared Sub Main() Dim x = (1,2,3,4,5,6,7,8,9) System.Console.WriteLine(x) end sub end class namespace System public class ValueTuple(Of T1, T2) public Item1 as T1 public Item2 as T2 public Sub New(item1 as T1 , item2 as T2 ) Me.Item1 = item1 Me.Item2 = item2 end sub End class public class ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest) public Item1 As T1 public Item2 As T2 public Item3 As T3 public Item4 As T4 public Item5 As T5 public Item6 As T6 public Item7 As T7 public Rest As TRest public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6, item7 As T7, rest As TRest) Item1 = item1 Item2 = item2 Item3 = item3 Item4 = item4 Item5 = item5 Item6 = item6 Item7 = item7 Rest = rest end Sub End Class end Namespace <%= s_tupleattributes %> </file> </compilation>, options:=TestOptions.DebugExe) comp.AssertTheseEmitDiagnostics( <errors> BC37281: Predefined type 'ValueTuple`2' must be a structure. Dim x = (1,2,3,4,5,6,7,8,9) ~ BC37281: Predefined type 'ValueTuple`8' must be a structure. Dim x = (1,2,3,4,5,6,7,8,9) ~ </errors>) End Sub <Fact> Public Sub ConversionToBase() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Public Class Base(Of T) End Class Public Class Derived Inherits Base(Of (a As Integer, b As Integer)) Public Shared Narrowing Operator CType(ByVal arg As Derived) As Base(Of (Integer, Integer)) Return Nothing End Operator Public Shared Narrowing Operator CType(ByVal arg As Base(Of (Integer, Integer))) As Derived Return Nothing End Operator End Class ]]></file> </compilation>, references:=s_valueTupleRefs) compilation1.AssertTheseDiagnostics( <errors> BC33026: Conversion operators cannot convert from a type to its base type. Public Shared Narrowing Operator CType(ByVal arg As Derived) As Base(Of (Integer, Integer)) ~~~~~ BC33030: Conversion operators cannot convert from a base type. Public Shared Narrowing Operator CType(ByVal arg As Base(Of (Integer, Integer))) As Derived ~~~~~ </errors>) End Sub <WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")> <Fact> Public Sub ValueTupleNotStruct2() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Tuples"> <file name="a.vb"> class C Shared Sub Main() end sub Shared Sub Test2(arg as (a As Integer, b As Integer)) End Sub end class namespace System public class ValueTuple(Of T1, T2) public Item1 as T1 public Item2 as T2 public Sub New(item1 as T1 , item2 as T2 ) Me.Item1 = item1 Me.Item2 = item2 end sub End class end Namespace <%= s_tupleattributes %> </file> </compilation>, options:=TestOptions.DebugExe) comp.AssertTheseEmitDiagnostics( <errors> BC37281: Predefined type 'ValueTuple`2' must be a structure. </errors>) End Sub <WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")> <Fact> Public Sub ValueTupleNotStruct2i() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Tuples"> <file name="a.vb"> class C Shared Sub Main() end sub Shared Sub Test2(arg as (a As Integer, b As Integer)) End Sub end class namespace System public interface ValueTuple(Of T1, T2) End Interface end Namespace <%= s_tupleattributes %> </file> </compilation>, options:=TestOptions.DebugExe) comp.AssertTheseEmitDiagnostics( <errors> BC37281: Predefined type 'ValueTuple`2' must be a structure. </errors>) End Sub <WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")> <Fact> Public Sub ValueTupleNotStruct3() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Tuples"> <file name="a.vb"> class C Shared Sub Main() Dim x as (a As Integer, b As String)() = Nothing ' by the language rules tuple x is definitely assigned ' since all its elements are definitely assigned System.Console.WriteLine(x) end sub end class namespace System public class ValueTuple(Of T1, T2) public Item1 as T1 public Item2 as T2 public Sub New(item1 as T1 , item2 as T2 ) Me.Item1 = item1 Me.Item2 = item2 end sub End class end Namespace <%= s_tupleattributes %> </file> </compilation>, options:=TestOptions.DebugExe) comp.AssertTheseEmitDiagnostics( <errors> BC37281: Predefined type 'ValueTuple`2' must be a structure. Dim x as (a As Integer, b As String)() = Nothing ~ </errors>) End Sub <WorkItem(11689, "https://github.com/dotnet/roslyn/issues/11689")> <Fact> Public Sub ValueTupleNotStruct4() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Tuples"> <file name="a.vb"> class C Shared Sub Main() end sub Shared Function Test2()as (a As Integer, b As Integer) End Function end class namespace System public class ValueTuple(Of T1, T2) public Item1 as T1 public Item2 as T2 public Sub New(item1 as T1 , item2 as T2 ) Me.Item1 = item1 Me.Item2 = item2 end sub End class end Namespace <%= s_tupleattributes %> </file> </compilation>, options:=TestOptions.DebugExe) comp.AssertTheseEmitDiagnostics( <errors> BC37281: Predefined type 'ValueTuple`2' must be a structure. Shared Function Test2()as (a As Integer, b As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub ValueTupleBaseError_NoSystemRuntime() Dim comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I Function F() As ((Integer, Integer), (Integer, Integer)) End Interface </file> </compilation>, references:={ValueTupleRef}) comp.AssertTheseEmitDiagnostics( <errors> BC30652: Reference required to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' containing the type 'ValueType'. Add one to your project. Function F() As ((Integer, Integer), (Integer, Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30652: Reference required to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' containing the type 'ValueType'. Add one to your project. Function F() As ((Integer, Integer), (Integer, Integer)) ~~~~~~~~~~~~~~~~~~ BC30652: Reference required to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' containing the type 'ValueType'. Add one to your project. Function F() As ((Integer, Integer), (Integer, Integer)) ~~~~~~~~~~~~~~~~~~ </errors>) End Sub <WorkItem(16879, "https://github.com/dotnet/roslyn/issues/16879")> <Fact> Public Sub ValueTupleBaseError_MissingReference() Dim comp0 = CreateCompilationWithMscorlib40( <compilation name="5a03232e-1a0f-4d1b-99ba-5d7b40ea931e"> <file name="a.vb"> Public Class A End Class Public Class B End Class </file> </compilation>) comp0.AssertNoDiagnostics() Dim ref0 = comp0.EmitToImageReference() Dim comp1 = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Public Class C(Of T) End Class Namespace System Public Class ValueTuple(Of T1, T2) Inherits A Public Sub New(_1 As T1, _2 As T2) End Sub End Class Public Class ValueTuple(Of T1, T2, T3) Inherits C(Of B) Public Sub New(_1 As T1, _2 As T2, _3 As T3) End Sub End Class End Namespace </file> </compilation>, references:={ref0}) Dim ref1 = comp1.EmitToImageReference() Dim comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I Function F() As (Integer, (Integer, Integer), (Integer, Integer)) End Interface </file> </compilation>, references:={ref1}) comp.AssertTheseEmitDiagnostics( <errors> BC30652: Reference required to assembly '5a03232e-1a0f-4d1b-99ba-5d7b40ea931e, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'A'. Add one to your project. BC30652: Reference required to assembly '5a03232e-1a0f-4d1b-99ba-5d7b40ea931e, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'B'. Add one to your project. </errors>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.TestExecutionNeedsWindowsTypes)> Public Sub ValueTupleBase_AssemblyUnification() Dim signedDllOptions = TestOptions.SigningReleaseDll. WithCryptoKeyFile(SigningTestHelpers.KeyPairFile) Dim comp0v1 = CreateCompilationWithMscorlib40( <compilation name="A"> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyVersion("1.0.0.0")> Public Class A End Class ]]></file> </compilation>, options:=signedDllOptions) comp0v1.AssertNoDiagnostics() Dim ref0v1 = comp0v1.EmitToImageReference() Dim comp0v2 = CreateCompilationWithMscorlib40( <compilation name="A"> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyVersion("2.0.0.0")> Public Class A End Class ]]></file> </compilation>, options:=signedDllOptions) comp0v2.AssertNoDiagnostics() Dim ref0v2 = comp0v2.EmitToImageReference() Dim comp1 = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Public Class B Inherits A End Class </file> </compilation>, references:={ref0v1}) comp1.AssertNoDiagnostics() Dim ref1 = comp1.EmitToImageReference() Dim comp2 = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Namespace System Public Class ValueTuple(Of T1, T2) Inherits B Public Sub New(_1 As T1, _2 As T2) End Sub End Class End Namespace </file> </compilation>, references:={ref0v1, ref1}) Dim ref2 = comp2.EmitToImageReference() Dim comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Interface I Function F() As (Integer, Integer) End Interface </file> </compilation>, references:={ref0v2, ref1, ref2}) comp.AssertTheseEmitDiagnostics( <errors> BC37281: Predefined type 'ValueTuple`2' must be a structure. </errors>) End Sub <Fact> Public Sub TernaryTypeInferenceWithDynamicAndTupleNames() ' No dynamic in VB Dim comp = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Tuples"> <file name="a.vb"><![CDATA[ Class C Sub M() Dim flag As Boolean = True Dim x1 = If(flag, (a:=1, b:=2), (a:=1, c:=3)) System.Console.Write(x1.a) End Sub End Class ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC41009: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'. Dim x1 = If(flag, (a:=1, b:=2), (a:=1, c:=3)) ~~~~ BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'. Dim x1 = If(flag, (a:=1, b:=2), (a:=1, c:=3)) ~~~~ </errors>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim x1 = nodes.OfType(Of VariableDeclaratorSyntax)().Skip(1).First().Names(0) Dim x1Symbol = model.GetDeclaredSymbol(x1) Assert.Equal("x1 As (a As System.Int32, System.Int32)", x1Symbol.ToTestDisplayString()) End Sub <Fact> <WorkItem(16825, "https://github.com/dotnet/roslyn/issues/16825")> Public Sub NullCoalescingOperatorWithTupleNames() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Tuples"> <file name="a.vb"><![CDATA[ Class C Sub M() Dim nab As (a As Integer, b As Integer)? = (1, 2) Dim nac As (a As Integer, c As Integer)? = (1, 3) Dim x1 = If(nab, nac) ' (a, )? Dim x2 = If(nab, nac.Value) ' (a, ) Dim x3 = If(new C(), nac) ' C Dim x4 = If(new D(), nac) ' (a, c)? Dim x5 = If(nab IsNot Nothing, nab, nac) ' (a, )? Dim x6 = If(nab, (a:= 1, c:= 3)) ' (a, ) Dim x7 = If(nab, (a:= 1, 3)) ' (a, ) Dim x8 = If(new C(), (a:= 1, c:= 3)) ' C Dim x9 = If(new D(), (a:= 1, c:= 3)) ' (a, c) Dim x6double = If(nab, (d:= 1.1, c:= 3)) ' (d, c) End Sub Public Shared Narrowing Operator CType(ByVal x As (Integer, Integer)) As C Throw New System.Exception() End Operator End Class Class D Public Shared Narrowing Operator CType(ByVal x As D) As (d1 As Integer, d2 As Integer) Throw New System.Exception() End Operator End Class ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'. Dim x6 = If(nab, (a:= 1, c:= 3)) ' (a, ) ~~~~~ </errors>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim x1 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(2).Names(0) Assert.Equal("x1 As System.Nullable(Of (a As System.Int32, System.Int32))", model.GetDeclaredSymbol(x1).ToTestDisplayString()) Dim x2 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(3).Names(0) Assert.Equal("x2 As (a As System.Int32, System.Int32)", model.GetDeclaredSymbol(x2).ToTestDisplayString()) Dim x3 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(4).Names(0) Assert.Equal("x3 As C", model.GetDeclaredSymbol(x3).ToTestDisplayString()) Dim x4 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(5).Names(0) Assert.Equal("x4 As System.Nullable(Of (a As System.Int32, c As System.Int32))", model.GetDeclaredSymbol(x4).ToTestDisplayString()) Dim x5 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(6).Names(0) Assert.Equal("x5 As System.Nullable(Of (a As System.Int32, System.Int32))", model.GetDeclaredSymbol(x5).ToTestDisplayString()) Dim x6 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(7).Names(0) Assert.Equal("x6 As (a As System.Int32, System.Int32)", model.GetDeclaredSymbol(x6).ToTestDisplayString()) Dim x7 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(8).Names(0) Assert.Equal("x7 As (a As System.Int32, System.Int32)", model.GetDeclaredSymbol(x7).ToTestDisplayString()) Dim x8 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(9).Names(0) Assert.Equal("x8 As C", model.GetDeclaredSymbol(x8).ToTestDisplayString()) Dim x9 = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(10).Names(0) Assert.Equal("x9 As (a As System.Int32, c As System.Int32)", model.GetDeclaredSymbol(x9).ToTestDisplayString()) Dim x6double = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(11).Names(0) Assert.Equal("x6double As (d As System.Double, c As System.Int32)", model.GetDeclaredSymbol(x6double).ToTestDisplayString()) End Sub <Fact> Public Sub TernaryTypeInferenceWithNoNames() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Tuples"> <file name="a.vb"><![CDATA[ Class C Sub M() Dim flag As Boolean = True Dim x1 = If(flag, (a:=1, b:=2), (1, 3)) Dim x2 = If(flag, (1, 2), (a:=1, b:=3)) End Sub End Class ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC41009: The tuple element name 'a' is ignored because a different name or no name is specified by the target type '(Integer, Integer)'. Dim x1 = If(flag, (a:=1, b:=2), (1, 3)) ~~~~ BC41009: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(Integer, Integer)'. Dim x1 = If(flag, (a:=1, b:=2), (1, 3)) ~~~~ BC41009: The tuple element name 'a' is ignored because a different name or no name is specified by the target type '(Integer, Integer)'. Dim x2 = If(flag, (1, 2), (a:=1, b:=3)) ~~~~ BC41009: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(Integer, Integer)'. Dim x2 = If(flag, (1, 2), (a:=1, b:=3)) ~~~~ </errors>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim x1 = nodes.OfType(Of VariableDeclaratorSyntax)().Skip(1).First().Names(0) Dim x1Symbol = model.GetDeclaredSymbol(x1) Assert.Equal("x1 As (System.Int32, System.Int32)", x1Symbol.ToTestDisplayString()) Dim x2 = nodes.OfType(Of VariableDeclaratorSyntax)().Skip(2).First().Names(0) Dim x2Symbol = model.GetDeclaredSymbol(x2) Assert.Equal("x2 As (System.Int32, System.Int32)", x2Symbol.ToTestDisplayString()) End Sub <Fact> Public Sub TernaryTypeInferenceDropsCandidates() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Tuples"> <file name="a.vb"><![CDATA[ Class C Sub M() Dim flag As Boolean = True Dim x1 = If(flag, (a:=1, b:=CType(2, Long)), (a:=CType(1, Byte), c:=3)) End Sub End Class ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(a As Integer, b As Long)'. Dim x1 = If(flag, (a:=1, b:=CType(2, Long)), (a:=CType(1, Byte), c:=3)) ~~~~ </errors>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim x1 = nodes.OfType(Of VariableDeclaratorSyntax)().Skip(1).First().Names(0) Dim x1Symbol = model.GetDeclaredSymbol(x1) Assert.Equal("x1 As (a As System.Int32, b As System.Int64)", x1Symbol.ToTestDisplayString()) End Sub <Fact> Public Sub LambdaTypeInferenceWithTupleNames() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Tuples"> <file name="a.vb"><![CDATA[ Class C Sub M() Dim x1 = M2(Function() Dim flag = True If flag Then Return (a:=1, b:=2) Else If flag Then Return (a:=1, c:=3) Else Return (a:=1, d:=4) End If End If End Function) End Sub Function M2(Of T)(f As System.Func(Of T)) As T Return f() End Function End Class ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC41009: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'. Return (a:=1, b:=2) ~~~~ BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'. Return (a:=1, c:=3) ~~~~ BC41009: The tuple element name 'd' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'. Return (a:=1, d:=4) ~~~~ </errors>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim x1 = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Dim x1Symbol = model.GetDeclaredSymbol(x1) Assert.Equal("x1 As (a As System.Int32, System.Int32)", x1Symbol.ToTestDisplayString()) End Sub <Fact> Public Sub LambdaTypeInferenceFallsBackToObject() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Tuples"> <file name="a.vb"><![CDATA[ Class C Sub M() Dim x1 = M2(Function() Dim flag = True Dim l1 = CType(2, Long) If flag Then Return (a:=1, b:=l1) Else If flag Then Return (a:=l1, c:=3) Else Return (a:=1, d:=l1) End If End If End Function) End Sub Function M2(Of T)(f As System.Func(Of T)) As T Return f() End Function End Class ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics() Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim x1 = nodes.OfType(Of VariableDeclaratorSyntax)().First().Names(0) Dim x1Symbol = model.GetDeclaredSymbol(x1) Assert.Equal("x1 As System.Object", x1Symbol.ToTestDisplayString()) End Sub <Fact> Public Sub IsBaseOf_WithoutCustomModifiers() ' The IL is from this code, but with modifiers ' public class Base<T> { } ' public class Derived<T> : Base<T> { } ' public class Test ' { ' public Base<Object> GetBaseWithModifiers() { return null; } ' public Derived<Object> GetDerivedWithoutModifiers() { return null; } ' } Dim il = <![CDATA[ .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern System.Core {} .assembly extern System.ValueTuple { .publickeytoken = (CC 7B 13 FF CD 2D DD 51 ) .ver 4:0:1:0 } .assembly '<<GeneratedFileName>>' { } .class public auto ansi beforefieldinit Base`1<T> extends [mscorlib]System.Object { // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2050 // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method Base`1::.ctor } // end of class Base`1 .class public auto ansi beforefieldinit Derived`1<T> extends class Base`1<!T> { // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2059 // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void class Base`1<!T>::.ctor() IL_0006: nop IL_0007: ret } // end of method Derived`1::.ctor } // end of class Derived`1 .class public auto ansi beforefieldinit Test extends [mscorlib]System.Object { // Methods .method public hidebysig instance class Base`1<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)> GetBaseWithModifiers () cil managed { // Method begins at RVA 0x2064 // Code size 7 (0x7) .maxstack 1 .locals init ( [0] class Base`1<object modopt([mscorlib]System.Runtime.CompilerServices.IsLong)> ) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: br.s IL_0005 IL_0005: ldloc.0 IL_0006: ret } // end of method Test::GetBaseWithModifiers .method public hidebysig instance class Derived`1<object> GetDerivedWithoutModifiers () cil managed { // Method begins at RVA 0x2078 // Code size 7 (0x7) .maxstack 1 .locals init ( [0] class Derived`1<object> ) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: br.s IL_0005 IL_0005: ldloc.0 IL_0006: ret } // end of method Test::GetDerivedWithoutModifiers .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x2050 // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method Test::.ctor } // end of class Test ]]>.Value Dim source1 = <compilation> <file name="c.vb"><![CDATA[ ]]></file> </compilation> Dim comp1 = CreateCompilationWithCustomILSource(source1, il, appendDefaultHeader:=False) comp1.AssertTheseDiagnostics() Dim baseWithModifiers = comp1.GlobalNamespace.GetMember(Of MethodSymbol)("Test.GetBaseWithModifiers").ReturnType Assert.Equal("Base(Of System.Object modopt(System.Runtime.CompilerServices.IsLong))", baseWithModifiers.ToTestDisplayString()) Dim derivedWithoutModifiers = comp1.GlobalNamespace.GetMember(Of MethodSymbol)("Test.GetDerivedWithoutModifiers").ReturnType Assert.Equal("Derived(Of System.Object)", derivedWithoutModifiers.ToTestDisplayString()) Dim diagnostics = New HashSet(Of DiagnosticInfo)() Assert.True(baseWithModifiers.IsBaseTypeOf(derivedWithoutModifiers, diagnostics)) Assert.True(derivedWithoutModifiers.IsOrDerivedFrom(derivedWithoutModifiers, diagnostics)) End Sub <Fact> Public Sub WarnForDroppingNamesInConversion() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Tuples"> <file name="a.vb"><![CDATA[ Class C Sub M() Dim x1 As (a As Integer, Integer) = (1, b:=2) Dim x2 As (a As Integer, String) = (1, b:=Nothing) End Sub End Class ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC41009: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'. Dim x1 As (a As Integer, Integer) = (1, b:=2) ~~~~ BC41009: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(a As Integer, String)'. Dim x2 As (a As Integer, String) = (1, b:=Nothing) ~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub MethodTypeInferenceMergesTupleNames() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Tuples"> <file name="a.vb"><![CDATA[ Class C Sub M() Dim t = M2((a:=1, b:=2), (a:=1, c:=3)) System.Console.Write(t.a) System.Console.Write(t.b) System.Console.Write(t.c) M2((1, 2), (c:=1, d:=3)) M2({(a:=1, b:=2)}, {(1, 3)}) End Sub Function M2(Of T)(x1 As T, x2 As T) As T Return x1 End Function End Class ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC41009: The tuple element name 'b' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'. Dim t = M2((a:=1, b:=2), (a:=1, c:=3)) ~~~~ BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(a As Integer, Integer)'. Dim t = M2((a:=1, b:=2), (a:=1, c:=3)) ~~~~ BC30456: 'b' is not a member of '(a As Integer, Integer)'. System.Console.Write(t.b) ~~~ BC30456: 'c' is not a member of '(a As Integer, Integer)'. System.Console.Write(t.c) ~~~ BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(Integer, Integer)'. M2((1, 2), (c:=1, d:=3)) ~~~~ BC41009: The tuple element name 'd' is ignored because a different name or no name is specified by the target type '(Integer, Integer)'. M2((1, 2), (c:=1, d:=3)) ~~~~ </errors>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim invocation1 = model.GetSymbolInfo(nodes.OfType(Of InvocationExpressionSyntax)().First()) Assert.Equal("(a As System.Int32, System.Int32)", DirectCast(invocation1.Symbol, MethodSymbol).ReturnType.ToTestDisplayString()) Dim invocation2 = model.GetSymbolInfo(nodes.OfType(Of InvocationExpressionSyntax)().Skip(4).First()) Assert.Equal("(System.Int32, System.Int32)", DirectCast(invocation2.Symbol, MethodSymbol).ReturnType.ToTestDisplayString()) Dim invocation3 = model.GetSymbolInfo(nodes.OfType(Of InvocationExpressionSyntax)().Skip(5).First()) Assert.Equal("(a As System.Int32, b As System.Int32)()", DirectCast(invocation3.Symbol, MethodSymbol).ReturnType.ToTestDisplayString()) End Sub <Fact> Public Sub MethodTypeInferenceDropsCandidates() Dim comp = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Tuples"> <file name="a.vb"><![CDATA[ Class C Sub M() M2((a:=1, b:=2), (a:=CType(1, Byte), c:=CType(3, Byte))) M2((CType(1, Long), b:=2), (c:=1, d:=CType(3, Byte))) M2((a:=CType(1, Long), b:=2), (CType(1, Byte), 3)) End Sub Function M2(Of T)(x1 As T, x2 As T) As T Return x1 End Function End Class ]]></file> </compilation>, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(a As Integer, b As Integer)'. M2((a:=1, b:=2), (a:=CType(1, Byte), c:=CType(3, Byte))) ~~~~~~~~~~~~~~~~~ BC41009: The tuple element name 'c' is ignored because a different name or no name is specified by the target type '(Long, b As Integer)'. M2((CType(1, Long), b:=2), (c:=1, d:=CType(3, Byte))) ~~~~ BC41009: The tuple element name 'd' is ignored because a different name or no name is specified by the target type '(Long, b As Integer)'. M2((CType(1, Long), b:=2), (c:=1, d:=CType(3, Byte))) ~~~~~~~~~~~~~~~~~ </errors>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim invocation1 = model.GetSymbolInfo(nodes.OfType(Of InvocationExpressionSyntax)().First()) Assert.Equal("(a As System.Int32, b As System.Int32)", DirectCast(invocation1.Symbol, MethodSymbol).ReturnType.ToTestDisplayString()) Dim invocation2 = model.GetSymbolInfo(nodes.OfType(Of InvocationExpressionSyntax)().Skip(1).First()) Assert.Equal("(System.Int64, b As System.Int32)", DirectCast(invocation2.Symbol, MethodSymbol).ReturnType.ToTestDisplayString()) Dim invocation3 = model.GetSymbolInfo(nodes.OfType(Of InvocationExpressionSyntax)().Skip(2).First()) Assert.Equal("(a As System.Int64, b As System.Int32)", DirectCast(invocation3.Symbol, MethodSymbol).ReturnType.ToTestDisplayString()) End Sub <Fact()> <WorkItem(14267, "https://github.com/dotnet/roslyn/issues/14267")> Public Sub NoSystemRuntimeFacade() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim o = (1, 2) End Sub End Module ]]></file> </compilation>, additionalRefs:={ValueTupleRef}) Assert.Equal(TypeKind.Class, comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).TypeKind) comp.AssertTheseDiagnostics( <errors> BC30652: Reference required to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' containing the type 'ValueType'. Add one to your project. Dim o = (1, 2) ~~~~~~ </errors>) End Sub <Fact> <WorkItem(14888, "https://github.com/dotnet/roslyn/issues/14888")> Public Sub Iterator_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class C Shared Sub Main() For Each x in Test() Console.WriteLine(x) Next End Sub Shared Iterator Function Test() As IEnumerable(Of (integer, integer)) yield (1, 2) End Function End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:="(1, 2)") End Sub <Fact()> <WorkItem(14888, "https://github.com/dotnet/roslyn/issues/14888")> Public Sub Iterator_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class C Iterator Function Test() As IEnumerable(Of (integer, integer)) yield (1, 2) End Function End Class </file> </compilation>, additionalRefs:={ValueTupleRef}) comp.AssertTheseEmitDiagnostics( <errors> BC30652: Reference required to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' containing the type 'ValueType'. Add one to your project. Iterator Function Test() As IEnumerable(Of (integer, integer)) ~~~~~~~~~~~~~~~~~~ BC30652: Reference required to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' containing the type 'ValueType'. Add one to your project. yield (1, 2) ~~~~~~ </errors>) End Sub <Fact> <WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")> Public Sub UserDefinedConversionsAndNameMismatch_01() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Test((X1:=1, Y1:=2)) Dim t1 = (X1:=3, Y1:=4) Test(t1) Test((5, 6)) Dim t2 = (7, 8) Test(t2) End Sub Shared Sub Test(val As AA) End Sub End Class Public Class AA Public Shared Widening Operator CType(x As (X1 As Integer, Y1 As Integer)) As AA System.Console.WriteLine(x) return new AA() End Operator End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" (1, 2) (3, 4) (5, 6) (7, 8) ") End Sub <Fact> <WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")> Public Sub UserDefinedConversionsAndNameMismatch_02() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Test((X1:=1, Y1:=2)) Dim t1 = (X1:=3, Y1:=4) Test(t1) Test((5, 6)) Dim t2 = (7, 8) Test(t2) End Sub Shared Sub Test(val As AA?) End Sub End Class Public Structure AA Public Shared Widening Operator CType(x As (X1 As Integer, Y1 As Integer)) As AA System.Console.WriteLine(x) return new AA() End Operator End Structure </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" (1, 2) (3, 4) (5, 6) (7, 8) ") End Sub <Fact> <WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")> Public Sub UserDefinedConversionsAndNameMismatch_03() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Dim t1 As (X1 as Integer, Y1 as Integer)? = (X1:=3, Y1:=4) Test(t1) Dim t2 As (Integer, Integer)? = (7, 8) Test(t2) System.Console.WriteLine("--") t1 = Nothing Test(t1) t2 = Nothing Test(t2) System.Console.WriteLine("--") End Sub Shared Sub Test(val As AA?) End Sub End Class Public Structure AA Public Shared Widening Operator CType(x As (X1 As Integer, Y1 As Integer)) As AA System.Console.WriteLine(x) return new AA() End Operator End Structure </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" (3, 4) (7, 8) -- -- ") End Sub <Fact> <WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")> Public Sub UserDefinedConversionsAndNameMismatch_04() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Test(new AA()) End Sub Shared Sub Test(val As (X1 As Integer, Y1 As Integer)) System.Console.WriteLine(val) End Sub End Class Public Class AA Public Shared Widening Operator CType(x As AA) As (Integer, Integer) return (1, 2) End Operator End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:="(1, 2)") End Sub <Fact> <WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")> Public Sub UserDefinedConversionsAndNameMismatch_05() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Test(new AA()) End Sub Shared Sub Test(val As (X1 As Integer, Y1 As Integer)) System.Console.WriteLine(val) End Sub End Class Public Class AA Public Shared Widening Operator CType(x As AA) As (X1 As Integer, Y1 As Integer) return (1, 2) End Operator End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:="(1, 2)") End Sub <Fact> <WorkItem(269808, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=269808")> Public Sub UserDefinedConversionsAndNameMismatch_06() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class C Shared Sub Main() Dim t1 As BB(Of (X1 as Integer, Y1 as Integer))? = New BB(Of (X1 as Integer, Y1 as Integer))() Test(t1) Dim t2 As BB(Of (Integer, Integer))? = New BB(Of (Integer, Integer))() Test(t2) System.Console.WriteLine("--") t1 = Nothing Test(t1) t2 = Nothing Test(t2) System.Console.WriteLine("--") End Sub Shared Sub Test(val As AA?) End Sub End Class Public Structure AA Public Shared Widening Operator CType(x As BB(Of (X1 As Integer, Y1 As Integer))) As AA System.Console.WriteLine("implicit operator AA") return new AA() End Operator End Structure Public Structure BB(Of T) End Structure </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:=" implicit operator AA implicit operator AA -- -- ") End Sub <Fact> Public Sub GenericConstraintAttributes() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Imports System.Collections Imports System.Collections.Generic Imports ClassLibrary4 Public Interface ITest(Of T) ReadOnly Property [Get] As T End Interface Public Class Test Implements ITest(Of (key As Integer, val As Integer)) Public ReadOnly Property [Get] As (key As Integer, val As Integer) Implements ITest(Of (key As Integer, val As Integer)).Get Get Return (0, 0) End Get End Property End Class Public Class Base(Of T) : Implements ITest(Of T) Public ReadOnly Property [Get] As T Implements ITest(Of T).Get Protected Sub New(t As T) [Get] = t End Sub End Class Public Class C(Of T As ITest(Of (key As Integer, val As Integer))) Public ReadOnly Property [Get] As T Public Sub New(t As T) [Get] = t End Sub End Class Public Class C2(Of T As Base(Of (key As Integer, val As Integer))) Public ReadOnly Property [Get] As T Public Sub New(t As T) [Get] = t End Sub End Class Public NotInheritable Class Test2 Inherits Base(Of (key As Integer, val As Integer)) Sub New() MyBase.New((-1, -2)) End Sub End Class Public Class C3(Of T As IEnumerable(Of (key As Integer, val As Integer))) Public ReadOnly Property [Get] As T Public Sub New(t As T) [Get] = t End Sub End Class Public Structure TestEnumerable Implements IEnumerable(Of (key As Integer, val As Integer)) Private ReadOnly _backing As (Integer, Integer)() Public Sub New(backing As (Integer, Integer)()) _backing = backing End Sub Private Class Inner Implements IEnumerator(Of (key As Integer, val As Integer)), IEnumerator Private index As Integer = -1 Private ReadOnly _backing As (Integer, Integer)() Public Sub New(backing As (Integer, Integer)()) _backing = backing End Sub Public ReadOnly Property Current As (key As Integer, val As Integer) Implements IEnumerator(Of (key As Integer, val As Integer)).Current Get Return _backing(index) End Get End Property Public ReadOnly Property Current1 As Object Implements IEnumerator.Current Get Return Current End Get End Property Public Sub Dispose() Implements IDisposable.Dispose End Sub Public Function MoveNext() As Boolean index += 1 Return index &lt; _backing.Length End Function Public Sub Reset() Throw New NotSupportedException() End Sub Private Function IEnumerator_MoveNext() As Boolean Implements IEnumerator.MoveNext Return MoveNext() End Function Private Sub IEnumerator_Reset() Implements IEnumerator.Reset Throw New NotImplementedException() End Sub End Class Public Function GetEnumerator() As IEnumerator(Of (key As Integer, val As Integer)) Implements IEnumerable(Of (key As Integer, val As Integer)).GetEnumerator Return New Inner(_backing) End Function Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return New Inner(_backing) End Function End Structure </file> </compilation>, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, symbolValidator:=Sub(m) Dim c = m.GlobalNamespace.GetTypeMember("C") Assert.Equal(1, c.TypeParameters.Length) Dim param = c.TypeParameters(0) Assert.Equal(1, param.ConstraintTypes.Length) Dim constraint = Assert.IsAssignableFrom(Of NamedTypeSymbol)(param.ConstraintTypes(0)) Assert.True(constraint.IsGenericType) Assert.Equal(1, constraint.TypeArguments.Length) Dim typeArg As TypeSymbol = constraint.TypeArguments(0) Assert.True(typeArg.IsTupleType) Assert.Equal(2, typeArg.TupleElementTypes.Length) Assert.All(typeArg.TupleElementTypes, Sub(t) Assert.Equal(SpecialType.System_Int32, t.SpecialType)) Assert.False(typeArg.TupleElementNames.IsDefault) Assert.Equal(2, typeArg.TupleElementNames.Length) Assert.Equal({"key", "val"}, typeArg.TupleElementNames) Dim c2 = m.GlobalNamespace.GetTypeMember("C2") Assert.Equal(1, c2.TypeParameters.Length) param = c2.TypeParameters(0) Assert.Equal(1, param.ConstraintTypes.Length) constraint = Assert.IsAssignableFrom(Of NamedTypeSymbol)(param.ConstraintTypes(0)) Assert.True(constraint.IsGenericType) Assert.Equal(1, constraint.TypeArguments.Length) typeArg = constraint.TypeArguments(0) Assert.True(typeArg.IsTupleType) Assert.Equal(2, typeArg.TupleElementTypes.Length) Assert.All(typeArg.TupleElementTypes, Sub(t) Assert.Equal(SpecialType.System_Int32, t.SpecialType)) Assert.False(typeArg.TupleElementNames.IsDefault) Assert.Equal(2, typeArg.TupleElementNames.Length) Assert.Equal({"key", "val"}, typeArg.TupleElementNames) End Sub ) Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Dim c = New C(Of Test)(New Test()) Dim temp = c.Get.Get Console.WriteLine(temp) Console.WriteLine("key: " &amp; temp.key) Console.WriteLine("val: " &amp; temp.val) Dim c2 = New C2(Of Test2)(New Test2()) Dim temp2 = c2.Get.Get Console.WriteLine(temp2) Console.WriteLine("key: " &amp; temp2.key) Console.WriteLine("val: " &amp; temp2.val) Dim backing = {(1, 2), (3, 4), (5, 6)} Dim c3 = New C3(Of TestEnumerable)(New TestEnumerable(backing)) For Each kvp In c3.Get Console.WriteLine($"key: {kvp.key}, val: {kvp.val}") Next Dim c4 = New C(Of Test2)(New Test2()) Dim temp4 = c4.Get.Get Console.WriteLine(temp4) Console.WriteLine("key: " &amp; temp4.key) Console.WriteLine("val: " &amp; temp4.val) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs.Concat({comp.EmitToImageReference()}).ToArray(), expectedOutput:=<![CDATA[ (0, 0) key: 0 val: 0 (-1, -2) key: -1 val: -2 key: 1, val: 2 key: 3, val: 4 key: 5, val: 6 (-1, -2) key: -1 val: -2 ]]>) End Sub <Fact> Public Sub UnusedTuple() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Class C Sub M() ' Warnings Dim x2 As Integer Const x3 As Integer = 1 Const x4 As String = "hello" Dim x5 As (Integer, Integer) Dim x6 As (String, String) ' No warnings Dim y10 As Integer = 1 Dim y11 As String = "hello" Dim y12 As (Integer, Integer) = (1, 2) Dim y13 As (String, String) = ("hello", "world") Dim tuple As (String, String) = ("hello", "world") Dim y14 As (String, String) = tuple Dim y15 = (2, 3) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> BC42024: Unused local variable: 'x2'. Dim x2 As Integer ~~ BC42099: Unused local constant: 'x3'. Const x3 As Integer = 1 ~~ BC42099: Unused local constant: 'x4'. Const x4 As String = "hello" ~~ BC42024: Unused local variable: 'x5'. Dim x5 As (Integer, Integer) ~~ BC42024: Unused local variable: 'x6'. Dim x6 As (String, String) ~~ </errors>) End Sub <Fact> <WorkItem(15198, "https://github.com/dotnet/roslyn/issues/15198")> Public Sub TuplePropertyArgs001() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class C Shared Sub Main() dim inst = new C dim f As (Integer, Integer) = (inst.P1, inst.P1) System.Console.WriteLine(f) End Sub public readonly Property P1 as integer Get return 42 End Get end Property End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:="(42, 42)") End Sub <Fact> <WorkItem(15198, "https://github.com/dotnet/roslyn/issues/15198")> Public Sub TuplePropertyArgs002() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class C Shared Sub Main() dim inst = new C dim f As IComparable(of (Integer, Integer)) = (inst.P1, inst.P1) System.Console.WriteLine(f) End Sub public readonly Property P1 as integer Get return 42 End Get end Property End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:="(42, 42)") End Sub <Fact> <WorkItem(15198, "https://github.com/dotnet/roslyn/issues/15198")> Public Sub TuplePropertyArgs003() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Public Class C Shared Sub Main() dim inst as Object = new C dim f As (Integer, Integer) = (inst.P1, inst.P1) System.Console.WriteLine(f) End Sub public readonly Property P1 as integer Get return 42 End Get end Property End Class </file> </compilation>, options:=TestOptions.ReleaseExe, additionalRefs:=s_valueTupleRefs) CompileAndVerify(comp, expectedOutput:="(42, 42)") End Sub <Fact> <WorkItem(14844, "https://github.com/dotnet/roslyn/issues/14844")> Public Sub InterfaceImplAttributesAreNotSharedAcrossTypeRefs() Dim src1 = <compilation> <file name="a.vb"> <![CDATA[ Public Interface I1(Of T) End Interface Public Interface I2 Inherits I1(Of (a As Integer, b As Integer)) End Interface Public Interface I3 Inherits I1(Of (c As Integer, d As Integer)) End Interface ]]> </file> </compilation> Dim src2 = <compilation> <file name="a.vb"> <![CDATA[ Class C1 Implements I2 Implements I1(Of (a As Integer, b As Integer)) End Class Class C2 Implements I3 Implements I1(Of (c As Integer, d As Integer)) End Class ]]> </file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(src1, references:=s_valueTupleRefs) AssertTheseDiagnostics(comp1) Dim comp2 = CreateCompilationWithMscorlib40(src2, references:={SystemRuntimeFacadeRef, ValueTupleRef, comp1.ToMetadataReference()}) AssertTheseDiagnostics(comp2) Dim comp3 = CreateCompilationWithMscorlib40(src2, references:={SystemRuntimeFacadeRef, ValueTupleRef, comp1.EmitToImageReference()}) AssertTheseDiagnostics(comp3) End Sub <Fact()> <WorkItem(14881, "https://github.com/dotnet/roslyn/issues/14881")> <WorkItem(15476, "https://github.com/dotnet/roslyn/issues/15476")> Public Sub TupleElementVsLocal() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module C Sub Main() Dim tuple As (Integer, elem2 As Integer) Dim elem2 As Integer tuple = (5, 6) tuple.elem2 = 23 elem2 = 10 Console.WriteLine(tuple.elem2) Console.WriteLine(elem2) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Where(Function(id) id.Identifier.ValueText = "elem2").ToArray() Assert.Equal(4, nodes.Length) Assert.Equal("tuple.elem2 = 23", nodes(0).Parent.Parent.ToString()) Assert.Equal("(System.Int32, elem2 As System.Int32).elem2 As System.Int32", model.GetSymbolInfo(nodes(0)).Symbol.ToTestDisplayString()) Assert.Equal("elem2 = 10", nodes(1).Parent.ToString()) Assert.Equal("elem2 As System.Int32", model.GetSymbolInfo(nodes(1)).Symbol.ToTestDisplayString()) Assert.Equal("(tuple.elem2)", nodes(2).Parent.Parent.Parent.ToString()) Assert.Equal("(System.Int32, elem2 As System.Int32).elem2 As System.Int32", model.GetSymbolInfo(nodes(2)).Symbol.ToTestDisplayString()) Assert.Equal("(elem2)", nodes(3).Parent.Parent.ToString()) Assert.Equal("elem2 As System.Int32", model.GetSymbolInfo(nodes(3)).Symbol.ToTestDisplayString()) Dim type = tree.GetRoot().DescendantNodes().OfType(Of TupleTypeSyntax)().Single() Dim symbolInfo = model.GetSymbolInfo(type) Assert.Equal("(System.Int32, elem2 As System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Dim typeInfo = model.GetTypeInfo(type) Assert.Equal("(System.Int32, elem2 As System.Int32)", typeInfo.Type.ToTestDisplayString()) Assert.Same(symbolInfo.Symbol, typeInfo.Type) Assert.Equal(SyntaxKind.TypedTupleElement, type.Elements.First().Kind()) Assert.Equal("(System.Int32, elem2 As System.Int32).Item1 As System.Int32", model.GetDeclaredSymbol(type.Elements.First()).ToTestDisplayString()) Assert.Equal(SyntaxKind.NamedTupleElement, type.Elements.Last().Kind()) Assert.Equal("(System.Int32, elem2 As System.Int32).elem2 As System.Int32", model.GetDeclaredSymbol(type.Elements.Last()).ToTestDisplayString()) Assert.Equal("(System.Int32, elem2 As System.Int32).Item1 As System.Int32", model.GetDeclaredSymbol(DirectCast(type.Elements.First(), SyntaxNode)).ToTestDisplayString()) Assert.Equal("(System.Int32, elem2 As System.Int32).elem2 As System.Int32", model.GetDeclaredSymbol(DirectCast(type.Elements.Last(), SyntaxNode)).ToTestDisplayString()) End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub ImplementSameInterfaceViaBaseWithDifferentTupleNames() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Interface ITest(Of T) End Interface Class Base Implements ITest(Of (a As Integer, b As Integer)) End Class Class Derived Inherits Base Implements ITest(Of (notA As Integer, notB As Integer)) End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim derived = tree.GetRoot().DescendantNodes().OfType(Of ClassStatementSyntax)().ElementAt(1) Dim derivedSymbol = model.GetDeclaredSymbol(derived) Assert.Equal("Derived", derivedSymbol.ToTestDisplayString()) Assert.Equal(New String() { "ITest(Of (a As System.Int32, b As System.Int32))", "ITest(Of (notA As System.Int32, notB As System.Int32))"}, derivedSymbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString())) End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub ImplementSameInterfaceViaBase() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Interface ITest(Of T) End Interface Class Base Implements ITest(Of Integer) End Class Class Derived Inherits Base Implements ITest(Of Integer) End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim derived = tree.GetRoot().DescendantNodes().OfType(Of ClassStatementSyntax)().ElementAt(1) Dim derivedSymbol = model.GetDeclaredSymbol(derived) Assert.Equal("Derived", derivedSymbol.ToTestDisplayString()) Assert.Equal(New String() {"ITest(Of System.Int32)"}, derivedSymbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString())) End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub GenericImplementSameInterfaceViaBaseWithoutTuples() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Interface ITest(Of T) End Interface Class Base Implements ITest(Of Integer) End Class Class Derived(Of T) Inherits Base Implements ITest(Of T) End Class Module M Sub Main() Dim instance1 = New Derived(Of Integer) Dim instance2 = New Derived(Of String) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim derived = tree.GetRoot().DescendantNodes().OfType(Of ClassStatementSyntax)().ElementAt(1) Dim derivedSymbol = DirectCast(model.GetDeclaredSymbol(derived), NamedTypeSymbol) Assert.Equal("Derived(Of T)", derivedSymbol.ToTestDisplayString()) Assert.Equal(New String() {"ITest(Of System.Int32)", "ITest(Of T)"}, derivedSymbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString())) Dim instance1 = tree.GetRoot().DescendantNodes().OfType(Of VariableDeclaratorSyntax)().ElementAt(0).Names(0) Dim instance1Symbol = DirectCast(model.GetDeclaredSymbol(instance1), LocalSymbol).Type Assert.Equal("Derived(Of Integer)", instance1Symbol.ToString()) Assert.Equal(New String() {"ITest(Of System.Int32)"}, instance1Symbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString())) Dim instance2 = tree.GetRoot().DescendantNodes().OfType(Of VariableDeclaratorSyntax)().ElementAt(1).Names(0) Dim instance2Symbol = DirectCast(model.GetDeclaredSymbol(instance2), LocalSymbol).Type Assert.Equal("Derived(Of String)", instance2Symbol.ToString()) Assert.Equal(New String() {"ITest(Of System.Int32)", "ITest(Of System.String)"}, instance2Symbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString())) Assert.Empty(derivedSymbol.AsUnboundGenericType().AllInterfaces) End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub GenericImplementSameInterfaceViaBase() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Interface ITest(Of T) End Interface Class Base Implements ITest(Of (a As Integer, b As Integer)) End Class Class Derived(Of T) Inherits Base Implements ITest(Of T) End Class Module M Sub Main() Dim instance1 = New Derived(Of (notA As Integer, notB As Integer)) Dim instance2 = New Derived(Of (notA As String, notB As String)) End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() Dim tree = compilation.SyntaxTrees.First() Dim model = compilation.GetSemanticModel(tree) Dim derived = tree.GetRoot().DescendantNodes().OfType(Of ClassStatementSyntax)().ElementAt(1) Dim derivedSymbol = model.GetDeclaredSymbol(derived) Assert.Equal("Derived(Of T)", derivedSymbol.ToTestDisplayString()) Assert.Equal(New String() {"ITest(Of (a As System.Int32, b As System.Int32))", "ITest(Of T)"}, derivedSymbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString())) Dim instance1 = tree.GetRoot().DescendantNodes().OfType(Of VariableDeclaratorSyntax)().ElementAt(0).Names(0) Dim instance1Symbol = DirectCast(model.GetDeclaredSymbol(instance1), LocalSymbol).Type Assert.Equal("Derived(Of (notA As Integer, notB As Integer))", instance1Symbol.ToString()) Assert.Equal(New String() { "ITest(Of (a As System.Int32, b As System.Int32))", "ITest(Of (notA As System.Int32, notB As System.Int32))"}, instance1Symbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString())) Dim instance2 = tree.GetRoot().DescendantNodes().OfType(Of VariableDeclaratorSyntax)().ElementAt(1).Names(0) Dim instance2Symbol = DirectCast(model.GetDeclaredSymbol(instance2), LocalSymbol).Type Assert.Equal("Derived(Of (notA As String, notB As String))", instance2Symbol.ToString()) Assert.Equal(New String() { "ITest(Of (a As System.Int32, b As System.Int32))", "ITest(Of (notA As System.String, notB As System.String))"}, instance2Symbol.AllInterfaces.Select(Function(i) i.ToTestDisplayString())) End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub GenericExplicitIEnumerableImplementationUsedWithDifferentTypesAndTupleNames() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections Imports System.Collections.Generic Class Base Implements IEnumerable(Of (a As Integer, b As Integer)) Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator Throw New Exception() End Function Function GetEnumerator2() As IEnumerator(Of (a As Integer, b As Integer)) Implements IEnumerable(Of (a As Integer, b As Integer)).GetEnumerator Throw New Exception() End Function End Class Class Derived(Of T) Inherits Base Implements IEnumerable(Of T) Public Dim state As T Function GetEnumerator3() As IEnumerator Implements IEnumerable.GetEnumerator Throw New Exception() End Function Function GetEnumerator4() As IEnumerator(Of T) Implements IEnumerable(Of T).GetEnumerator Return New DerivedEnumerator With {.state = state} End Function Public Class DerivedEnumerator Implements IEnumerator(Of T) Public Dim state As T Dim done As Boolean = False Function MoveNext() As Boolean Implements IEnumerator.MoveNext If done Then Return False Else done = True Return True End If End Function ReadOnly Property Current As T Implements IEnumerator(Of T).Current Get Return state End Get End Property ReadOnly Property Current2 As Object Implements IEnumerator.Current Get Throw New Exception() End Get End Property Public Sub Dispose() Implements IDisposable.Dispose End Sub Public Sub Reset() Implements IEnumerator.Reset End Sub End Class End Class Module M Sub Main() Dim collection = New Derived(Of (notA As String, notB As String)) With {.state = (42, 43)} For Each x In collection Console.Write(x.notA) Next End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) compilation.AssertTheseDiagnostics(<errors> BC32096: 'For Each' on type 'Derived(Of (notA As String, notB As String))' is ambiguous because the type implements multiple instantiations of 'System.Collections.Generic.IEnumerable(Of T)'. For Each x In collection ~~~~~~~~~~ </errors>) End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub GenericExplicitIEnumerableImplementationUsedWithDifferentTupleNames() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections Imports System.Collections.Generic Class Base Implements IEnumerable(Of (a As Integer, b As Integer)) Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator Throw New Exception() End Function Function GetEnumerator2() As IEnumerator(Of (a As Integer, b As Integer)) Implements IEnumerable(Of (a As Integer, b As Integer)).GetEnumerator Throw New Exception() End Function End Class Class Derived(Of T) Inherits Base Implements IEnumerable(Of T) Public Dim state As T Function GetEnumerator3() As IEnumerator Implements IEnumerable.GetEnumerator Throw New Exception() End Function Function GetEnumerator4() As IEnumerator(Of T) Implements IEnumerable(Of T).GetEnumerator Return New DerivedEnumerator With {.state = state} End Function Public Class DerivedEnumerator Implements IEnumerator(Of T) Public Dim state As T Dim done As Boolean = False Function MoveNext() As Boolean Implements IEnumerator.MoveNext If done Then Return False Else done = True Return True End If End Function ReadOnly Property Current As T Implements IEnumerator(Of T).Current Get Return state End Get End Property ReadOnly Property Current2 As Object Implements IEnumerator.Current Get Throw New Exception() End Get End Property Public Sub Dispose() Implements IDisposable.Dispose End Sub Public Sub Reset() Implements IEnumerator.Reset End Sub End Class End Class Module M Sub Main() Dim collection = New Derived(Of (notA As Integer, notB As Integer)) With {.state = (42, 43)} For Each x In collection Console.Write(x.notA) Next End Sub End Module ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) compilation.AssertTheseDiagnostics() CompileAndVerify(compilation, expectedOutput:="42") End Sub <Fact()> <WorkItem(14843, "https://github.com/dotnet/roslyn/issues/14843")> Public Sub TupleNameDifferencesIgnoredInConstraintWhenNotIdentityConversion() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Interface I1(Of T) End Interface Class Base(Of U As I1(Of (a As Integer, b As Integer))) End Class Class Derived Inherits Base(Of I1(Of (notA As Integer, notB As Integer))) End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() End Sub <Fact()> <WorkItem(14843, "https://github.com/dotnet/roslyn/issues/14843")> Public Sub TupleNameDifferencesIgnoredInConstraintWhenNotIdentityConversion2() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Interface I1(Of T) End Interface Interface I2(Of T) Inherits I1(Of T) End Interface Class Base(Of U As I1(Of (a As Integer, b As Integer))) End Class Class Derived Inherits Base(Of I2(Of (notA As Integer, notB As Integer))) End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub CanReImplementInterfaceWithDifferentTupleNames() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Interface ITest(Of T) Function M() As T End Interface Class Base Implements ITest(Of (a As Integer, b As Integer)) Function M() As (a As Integer, b As Integer) Implements ITest(Of (a As Integer, b As Integer)).M Return (1, 2) End Function End Class Class Derived Inherits Base Implements ITest(Of (notA As Integer, notB As Integer)) Overloads Function M() As (notA As Integer, notB As Integer) Implements ITest(Of (notA As Integer, notB As Integer)).M Return (3, 4) End Function End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics() End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_01() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Interface ITest(Of T) Function M() As T End Interface Class Base Implements ITest(Of (a As Integer, b As Integer)) Function M() As (a As Integer, b As Integer) Implements ITest(Of (a As Integer, b As Integer)).M Return (1, 2) End Function End Class Class Derived1 Inherits Base Implements ITest(Of (notA As Integer, notB As Integer)) End Class Class Derived2 Inherits Base Implements ITest(Of (a As Integer, b As Integer)) End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics(<errors> BC30149: Class 'Derived1' must implement 'Function M() As (notA As Integer, notB As Integer)' for interface 'ITest(Of (notA As Integer, notB As Integer))'. Implements ITest(Of (notA As Integer, notB As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_02() Dim csSource = " public interface ITest<T> { T M(); } public class Base : ITest<(int a, int b)> { (int a, int b) ITest<(int a, int b)>.M() { return (1, 2); } // explicit implementation public virtual (int notA, int notB) M() { return (1, 2); } } " Dim csComp = CreateCSharpCompilation(csSource, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedAssemblies:=TargetFrameworkUtil.GetReferences(TargetFramework.StandardAndVBRuntime)) csComp.VerifyDiagnostics() Dim comp = CreateCompilation( <compilation> <file name="a.vb"><![CDATA[ Class Derived1 Inherits Base Implements ITest(Of (notA As Integer, notB As Integer)) End Class Class Derived2 Inherits Base Implements ITest(Of (a As Integer, b As Integer)) End Class ]]></file> </compilation>, references:={csComp.EmitToImageReference()}) comp.AssertTheseDiagnostics(<errors> BC30149: Class 'Derived1' must implement 'Function M() As (notA As Integer, notB As Integer)' for interface 'ITest(Of (notA As Integer, notB As Integer))'. Implements ITest(Of (notA As Integer, notB As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) Dim derived1 As INamedTypeSymbol = comp.GetTypeByMetadataName("Derived1") Assert.Equal("ITest(Of (notA As System.Int32, notB As System.Int32))", derived1.Interfaces(0).ToTestDisplayString()) Dim derived2 As INamedTypeSymbol = comp.GetTypeByMetadataName("Derived2") Assert.Equal("ITest(Of (a As System.Int32, b As System.Int32))", derived2.Interfaces(0).ToTestDisplayString()) Dim m = comp.GetTypeByMetadataName("Base").GetMembers("ITest<(System.Int32a,System.Int32b)>.M").Single() Dim mImplementations = DirectCast(m, IMethodSymbol).ExplicitInterfaceImplementations Assert.Equal(1, mImplementations.Length) Assert.Equal("Function ITest(Of (System.Int32, System.Int32)).M() As (System.Int32, System.Int32)", mImplementations(0).ToTestDisplayString()) Assert.Same(m, derived1.FindImplementationForInterfaceMember(DirectCast(derived1.Interfaces(0), TypeSymbol).GetMember("M"))) Assert.Same(m, derived1.FindImplementationForInterfaceMember(DirectCast(derived2.Interfaces(0), TypeSymbol).GetMember("M"))) Assert.Same(m, derived2.FindImplementationForInterfaceMember(DirectCast(derived1.Interfaces(0), TypeSymbol).GetMember("M"))) Assert.Same(m, derived2.FindImplementationForInterfaceMember(DirectCast(derived2.Interfaces(0), TypeSymbol).GetMember("M"))) End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_03() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Interface ITest(Of T) Function M() As T End Interface Class Base Implements ITest(Of (a As Integer, b As Integer)) End Class Class Derived1 Inherits Base Implements ITest(Of (notA As Integer, notB As Integer)) End Class Class Derived2 Inherits Base Implements ITest(Of (a As Integer, b As Integer)) End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) compilation.AssertTheseDiagnostics(<errors> BC30149: Class 'Base' must implement 'Function M() As (a As Integer, b As Integer)' for interface 'ITest(Of (a As Integer, b As Integer))'. Implements ITest(Of (a As Integer, b As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30149: Class 'Derived1' must implement 'Function M() As (notA As Integer, notB As Integer)' for interface 'ITest(Of (notA As Integer, notB As Integer))'. Implements ITest(Of (notA As Integer, notB As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_04() Dim compilation1 = CreateCompilation( <compilation> <file name="a.vb"><![CDATA[ Public Interface ITest(Of T) Function M() As T End Interface Public Class Base Implements ITest(Of (a As Integer, b As Integer)) End Class ]]></file> </compilation>) compilation1.AssertTheseDiagnostics(<errors> BC30149: Class 'Base' must implement 'Function M() As (a As Integer, b As Integer)' for interface 'ITest(Of (a As Integer, b As Integer))'. Implements ITest(Of (a As Integer, b As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) Dim compilation2 = CreateCompilation( <compilation> <file name="a.vb"><![CDATA[ Class Derived1 Inherits Base Implements ITest(Of (notA As Integer, notB As Integer)) End Class Class Derived2 Inherits Base Implements ITest(Of (a As Integer, b As Integer)) End Class ]]></file> </compilation>, references:={compilation1.ToMetadataReference()}) compilation2.AssertTheseDiagnostics(<errors> BC30149: Class 'Derived1' must implement 'Function M() As (notA As Integer, notB As Integer)' for interface 'ITest(Of (notA As Integer, notB As Integer))'. Implements ITest(Of (notA As Integer, notB As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub ExplicitBaseImplementationNotConsideredImplementationForInterfaceWithDifferentTupleNames_05() Dim csSource = " public interface ITest<T> { T M(); } public class Base : ITest<(int a, int b)> { public virtual (int a, int b) M() { return (1, 2); } } " Dim csComp = CreateCSharpCompilation(csSource, compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), referencedAssemblies:=TargetFrameworkUtil.GetReferences(TargetFramework.StandardAndVBRuntime)) csComp.VerifyDiagnostics() Dim comp = CreateCompilation( <compilation> <file name="a.vb"><![CDATA[ Class Derived1 Inherits Base Implements ITest(Of (notA As Integer, notB As Integer)) End Class Class Derived2 Inherits Base Implements ITest(Of (a As Integer, b As Integer)) End Class ]]></file> </compilation>, references:={csComp.EmitToImageReference()}) comp.AssertTheseDiagnostics(<errors> BC30149: Class 'Derived1' must implement 'Function M() As (notA As Integer, notB As Integer)' for interface 'ITest(Of (notA As Integer, notB As Integer))'. Implements ITest(Of (notA As Integer, notB As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) Dim derived1 As INamedTypeSymbol = comp.GetTypeByMetadataName("Derived1") Assert.Equal("ITest(Of (notA As System.Int32, notB As System.Int32))", derived1.Interfaces(0).ToTestDisplayString()) Dim derived2 As INamedTypeSymbol = comp.GetTypeByMetadataName("Derived2") Assert.Equal("ITest(Of (a As System.Int32, b As System.Int32))", derived2.Interfaces(0).ToTestDisplayString()) Dim m = comp.GetTypeByMetadataName("Base").GetMember("M") Dim mImplementations = DirectCast(m, IMethodSymbol).ExplicitInterfaceImplementations Assert.Equal(0, mImplementations.Length) Assert.Same(m, derived1.FindImplementationForInterfaceMember(DirectCast(derived1.Interfaces(0), TypeSymbol).GetMember("M"))) Assert.Same(m, derived1.FindImplementationForInterfaceMember(DirectCast(derived2.Interfaces(0), TypeSymbol).GetMember("M"))) Assert.Same(m, derived2.FindImplementationForInterfaceMember(DirectCast(derived1.Interfaces(0), TypeSymbol).GetMember("M"))) Assert.Same(m, derived2.FindImplementationForInterfaceMember(DirectCast(derived2.Interfaces(0), TypeSymbol).GetMember("M"))) End Sub <Fact()> <WorkItem(14841, "https://github.com/dotnet/roslyn/issues/14841")> Public Sub ReImplementationAndInference() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Interface ITest(Of T) Function M() As T End Interface Class Base Implements ITest(Of (a As Integer, b As Integer)) Function M() As (a As Integer, b As Integer) Implements ITest(Of (a As Integer, b As Integer)).M Return (1, 2) End Function End Class Class Derived Inherits Base Implements ITest(Of (notA As Integer, notB As Integer)) Overloads Function M() As (notA As Integer, notB As Integer) Implements ITest(Of (notA As Integer, notB As Integer)).M Return (3, 4) End Function End Class Class C Shared Sub Main() Dim b As Base = New Derived() Dim x = Test(b) ' tuple names from Base, implementation from Derived System.Console.WriteLine(x.a) End Sub Shared Function Test(Of T)(t1 As ITest(Of T)) As T Return t1.M() End Function End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics() CompileAndVerify(comp, expectedOutput:="3") Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim x = nodes.OfType(Of VariableDeclaratorSyntax)().ElementAt(1).Names(0) Assert.Equal("x", x.Identifier.ToString()) Dim xSymbol = DirectCast(model.GetDeclaredSymbol(x), LocalSymbol).Type Assert.Equal("(a As System.Int32, b As System.Int32)", xSymbol.ToTestDisplayString()) End Sub <Fact()> <WorkItem(14091, "https://github.com/dotnet/roslyn/issues/14091")> Public Sub TupleTypeWithTooFewElements() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M(x As Integer, y As (), z As (a As Integer)) End Sub End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics(<errors> BC30182: Type expected. Shared Sub M(x As Integer, y As (), z As (a As Integer)) ~ BC37259: Tuple must contain at least two elements. Shared Sub M(x As Integer, y As (), z As (a As Integer)) ~ BC37259: Tuple must contain at least two elements. Shared Sub M(x As Integer, y As (), z As (a As Integer)) ~ </errors>) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim y = nodes.OfType(Of TupleTypeSyntax)().ElementAt(0) Assert.Equal("()", y.ToString()) Dim yType = model.GetTypeInfo(y) Assert.Equal("(?, ?)", yType.Type.ToTestDisplayString()) Dim z = nodes.OfType(Of TupleTypeSyntax)().ElementAt(1) Assert.Equal("(a As Integer)", z.ToString()) Dim zType = model.GetTypeInfo(z) Assert.Equal("(a As System.Int32, ?)", zType.Type.ToTestDisplayString()) End Sub <Fact()> <WorkItem(14091, "https://github.com/dotnet/roslyn/issues/14091")> Public Sub TupleExpressionWithTooFewElements() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class C Dim x = (Alice:=1) End Class ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics(<errors> BC37259: Tuple must contain at least two elements. Dim x = (Alice:=1) ~ </errors>) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim nodes = comp.SyntaxTrees(0).GetCompilationUnitRoot().DescendantNodes() Dim tuple = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(0) Assert.Equal("(Alice:=1)", tuple.ToString()) Dim tupleType = model.GetTypeInfo(tuple) Assert.Equal("(Alice As System.Int32, ?)", tupleType.Type.ToTestDisplayString()) End Sub <Fact> Public Sub GetWellKnownTypeWithAmbiguities() Const versionTemplate = "<Assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")>" Const corlib_vb = " Namespace System Public Class [Object] End Class Public Structure Void End Structure Public Class ValueType End Class Public Structure IntPtr End Structure Public Structure Int32 End Structure Public Class [String] End Class Public Class Attribute End Class End Namespace Namespace System.Reflection Public Class AssemblyVersionAttribute Inherits Attribute Public Sub New(version As String) End Sub End Class End Namespace " Const valuetuple_vb As String = " Namespace System Public Structure ValueTuple(Of T1, T2) Public Dim Item1 As T1 Public Dim Item2 As T2 Public Sub New(item1 As T1, item2 As T2) End Sub End Structure End Namespace " Dim corlibWithoutVT = CreateEmptyCompilation({String.Format(versionTemplate, "1") + corlib_vb}, options:=TestOptions.DebugDll, assemblyName:="corlib") corlibWithoutVT.AssertTheseDiagnostics() Dim corlibWithoutVTRef = corlibWithoutVT.EmitToImageReference() Dim corlibWithVT = CreateEmptyCompilation({String.Format(versionTemplate, "2") + corlib_vb + valuetuple_vb}, options:=TestOptions.DebugDll, assemblyName:="corlib") corlibWithVT.AssertTheseDiagnostics() Dim corlibWithVTRef = corlibWithVT.EmitToImageReference() Dim libWithVT = CreateEmptyCompilation(valuetuple_vb, references:={corlibWithoutVTRef}, options:=TestOptions.DebugDll) libWithVT.VerifyDiagnostics() Dim libWithVTRef = libWithVT.EmitToImageReference() Dim comp = VisualBasicCompilation.Create("test", references:={libWithVTRef, corlibWithVTRef}) Dim found = comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2) Assert.False(found.IsErrorType()) Assert.Equal("corlib", found.ContainingAssembly.Name) Dim comp2 = comp.WithOptions(comp.Options.WithIgnoreCorLibraryDuplicatedTypes(True)) Dim tuple2 = comp2.GetWellKnownType(WellKnownType.System_ValueTuple_T2) Assert.False(tuple2.IsErrorType()) Assert.Equal(libWithVTRef.Display, tuple2.ContainingAssembly.MetadataName.ToString()) Dim comp3 = VisualBasicCompilation.Create("test", references:={corlibWithVTRef, libWithVTRef}). ' order reversed WithOptions(comp.Options.WithIgnoreCorLibraryDuplicatedTypes(True)) Dim tuple3 = comp3.GetWellKnownType(WellKnownType.System_ValueTuple_T2) Assert.False(tuple3.IsErrorType()) Assert.Equal(libWithVTRef.Display, tuple3.ContainingAssembly.MetadataName.ToString()) End Sub <Fact> Public Sub CheckedConversions() Dim source = <compilation> <file> Imports System Class C Shared Function F(t As (Integer, Integer)) As (Long, Byte) Return CType(t, (Long, Byte)) End Function Shared Sub Main() Try Dim t = F((-1, -1)) Console.WriteLine(t) Catch e As OverflowException Console.WriteLine("overflow") End Try End Sub End Class </file> </compilation> Dim verifier = CompileAndVerify( source, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), references:=s_valueTupleRefs, expectedOutput:=<![CDATA[(-1, 255)]]>) verifier.VerifyIL("C.F", <![CDATA[ { // Code size 22 (0x16) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer) V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0008: conv.i8 IL_0009: ldloc.0 IL_000a: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_000f: conv.u1 IL_0010: newobj "Sub System.ValueTuple(Of Long, Byte)..ctor(Long, Byte)" IL_0015: ret } ]]>) verifier = CompileAndVerify( source, options:=TestOptions.ReleaseExe.WithOverflowChecks(True), references:=s_valueTupleRefs, expectedOutput:=<![CDATA[overflow]]>) verifier.VerifyIL("C.F", <![CDATA[ { // Code size 22 (0x16) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer) V_0) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldfld "System.ValueTuple(Of Integer, Integer).Item1 As Integer" IL_0008: conv.i8 IL_0009: ldloc.0 IL_000a: ldfld "System.ValueTuple(Of Integer, Integer).Item2 As Integer" IL_000f: conv.ovf.u1 IL_0010: newobj "Sub System.ValueTuple(Of Long, Byte)..ctor(Long, Byte)" IL_0015: ret } ]]>) End Sub <Fact> <WorkItem(18738, "https://github.com/dotnet/roslyn/issues/18738")> Public Sub TypelessTupleWithNoImplicitConversion() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> option strict on Imports System Module C Sub M() Dim e As Integer? = 5 Dim x as (Integer, String) = (e, Nothing) ' No implicit conversion System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics(<errors> BC30512: Option Strict On disallows implicit conversions from 'Integer?' to 'Integer'. Dim x as (Integer, String) = (e, Nothing) ' No implicit conversion ~ </errors>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e, Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Assert.Equal("(System.Int32, System.String)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.NarrowingTuple, model.GetConversion(node).Kind) End Sub <Fact> <WorkItem(18738, "https://github.com/dotnet/roslyn/issues/18738")> Public Sub TypelessTupleWithNoImplicitConversion2() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> option strict on Imports System Module C Sub M() Dim e As Integer? = 5 Dim x as (Integer, String, Integer) = (e, Nothing) ' No conversion System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics(<errors> BC30311: Value of type '(e As Integer?, Object)' cannot be converted to '(Integer, String, Integer)'. Dim x as (Integer, String, Integer) = (e, Nothing) ' No conversion ~~~~~~~~~~~~ </errors>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e, Nothing)", node.ToString()) Assert.Null(model.GetTypeInfo(node).Type) Assert.Equal("(System.Int32, System.String, System.Int32)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.DelegateRelaxationLevelNone, model.GetConversion(node).Kind) End Sub <Fact> <WorkItem(18738, "https://github.com/dotnet/roslyn/issues/18738")> Public Sub TypedTupleWithNoImplicitConversion() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> option strict on Imports System Module C Sub M() Dim e As Integer? = 5 Dim x as (Integer, String, Integer) = (e, "") ' No conversion System.Console.WriteLine(x.ToString()) End Sub End Module </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics(<errors> BC30311: Value of type '(e As Integer?, String)' cannot be converted to '(Integer, String, Integer)'. Dim x as (Integer, String, Integer) = (e, "") ' No conversion ~~~~~~~ </errors>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree, ignoreAccessibility:=False) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().Single() Assert.Equal("(e, """")", node.ToString()) Assert.Equal("(e As System.Nullable(Of System.Int32), System.String)", model.GetTypeInfo(node).Type.ToTestDisplayString()) Assert.Equal("(System.Int32, System.String, System.Int32)", model.GetTypeInfo(node).ConvertedType.ToTestDisplayString()) Assert.Equal(ConversionKind.DelegateRelaxationLevelNone, model.GetConversion(node).Kind) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> Public Sub MoreGenericTieBreaker_01() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Module Module1 Public Sub Main() Dim a As A(Of A(Of Integer)) = Nothing M1(a) ' ok, selects M1(Of T)(A(Of A(Of T)) a) Dim b = New ValueTuple(Of ValueTuple(Of Integer, Integer), Integer)() M2(b) ' ok, should select M2(Of T)(ValueTuple(Of ValueTuple(Of T, Integer), Integer) a) End Sub Public Sub M1(Of T)(a As A(Of T)) Console.Write(1) End Sub Public Sub M1(Of T)(a As A(Of A(Of T))) Console.Write(2) End Sub Public Sub M2(Of T)(a As ValueTuple(Of T, Integer)) Console.Write(3) End Sub Public Sub M2(Of T)(a As ValueTuple(Of ValueTuple(Of T, Integer), Integer)) Console.Write(4) End Sub End Module Public Class A(Of T) End Class </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ 24 ]]>) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> Public Sub MoreGenericTieBreaker_01b() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Module Module1 Public Sub Main() Dim b = ((0, 0), 0) M2(b) ' ok, should select M2(Of T)(ValueTuple(Of ValueTuple(Of T, Integer), Integer) a) End Sub Public Sub M2(Of T)(a As (T, Integer)) Console.Write(3) End Sub Public Sub M2(Of T)(a As ((T, Integer), Integer)) Console.Write(4) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ 4 ]]>) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> <WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")> Public Sub MoreGenericTieBreaker_02a1() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports int = System.Int32 Module Module1 Public Sub Main() ' Dim b = (1, 2, 3, 4, 5, 6, 7, 8) Dim b = new ValueTuple(Of int, int, int, int, int, int, int, ValueTuple(Of int))(1, 2, 3, 4, 5, 6, 7, new ValueTuple(Of int)(8)) M1(b) M2(b) End Sub Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest as Structure)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest)) Console.Write(1) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, T8)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, ValueTuple(Of T8))) Console.Write(2) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest)) Console.Write(3) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ 12 ]]>) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> <WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")> Public Sub MoreGenericTieBreaker_02a2() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports int = System.Int32 Module Module1 Public Sub Main() ' Dim b = (1, 2, 3, 4, 5, 6, 7, 8) Dim b = new ValueTuple(Of int, int, int, int, int, int, int, ValueTuple(Of int))(1, 2, 3, 4, 5, 6, 7, new ValueTuple(Of int)(8)) M1(b) M2(b) End Sub Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest as Structure)(ByRef a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest)) Console.Write(1) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, T8)(ByRef a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, ValueTuple(Of T8))) Console.Write(2) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(ByRef a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest)) Console.Write(3) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ 12 ]]>) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> <WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")> Public Sub MoreGenericTieBreaker_02a3() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports int = System.Int32 Module Module1 Public Sub Main() Dim b As I(Of ValueTuple(Of int, int, int, int, int, int, int, ValueTuple(Of int))) = Nothing M1(b) M2(b) End Sub Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest as Structure)(a As I(Of ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest))) Console.Write(1) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, T8)(a As I(Of ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, ValueTuple(Of T8)))) Console.Write(2) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(a As I(Of ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest))) Console.Write(3) End Sub End Module Interface I(Of in T) End Interface </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ 12 ]]>) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> <WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")> Public Sub MoreGenericTieBreaker_02a4() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports int = System.Int32 Module Module1 Public Sub Main() Dim b As I(Of ValueTuple(Of int, int, int, int, int, int, int, ValueTuple(Of int))) = Nothing M1(b) M2(b) End Sub Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest as Structure)(a As I(Of ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest))) Console.Write(1) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, T8)(a As I(Of ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, ValueTuple(Of T8)))) Console.Write(2) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(a As I(Of ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest))) Console.Write(3) End Sub End Module Interface I(Of out T) End Interface </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ 12 ]]>) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> <WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")> Public Sub MoreGenericTieBreaker_02a5() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports int = System.Int32 Module Module1 Public Sub Main() M1((1, 2, 3, 4, 5, 6, 7, 8)) M2((1, 2, 3, 4, 5, 6, 7, 8)) End Sub Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest as Structure)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest)) Console.Write(1) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, T8)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, ValueTuple(Of T8))) Console.Write(2) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest)) Console.Write(3) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ 12 ]]>) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> <WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")> Public Sub MoreGenericTieBreaker_02a6() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports int = System.Int32 Module Module1 Public Sub Main() M2((Function() 1, Function() 2, Function() 3, Function() 4, Function() 5, Function() 6, Function() 7, Function() 8)) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, T8)(a As ValueTuple(Of Func(Of T1), Func(Of T2), Func(Of T3), Func(Of T4), Func(Of T5), Func(Of T6), Func(Of T7), ValueTuple(Of Func(Of T8)))) Console.Write(2) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(a As ValueTuple(Of Func(Of T1), Func(Of T2), Func(Of T3), Func(Of T4), Func(Of T5), Func(Of T6), Func(Of T7), TRest)) Console.Write(3) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ 2 ]]>) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> <WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")> Public Sub MoreGenericTieBreaker_02a7() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Imports int = System.Int32 Module Module1 Public Sub Main() M1((Function() 1, Function() 2, Function() 3, Function() 4, Function() 5, Function() 6, Function() 7, Function() 8)) End Sub Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest as Structure)(a As ValueTuple(Of Func(Of T1), Func(Of T2), Func(Of T3), Func(Of T4), Func(Of T5), Func(Of T6), Func(Of T7), TRest)) Console.Write(1) End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <expected> BC36645: Data type(s) of the type parameter(s) in method 'Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(a As ValueTuple(Of Func(Of T1), Func(Of T2), Func(Of T3), Func(Of T4), Func(Of T5), Func(Of T6), Func(Of T7), TRest))' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. M1((Function() 1, Function() 2, Function() 3, Function() 4, Function() 5, Function() 6, Function() 7, Function() 8)) ~~ </expected> ) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> <WorkItem(20583, "https://github.com/dotnet/roslyn/issues/20583")> Public Sub MoreGenericTieBreaker_02b() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports int = System.Int32 Module Module1 Public Sub Main() Dim b = (1, 2, 3, 4, 5, 6, 7, 8) M1(b) M2(b) End Sub Public Sub M1(Of T1, T2, T3, T4, T5, T6, T7, TRest as Structure)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest)) Console.Write(1) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, T8)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, ValueTuple(Of T8))) Console.Write(2) End Sub Public Sub M2(Of T1, T2, T3, T4, T5, T6, T7, TRest As Structure)(a As ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest)) Console.Write(3) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ 12 ]]>) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> Public Sub MoreGenericTieBreaker_03() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Module Module1 Public Sub Main() Dim b = ((1, 1), 2, 3, 4, 5, 6, 7, 8, 9, (10, 10), (11, 11)) M1(b) ' ok, should select M1(Of T, U, V)(a As ((T, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, (U, Integer), V)) End Sub Sub M1(Of T, U, V)(a As ((T, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, (U, Integer), V)) Console.Write(3) End Sub Sub M1(Of T, U, V)(a As (T, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, U, (V, Integer))) Console.Write(4) End Sub End Module </file> </compilation>, references:=s_valueTupleRefs, expectedOutput:=<![CDATA[ 3 ]]>) End Sub <Fact> <WorkItem(20494, "https://github.com/dotnet/roslyn/issues/20494")> Public Sub MoreGenericTieBreaker_04() Dim source = <compilation> <file name="a.vb"> Option Strict On Imports System Module Module1 Public Sub Main() Dim b = ((1, 1), 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, (20, 20)) M1(b) ' error: ambiguous End Sub Sub M1(Of T, U)(a As (T, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, (U, Integer))) Console.Write(3) End Sub Sub M1(Of T, U)(a As ((T, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, U)) Console.Write(4) End Sub End Module </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, references:=s_valueTupleRefs) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_NoMostSpecificOverload2, "M1").WithArguments("M1", " 'Public Sub M1(Of (Integer, Integer), Integer)(a As ((Integer, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer)))': Not most specific. 'Public Sub M1(Of Integer, (Integer, Integer))(a As ((Integer, Integer), Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer)))': Not most specific.").WithLocation(7, 9) ) End Sub <Fact> <WorkItem(21785, "https://github.com/dotnet/roslyn/issues/21785")> Public Sub TypelessTupleInArrayInitializer() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Module1 Private mTupleArray As (X As Integer, P As System.Func(Of Byte(), Integer))() = { (X:=0, P:=Nothing), (X:=0, P:=AddressOf MyFunction) } Sub Main() System.Console.Write(mTupleArray(1).P(Nothing)) End Sub Public Function MyFunction(ArgBytes As Byte()) As Integer Return 1 End Function End Module </file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertNoDiagnostics() CompileAndVerify(comp, expectedOutput:="1") Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(1) Assert.Equal("(X:=0, P:=AddressOf MyFunction)", node.ToString()) Dim tupleSymbol = model.GetTypeInfo(node) Assert.Null(tupleSymbol.Type) Assert.Equal("(X As System.Int32, P As System.Func(Of System.Byte(), System.Int32))", tupleSymbol.ConvertedType.ToTestDisplayString()) End Sub <Fact> <WorkItem(21785, "https://github.com/dotnet/roslyn/issues/21785")> Public Sub TypelessTupleInArrayInitializerWithInferenceFailure() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Module1 Private mTupleArray = { (X:=0, P:=AddressOf MyFunction) } Sub Main() System.Console.Write(mTupleArray(1).P(Nothing)) End Sub Public Function MyFunction(ArgBytes As Byte()) As Integer Return 1 End Function End Module </file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertTheseDiagnostics(<errors> BC30491: Expression does not produce a value. Private mTupleArray = { (X:=0, P:=AddressOf MyFunction) } ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(0) Assert.Equal("(X:=0, P:=AddressOf MyFunction)", node.ToString()) Dim tupleSymbol = model.GetTypeInfo(node) Assert.Null(tupleSymbol.Type) Assert.Equal("System.Object", tupleSymbol.ConvertedType.ToTestDisplayString()) End Sub <Fact> <WorkItem(21785, "https://github.com/dotnet/roslyn/issues/21785")> Public Sub TypelessTupleInArrayInitializerWithInferenceSuccess() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim y As MyDelegate = AddressOf MyFunction Dim mTupleArray = { (X:=0, P:=y), (X:=0, P:=AddressOf MyFunction) } System.Console.Write(mTupleArray(1).P(Nothing)) End Sub Delegate Function MyDelegate(ArgBytes As Byte()) As Integer Public Function MyFunction(ArgBytes As Byte()) As Integer Return 1 End Function End Module </file> </compilation>, additionalRefs:=s_valueTupleRefs, options:=TestOptions.DebugExe) comp.AssertNoDiagnostics() CompileAndVerify(comp, expectedOutput:="1") Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim node = nodes.OfType(Of TupleExpressionSyntax)().ElementAt(1) Assert.Equal("(X:=0, P:=AddressOf MyFunction)", node.ToString()) Dim tupleSymbol = model.GetTypeInfo(node) Assert.Null(tupleSymbol.Type) Assert.Equal("(X As System.Int32, P As Module1.MyDelegate)", tupleSymbol.ConvertedType.ToTestDisplayString()) End Sub <Fact> <WorkItem(24781, "https://github.com/dotnet/roslyn/issues/24781")> Public Sub InferenceWithTuple() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Public Interface IAct(Of T) Function Act(Of TReturn)(fn As Func(Of T, TReturn)) As IResult(Of TReturn) End Interface Public Interface IResult(Of TReturn) End Interface Module Module1 Sub M(impl As IAct(Of (Integer, Integer))) Dim case3 = impl.Act(Function(a As (x As Integer, y As Integer)) a.x * a.y) End Sub End Module </file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics() Dim tree = comp.SyntaxTrees(0) Dim model = comp.GetSemanticModel(tree) Dim nodes = tree.GetCompilationUnitRoot().DescendantNodes() Dim actSyntax = nodes.OfType(Of InvocationExpressionSyntax)().Single() Assert.Equal("impl.Act(Function(a As (x As Integer, y As Integer)) a.x * a.y)", actSyntax.ToString()) Dim actSymbol = DirectCast(model.GetSymbolInfo(actSyntax).Symbol, IMethodSymbol) Assert.Equal("IResult(Of System.Int32)", actSymbol.ReturnType.ToTestDisplayString()) End Sub <Fact> <WorkItem(21727, "https://github.com/dotnet/roslyn/issues/21727")> Public Sub FailedDecodingOfTupleNamesWhenMissingValueTupleType() Dim vtLib = CreateEmptyCompilation(s_trivial2uple, references:={MscorlibRef}, assemblyName:="vt") Dim libComp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System.Collections.Generic Imports System.Collections Public Class ClassA Implements IEnumerable(Of (alice As Integer, bob As Integer)) Function GetGenericEnumerator() As IEnumerator(Of (alice As Integer, bob As Integer)) Implements IEnumerable(Of (alice As Integer, bob As Integer)).GetEnumerator Return Nothing End Function Function GetEnumerator() As IEnumerator Implements IEnumerable(Of (alice As Integer, bob As Integer)).GetEnumerator Return Nothing End Function End Class </file> </compilation>, additionalRefs:={vtLib.EmitToImageReference()}) libComp.VerifyDiagnostics() Dim source As Xml.Linq.XElement = <compilation> <file name="a.vb"> Class ClassB Sub M() Dim x = New ClassA() x.ToString() End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={libComp.EmitToImageReference()}) ' missing reference to vt comp.AssertNoDiagnostics() FailedDecodingOfTupleNamesWhenMissingValueTupleType_Verify(comp, successfulDecoding:=False) Dim compWithMetadataReference = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={libComp.ToMetadataReference()}) ' missing reference to vt compWithMetadataReference.AssertNoDiagnostics() FailedDecodingOfTupleNamesWhenMissingValueTupleType_Verify(compWithMetadataReference, successfulDecoding:=True) Dim fakeVtLib = CreateEmptyCompilation("", references:={MscorlibRef}, assemblyName:="vt") Dim compWithFakeVt = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={libComp.EmitToImageReference(), fakeVtLib.EmitToImageReference()}) ' reference to fake vt compWithFakeVt.AssertNoDiagnostics() FailedDecodingOfTupleNamesWhenMissingValueTupleType_Verify(compWithFakeVt, successfulDecoding:=False) Dim source2 As Xml.Linq.XElement = <compilation> <file name="a.vb"> Class ClassB Sub M() Dim x = New ClassA().GetGenericEnumerator() For Each i In New ClassA() System.Console.Write(i.alice) Next End Sub End Class </file> </compilation> Dim comp2 = CreateCompilationWithMscorlib40AndVBRuntime(source2, additionalRefs:={libComp.EmitToImageReference()}) ' missing reference to vt comp2.AssertTheseDiagnostics(<errors> BC30652: Reference required to assembly 'vt, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'ValueTuple(Of ,)'. Add one to your project. Dim x = New ClassA().GetGenericEnumerator() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) FailedDecodingOfTupleNamesWhenMissingValueTupleType_Verify(comp2, successfulDecoding:=False) Dim comp2WithFakeVt = CreateCompilationWithMscorlib40AndVBRuntime(source2, additionalRefs:={libComp.EmitToImageReference(), fakeVtLib.EmitToImageReference()}) ' reference to fake vt comp2WithFakeVt.AssertTheseDiagnostics(<errors> BC31091: Import of type 'ValueTuple(Of ,)' from assembly or module 'vt.dll' failed. Dim x = New ClassA().GetGenericEnumerator() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </errors>) FailedDecodingOfTupleNamesWhenMissingValueTupleType_Verify(comp2WithFakeVt, successfulDecoding:=False) End Sub Private Sub FailedDecodingOfTupleNamesWhenMissingValueTupleType_Verify(compilation As Compilation, successfulDecoding As Boolean) Dim classA = DirectCast(compilation.GetMember("ClassA"), NamedTypeSymbol) Dim iEnumerable = classA.Interfaces()(0) If successfulDecoding Then Assert.Equal("System.Collections.Generic.IEnumerable(Of (alice As System.Int32, bob As System.Int32))", iEnumerable.ToTestDisplayString()) Dim tuple = iEnumerable.TypeArguments()(0) Assert.Equal("(alice As System.Int32, bob As System.Int32)", tuple.ToTestDisplayString()) Assert.True(tuple.IsTupleType) Assert.True(tuple.TupleUnderlyingType.IsErrorType()) Else Assert.Equal("System.Collections.Generic.IEnumerable(Of System.ValueTuple(Of System.Int32, System.Int32)[missing])", iEnumerable.ToTestDisplayString()) Dim tuple = iEnumerable.TypeArguments()(0) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32)[missing]", tuple.ToTestDisplayString()) Assert.False(tuple.IsTupleType) End If End Sub <Fact> <WorkItem(21727, "https://github.com/dotnet/roslyn/issues/21727")> Public Sub FailedDecodingOfTupleNamesWhenMissingContainerType() Dim containerLib = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Public Class Container(Of T) Public Class Contained(Of U) End Class End Class </file> </compilation>) containerLib.VerifyDiagnostics() Dim libComp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System.Collections.Generic Imports System.Collections Public Class ClassA Implements IEnumerable(Of Container(Of (alice As Integer, bob As Integer)).Contained(Of (charlie As Integer, dylan as Integer))) Function GetGenericEnumerator() As IEnumerator(Of Container(Of (alice As Integer, bob As Integer)).Contained(Of (charlie As Integer, dylan as Integer))) _ Implements IEnumerable(Of Container(Of (alice As Integer, bob As Integer)).Contained(Of (charlie As Integer, dylan as Integer))).GetEnumerator Return Nothing End Function Function GetEnumerator() As IEnumerator Implements IEnumerable(Of Container(Of (alice As Integer, bob As Integer)).Contained(Of (charlie As Integer, dylan as Integer))).GetEnumerator Return Nothing End Function End Class </file> </compilation>, additionalRefs:={containerLib.EmitToImageReference(), ValueTupleRef, SystemRuntimeFacadeRef}) libComp.VerifyDiagnostics() Dim source As Xml.Linq.XElement = <compilation> <file name="a.vb"> Class ClassB Sub M() Dim x = New ClassA() x.ToString() End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={libComp.EmitToImageReference(), ValueTupleRef, SystemRuntimeFacadeRef}) ' missing reference to container comp.AssertNoDiagnostics() FailedDecodingOfTupleNamesWhenMissingContainerType_Verify(comp, decodingSuccessful:=False) Dim compWithMetadataReference = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={libComp.ToMetadataReference(), ValueTupleRef, SystemRuntimeFacadeRef}) ' missing reference to container compWithMetadataReference.AssertNoDiagnostics() FailedDecodingOfTupleNamesWhenMissingContainerType_Verify(compWithMetadataReference, decodingSuccessful:=True) Dim fakeContainerLib = CreateEmptyCompilation("", references:={MscorlibRef}, assemblyName:="vt") Dim compWithFakeVt = CreateCompilationWithMscorlib40AndVBRuntime(source, additionalRefs:={libComp.EmitToImageReference(), fakeContainerLib.EmitToImageReference(), ValueTupleRef, SystemRuntimeFacadeRef}) ' reference to fake container compWithFakeVt.AssertNoDiagnostics() FailedDecodingOfTupleNamesWhenMissingContainerType_Verify(compWithFakeVt, decodingSuccessful:=False) End Sub Private Sub FailedDecodingOfTupleNamesWhenMissingContainerType_Verify(compilation As Compilation, decodingSuccessful As Boolean) Dim classA = DirectCast(compilation.GetMember("ClassA"), NamedTypeSymbol) Dim iEnumerable = classA.Interfaces()(0) Dim tuple = DirectCast(iEnumerable.TypeArguments()(0), NamedTypeSymbol).TypeArguments()(0) If decodingSuccessful Then Assert.Equal("System.Collections.Generic.IEnumerable(Of Container(Of (alice As System.Int32, bob As System.Int32))[missing].Contained(Of (charlie As System.Int32, dylan As System.Int32))[missing])", iEnumerable.ToTestDisplayString()) Assert.Equal("(charlie As System.Int32, dylan As System.Int32)", tuple.ToTestDisplayString()) Assert.True(tuple.IsTupleType) Assert.False(tuple.TupleUnderlyingType.IsErrorType()) Else Assert.Equal("System.Collections.Generic.IEnumerable(Of Container(Of System.ValueTuple(Of System.Int32, System.Int32))[missing].Contained(Of System.ValueTuple(Of System.Int32, System.Int32))[missing])", iEnumerable.ToTestDisplayString()) Assert.Equal("System.ValueTuple(Of System.Int32, System.Int32)", tuple.ToTestDisplayString()) Assert.False(tuple.IsTupleType) End If End Sub <Theory> <InlineData(True)> <InlineData(False)> <WorkItem(40033, "https://github.com/dotnet/roslyn/issues/40033")> Public Sub SynthesizeTupleElementNamesAttributeBasedOnInterfacesToEmit_IndirectInterfaces(ByVal useImageReferences As Boolean) Dim getReference As Func(Of Compilation, MetadataReference) = Function(c) If(useImageReferences, c.EmitToImageReference(), c.ToMetadataReference()) Dim valueTuple_source = " Namespace System Public Structure ValueTuple(Of T1, T2) Public Dim Item1 As T1 Public Dim Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return ""{"" + Item1?.ToString() + "", "" + Item2?.ToString() + ""}"" End Function End Structure End Namespace " Dim valueTuple_comp = CreateCompilationWithMscorlib40(valueTuple_source) Dim tupleElementNamesAttribute_comp = CreateCompilationWithMscorlib40(s_tupleattributes) tupleElementNamesAttribute_comp.AssertNoDiagnostics() Dim lib1_source = " Imports System.Threading.Tasks Public Interface I2(Of T, TResult) Function ExecuteAsync(parameter As T) As Task(Of TResult) End Interface Public Interface I1(Of T) Inherits I2(Of T, (a As Object, b As Object)) End Interface " Dim lib1_comp = CreateCompilationWithMscorlib40(lib1_source, references:={getReference(valueTuple_comp), getReference(tupleElementNamesAttribute_comp)}) lib1_comp.AssertNoDiagnostics() Dim lib2_source = " Public interface I0 Inherits I1(Of string) End Interface " Dim lib2_comp = CreateCompilationWithMscorlib40(lib2_source, references:={getReference(lib1_comp), getReference(valueTuple_comp)}) ' Missing TupleElementNamesAttribute lib2_comp.AssertNoDiagnostics() lib2_comp.AssertTheseEmitDiagnostics() Dim imc1 = CType(lib2_comp.GlobalNamespace.GetMember("I0"), TypeSymbol) AssertEx.SetEqual({"I1(Of System.String)"}, imc1.InterfacesNoUseSiteDiagnostics().Select(Function(i) i.ToTestDisplayString())) AssertEx.SetEqual({"I1(Of System.String)", "I2(Of System.String, (a As System.Object, b As System.Object))"}, imc1.AllInterfacesNoUseSiteDiagnostics.Select(Function(i) i.ToTestDisplayString())) Dim client_source = " Public Class C Public Sub M(imc As I0) imc.ExecuteAsync("""") End Sub End Class " Dim client_comp = CreateCompilationWithMscorlib40(client_source, references:={getReference(lib1_comp), getReference(lib2_comp), getReference(valueTuple_comp)}) client_comp.AssertNoDiagnostics() Dim imc2 = CType(client_comp.GlobalNamespace.GetMember("I0"), TypeSymbol) AssertEx.SetEqual({"I1(Of System.String)"}, imc2.InterfacesNoUseSiteDiagnostics().Select(Function(i) i.ToTestDisplayString())) AssertEx.SetEqual({"I1(Of System.String)", "I2(Of System.String, (a As System.Object, b As System.Object))"}, imc2.AllInterfacesNoUseSiteDiagnostics.Select(Function(i) i.ToTestDisplayString())) End Sub <Fact, WorkItem(40033, "https://github.com/dotnet/roslyn/issues/40033")> Public Sub SynthesizeTupleElementNamesAttributeBasedOnInterfacesToEmit_BaseAndDirectInterface() Dim source = " Namespace System Public Structure ValueTuple(Of T1, T2) Public Dim Item1 As T1 Public Dim Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return ""{"" + Item1?.ToString() + "", "" + Item2?.ToString() + ""}"" End Function End Structure End Namespace Namespace System.Runtime.CompilerServices Public Class TupleElementNamesAttribute Inherits Attribute Public Sub New() ' Note: bad signature End Sub End Class End Namespace Public Interface I(Of T) End Interface Public Class Base(Of T) End Class Public Class C1 Implements I(Of (a As Object, b As Object)) End Class Public Class C2 Inherits Base(Of (a As Object, b As Object)) End Class " Dim comp = CreateCompilationWithMscorlib40(source) comp.AssertTheseEmitDiagnostics(<errors><![CDATA[ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Implements I(Of (a As Object, b As Object)) ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Inherits Base(Of (a As Object, b As Object)) ~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Theory> <InlineData(True)> <InlineData(False)> <WorkItem(40430, "https://github.com/dotnet/roslyn/issues/40430")> Public Sub MissingTypeArgumentInBase_ValueTuple(useImageReference As Boolean) Dim lib_vb = " Public Class ClassWithTwoTypeParameters(Of T1, T2) End Class Public Class SelfReferencingClassWithTuple Inherits ClassWithTwoTypeParameters(Of SelfReferencingClassWithTuple, (A As String, B As Integer)) Sub New() System.Console.Write(""ran"") End Sub End Class " Dim library = CreateCompilationWithMscorlib40(lib_vb, references:=s_valueTupleRefs) library.VerifyDiagnostics() Dim libraryRef = If(useImageReference, library.EmitToImageReference(), library.ToMetadataReference()) Dim source_vb = " Public Class TriggerStackOverflowException Public Shared Sub Method() Dim x = New SelfReferencingClassWithTuple() End Sub End Class " Dim comp = CreateCompilationWithMscorlib40(source_vb, references:={libraryRef}) comp.VerifyEmitDiagnostics() Dim executable_vb = " Public Class C Public Shared Sub Main() TriggerStackOverflowException.Method() End Sub End Class " Dim executableComp = CreateCompilationWithMscorlib40(executable_vb, references:={comp.EmitToImageReference(), libraryRef, SystemRuntimeFacadeRef, ValueTupleRef}, options:=TestOptions.DebugExe) CompileAndVerify(executableComp, expectedOutput:="ran") End Sub <Fact> <WorkItem(41699, "https://github.com/dotnet/roslyn/issues/41699")> Public Sub MissingBaseType_TupleTypeArgumentWithNames() Dim sourceA = "Public Class A(Of T) End Class" Dim comp = CreateCompilation(sourceA, assemblyName:="A") Dim refA = comp.EmitToImageReference() Dim sourceB = "Public Class B Inherits A(Of (X As Object, Y As B)) End Class" comp = CreateCompilation(sourceB, references:={refA}) Dim refB = comp.EmitToImageReference() Dim sourceC = "Module Program Sub Main() Dim b = New B() b.ToString() End Sub End Module" comp = CreateCompilation(sourceC, references:={refB}) comp.AssertTheseDiagnostics( "BC30456: 'ToString' is not a member of 'B'. b.ToString() ~~~~~~~~~~ BC30652: Reference required to assembly 'A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' containing the type 'A(Of )'. Add one to your project. b.ToString() ~~~~~~~~~~") End Sub <Fact> <WorkItem(41207, "https://github.com/dotnet/roslyn/issues/41207")> <WorkItem(1056281, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056281")> Public Sub CustomFields_01() Dim source0 = " Namespace System Public Structure ValueTuple(Of T1, T2) Public Shared F1 As Integer = 123 Public Dim Item1 As T1 Public Dim Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 End Sub Public Overrides Function ToString() As String Return F1.ToString() End Function End Structure End Namespace " Dim source1 = " class Program public Shared Sub Main() System.Console.WriteLine((1,2).ToString()) End Sub End Class " Dim source2 = " class Program public Shared Sub Main() System.Console.WriteLine(System.ValueTuple(Of Integer, Integer).F1) End Sub End Class " Dim verifyField = Sub(comp As VisualBasicCompilation) Dim field = comp.GetMember(Of FieldSymbol)("System.ValueTuple.F1") Assert.Null(field.TupleUnderlyingField) Dim toEmit = field.ContainingType.GetFieldsToEmit().Where(Function(f) f.Name = "F1").Single() Assert.Same(field, toEmit) End Sub Dim comp1 = CreateCompilation(source0 + source1, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe) CompileAndVerify(comp1, expectedOutput:="123") verifyField(comp1) Dim comp1Ref = {comp1.ToMetadataReference()} Dim comp1ImageRef = {comp1.EmitToImageReference()} Dim comp4 = CreateCompilation(source0 + source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe) CompileAndVerify(comp4, expectedOutput:="123") Dim comp5 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1Ref) CompileAndVerify(comp5, expectedOutput:="123") verifyField(comp5) Dim comp6 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1ImageRef) CompileAndVerify(comp6, expectedOutput:="123") verifyField(comp6) Dim comp7 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib46, options:=TestOptions.DebugExe, references:=comp1Ref) CompileAndVerify(comp7, expectedOutput:="123") verifyField(comp7) End Sub <Fact> <WorkItem(41207, "https://github.com/dotnet/roslyn/issues/41207")> <WorkItem(1056281, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056281")> Public Sub CustomFields_02() Dim source0 = " Namespace System Public Structure ValueTuple(Of T1, T2) Public Dim F1 As Integer Public Dim Item1 As T1 Public Dim Item2 As T2 Public Sub New(item1 As T1, item2 As T2) me.Item1 = item1 me.Item2 = item2 me.F1 = 123 End Sub Public Overrides Function ToString() As String Return F1.ToString() End Function End Structure End Namespace " Dim source1 = " class Program public Shared Sub Main() System.Console.WriteLine((1,2).ToString()) End Sub End Class " Dim source2 = " class Program public Shared Sub Main() System.Console.WriteLine((1,2).F1) End Sub End Class " Dim verifyField = Sub(comp As VisualBasicCompilation) Dim field = comp.GetMember(Of FieldSymbol)("System.ValueTuple.F1") Assert.Null(field.TupleUnderlyingField) Dim toEmit = field.ContainingType.GetFieldsToEmit().Where(Function(f) f.Name = "F1").Single() Assert.Same(field, toEmit) End Sub Dim comp1 = CreateCompilation(source0 + source1, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe) CompileAndVerify(comp1, expectedOutput:="123") verifyField(comp1) Dim comp1Ref = {comp1.ToMetadataReference()} Dim comp1ImageRef = {comp1.EmitToImageReference()} Dim comp4 = CreateCompilation(source0 + source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe) CompileAndVerify(comp4, expectedOutput:="123") Dim comp5 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1Ref) CompileAndVerify(comp5, expectedOutput:="123") verifyField(comp5) Dim comp6 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1ImageRef) CompileAndVerify(comp6, expectedOutput:="123") verifyField(comp6) Dim comp7 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib46, options:=TestOptions.DebugExe, references:=comp1Ref) CompileAndVerify(comp7, expectedOutput:="123") verifyField(comp7) End Sub <Fact> <WorkItem(43524, "https://github.com/dotnet/roslyn/issues/43524")> <WorkItem(1095184, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1095184")> Public Sub CustomFields_03() Dim source0 = " namespace System public structure ValueTuple public shared readonly F1 As Integer = 4 public Shared Function CombineHashCodes(h1 As Integer, h2 As Integer) As Integer return F1 + h1 + h2 End Function End Structure End Namespace " Dim source1 = " class Program shared sub Main() System.Console.WriteLine(System.ValueTuple.CombineHashCodes(2, 3)) End Sub End Class " Dim source2 = " class Program public shared Sub Main() System.Console.WriteLine(System.ValueTuple.F1 + 2 + 3) End Sub End Class " Dim verifyField = Sub(comp As VisualBasicCompilation) Dim field = comp.GetMember(Of FieldSymbol)("System.ValueTuple.F1") Assert.Null(field.TupleUnderlyingField) Dim toEmit = field.ContainingType.GetFieldsToEmit().Single() Assert.Same(field, toEmit) End Sub Dim comp1 = CreateCompilation(source0 + source1, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe) CompileAndVerify(comp1, expectedOutput:="9") verifyField(comp1) Dim comp1Ref = {comp1.ToMetadataReference()} Dim comp1ImageRef = {comp1.EmitToImageReference()} Dim comp4 = CreateCompilation(source0 + source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe) CompileAndVerify(comp4, expectedOutput:="9") Dim comp5 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1Ref) CompileAndVerify(comp5, expectedOutput:="9") verifyField(comp5) Dim comp6 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1ImageRef) CompileAndVerify(comp6, expectedOutput:="9") verifyField(comp6) Dim comp7 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib46, options:=TestOptions.DebugExe, references:=comp1Ref) CompileAndVerify(comp7, expectedOutput:="9") verifyField(comp7) End Sub <Fact> <WorkItem(43524, "https://github.com/dotnet/roslyn/issues/43524")> <WorkItem(1095184, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1095184")> Public Sub CustomFields_04() Dim source0 = " namespace System public structure ValueTuple public F1 as Integer public Function CombineHashCodes(h1 as Integer, h2 as Integer) as Integer return F1 + h1 + h2 End Function End Structure End Namespace " Dim source1 = " class Program shared sub Main() Dim tuple as System.ValueTuple = Nothing tuple.F1 = 4 System.Console.WriteLine(tuple.CombineHashCodes(2, 3)) End Sub End Class " Dim source2 = " class Program public shared Sub Main() Dim tuple as System.ValueTuple = Nothing tuple.F1 = 4 System.Console.WriteLine(tuple.F1 + 2 + 3) End Sub End Class " Dim verifyField = Sub(comp As VisualBasicCompilation) Dim field = comp.GetMember(Of FieldSymbol)("System.ValueTuple.F1") Assert.Null(field.TupleUnderlyingField) Dim toEmit = field.ContainingType.GetFieldsToEmit().Single() Assert.Same(field, toEmit) End Sub Dim comp1 = CreateCompilation(source0 + source1, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe) CompileAndVerify(comp1, expectedOutput:="9") verifyField(comp1) Dim comp1Ref = {comp1.ToMetadataReference()} Dim comp1ImageRef = {comp1.EmitToImageReference()} Dim comp4 = CreateCompilation(source0 + source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe) CompileAndVerify(comp4, expectedOutput:="9") Dim comp5 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1Ref) CompileAndVerify(comp5, expectedOutput:="9") verifyField(comp5) Dim comp6 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib40, options:=TestOptions.DebugExe, references:=comp1ImageRef) CompileAndVerify(comp6, expectedOutput:="9") verifyField(comp6) Dim comp7 = CreateCompilation(source2, targetFramework:=TargetFramework.Mscorlib46, options:=TestOptions.DebugExe, references:=comp1Ref) CompileAndVerify(comp7, expectedOutput:="9") verifyField(comp7) End Sub <Fact> <WorkItem(41702, "https://github.com/dotnet/roslyn/issues/41702")> Public Sub TupleUnderlyingType_FromCSharp() Dim source = "#pragma warning disable 169 class Program { static System.ValueTuple F0; static (int, int) F1; static (int A, int B) F2; static (object, object, object, object, object, object, object, object) F3; static (object, object B, object, object D, object, object F, object, object H) F4; }" Dim comp = CreateCSharpCompilation(source, referencedAssemblies:=TargetFrameworkUtil.GetReferences(TargetFramework.Standard)) comp.VerifyDiagnostics() Dim containingType = comp.GlobalNamespace.GetTypeMembers("Program").Single() VerifyTypeFromCSharp(DirectCast(DirectCast(containingType.GetMembers("F0").Single(), IFieldSymbol).Type, INamedTypeSymbol), TupleUnderlyingTypeValue.Nothing, "System.ValueTuple", "()") VerifyTypeFromCSharp(DirectCast(DirectCast(containingType.GetMembers("F1").Single(), IFieldSymbol).Type, INamedTypeSymbol), TupleUnderlyingTypeValue.Nothing, "(System.Int32, System.Int32)", "(System.Int32, System.Int32)") VerifyTypeFromCSharp(DirectCast(DirectCast(containingType.GetMembers("F2").Single(), IFieldSymbol).Type, INamedTypeSymbol), TupleUnderlyingTypeValue.Distinct, "(System.Int32 A, System.Int32 B)", "(A As System.Int32, B As System.Int32)") VerifyTypeFromCSharp(DirectCast(DirectCast(containingType.GetMembers("F3").Single(), IFieldSymbol).Type, INamedTypeSymbol), TupleUnderlyingTypeValue.Nothing, "(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", "(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)") VerifyTypeFromCSharp(DirectCast(DirectCast(containingType.GetMembers("F4").Single(), IFieldSymbol).Type, INamedTypeSymbol), TupleUnderlyingTypeValue.Distinct, "(System.Object, System.Object B, System.Object, System.Object D, System.Object, System.Object F, System.Object, System.Object H)", "(System.Object, B As System.Object, System.Object, D As System.Object, System.Object, F As System.Object, System.Object, H As System.Object)") End Sub <Fact> <WorkItem(41702, "https://github.com/dotnet/roslyn/issues/41702")> Public Sub TupleUnderlyingType_FromVisualBasic() Dim source = "Class Program Private F0 As System.ValueTuple Private F1 As (Integer, Integer) Private F2 As (A As Integer, B As Integer) Private F3 As (Object, Object, Object, Object, Object, Object, Object, Object) Private F4 As (Object, B As Object, Object, D As Object, Object, F As Object, Object, H As Object) End Class" Dim comp = CreateCompilation(source) comp.AssertNoDiagnostics() Dim containingType = comp.GlobalNamespace.GetTypeMembers("Program").Single() VerifyTypeFromVisualBasic(DirectCast(DirectCast(containingType.GetMembers("F0").Single(), FieldSymbol).Type, NamedTypeSymbol), TupleUnderlyingTypeValue.Nothing, "System.ValueTuple", "System.ValueTuple") VerifyTypeFromVisualBasic(DirectCast(DirectCast(containingType.GetMembers("F1").Single(), FieldSymbol).Type, NamedTypeSymbol), TupleUnderlyingTypeValue.Distinct, "(System.Int32, System.Int32)", "(System.Int32, System.Int32)") VerifyTypeFromVisualBasic(DirectCast(DirectCast(containingType.GetMembers("F2").Single(), FieldSymbol).Type, NamedTypeSymbol), TupleUnderlyingTypeValue.Distinct, "(System.Int32 A, System.Int32 B)", "(A As System.Int32, B As System.Int32)") VerifyTypeFromVisualBasic(DirectCast(DirectCast(containingType.GetMembers("F3").Single(), FieldSymbol).Type, NamedTypeSymbol), TupleUnderlyingTypeValue.Distinct, "(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)", "(System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object, System.Object)") VerifyTypeFromVisualBasic(DirectCast(DirectCast(containingType.GetMembers("F4").Single(), FieldSymbol).Type, NamedTypeSymbol), TupleUnderlyingTypeValue.Distinct, "(System.Object, System.Object B, System.Object, System.Object D, System.Object, System.Object F, System.Object, System.Object H)", "(System.Object, B As System.Object, System.Object, D As System.Object, System.Object, F As System.Object, System.Object, H As System.Object)") End Sub Private Enum TupleUnderlyingTypeValue [Nothing] Distinct Same End Enum Private Shared Sub VerifyTypeFromCSharp(type As INamedTypeSymbol, expectedValue As TupleUnderlyingTypeValue, expectedCSharp As String, expectedVisualBasic As String) VerifyDisplay(type, expectedCSharp, expectedVisualBasic) VerifyPublicType(type, expectedValue) VerifyPublicType(type.OriginalDefinition, TupleUnderlyingTypeValue.Nothing) End Sub Private Shared Sub VerifyTypeFromVisualBasic(type As NamedTypeSymbol, expectedValue As TupleUnderlyingTypeValue, expectedCSharp As String, expectedVisualBasic As String) VerifyDisplay(type, expectedCSharp, expectedVisualBasic) VerifyInternalType(type, expectedValue) VerifyPublicType(type, expectedValue) type = type.OriginalDefinition VerifyInternalType(type, expectedValue) VerifyPublicType(type, expectedValue) End Sub Private Shared Sub VerifyDisplay(type As INamedTypeSymbol, expectedCSharp As String, expectedVisualBasic As String) Assert.Equal(expectedCSharp, CSharp.SymbolDisplay.ToDisplayString(type, SymbolDisplayFormat.TestFormat)) Assert.Equal(expectedVisualBasic, VisualBasic.SymbolDisplay.ToDisplayString(type, SymbolDisplayFormat.TestFormat)) End Sub Private Shared Sub VerifyInternalType(type As NamedTypeSymbol, expectedValue As TupleUnderlyingTypeValue) Dim underlyingType = type.TupleUnderlyingType Select Case expectedValue Case TupleUnderlyingTypeValue.Nothing Assert.Null(underlyingType) Case TupleUnderlyingTypeValue.Distinct Assert.NotEqual(type, underlyingType) Assert.NotEqual(underlyingType, type) Assert.True(type.Equals(underlyingType, TypeCompareKind.AllIgnoreOptions)) Assert.True(underlyingType.Equals(type, TypeCompareKind.AllIgnoreOptions)) Assert.False(type.Equals(underlyingType, TypeCompareKind.ConsiderEverything)) Assert.False(underlyingType.Equals(type, TypeCompareKind.ConsiderEverything)) Assert.True(DirectCast(type, Symbol).Equals(underlyingType, TypeCompareKind.AllIgnoreOptions)) Assert.True(DirectCast(underlyingType, Symbol).Equals(type, TypeCompareKind.AllIgnoreOptions)) Assert.False(DirectCast(type, Symbol).Equals(underlyingType, TypeCompareKind.ConsiderEverything)) Assert.False(DirectCast(underlyingType, Symbol).Equals(type, TypeCompareKind.ConsiderEverything)) VerifyPublicType(underlyingType, expectedValue:=TupleUnderlyingTypeValue.Nothing) Case Else Throw ExceptionUtilities.UnexpectedValue(expectedValue) End Select End Sub Private Shared Sub VerifyPublicType(type As INamedTypeSymbol, expectedValue As TupleUnderlyingTypeValue) Dim underlyingType = type.TupleUnderlyingType Select Case expectedValue Case TupleUnderlyingTypeValue.Nothing Assert.Null(underlyingType) Case TupleUnderlyingTypeValue.Distinct Assert.NotEqual(type, underlyingType) Assert.False(type.Equals(underlyingType, SymbolEqualityComparer.Default)) Assert.False(type.Equals(underlyingType, SymbolEqualityComparer.ConsiderEverything)) VerifyPublicType(underlyingType, expectedValue:=TupleUnderlyingTypeValue.Nothing) Case Else Throw ExceptionUtilities.UnexpectedValue(expectedValue) End Select End Sub <Fact> <WorkItem(27322, "https://github.com/dotnet/roslyn/issues/27322")> Public Sub Issue27322() Dim source0 = " Imports System Imports System.Collections.Generic Imports System.Linq.Expressions Module Module1 Sub Main() Dim tupleA = (1, 3) Dim tupleB = (1, ""123"".Length) Dim ok1 As Expression(Of Func(Of Integer)) = Function() tupleA.Item1 Dim ok2 As Expression(Of Func(Of Integer)) = Function() tupleA.GetHashCode() Dim ok3 As Expression(Of Func(Of Tuple(Of Integer, Integer))) = Function() tupleA.ToTuple() Dim ok4 As Expression(Of Func(Of Boolean)) = Function() Equals(tupleA, tupleB) Dim ok5 As Expression(Of Func(Of Integer)) = Function() Comparer(Of (Integer, Integer)).Default.Compare(tupleA, tupleB) ok1.Compile()() ok2.Compile()() ok3.Compile()() ok4.Compile()() ok5.Compile()() Dim err1 As Expression(Of Func(Of Boolean)) = Function() tupleA.Equals(tupleB) Dim err2 As Expression(Of Func(Of Integer)) = Function() tupleA.CompareTo(tupleB) err1.Compile()() err2.Compile()() System.Console.WriteLine(""Done"") End Sub End Module " Dim comp1 = CreateCompilation(source0, options:=TestOptions.DebugExe) CompileAndVerify(comp1, expectedOutput:="Done") End Sub <Fact> <WorkItem(24517, "https://github.com/dotnet/roslyn/issues/24517")> Public Sub Issue24517() Dim source0 = " Imports System Imports System.Collections.Generic Imports System.Linq.Expressions Module Module1 Sub Main() Dim e1 As Expression(Of Func(Of ValueTuple(Of Integer, Integer))) = Function() new ValueTuple(Of Integer, Integer)(1, 2) Dim e2 As Expression(Of Func(Of KeyValuePair(Of Integer, Integer))) = Function() new KeyValuePair(Of Integer, Integer)(1, 2) e1.Compile()() e2.Compile()() System.Console.WriteLine(""Done"") End Sub End Module " Dim comp1 = CreateCompilation(source0, options:=TestOptions.DebugExe) CompileAndVerify(comp1, expectedOutput:="Done") End Sub End Class End Namespace
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Test/Symbol/Compilation/ForEachStatementInfoTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp { public class ForEachStatementInfoTests : CSharpTestBase { [Fact] public void Equality() { var c = (Compilation)CreateCompilation(@" class E1 { public E GetEnumerator() { return null; } public bool MoveNext() { return false; } public object Current { get; } public void Dispose() { } } class E2 { public E GetEnumerator() { return null; } public bool MoveNext() { return false; } public object Current { get; } public void Dispose() { } } "); var e1 = (ITypeSymbol)c.GlobalNamespace.GetMembers("E1").Single(); var ge1 = (IMethodSymbol)e1.GetMembers("GetEnumerator").Single(); var mn1 = (IMethodSymbol)e1.GetMembers("MoveNext").Single(); var cur1 = (IPropertySymbol)e1.GetMembers("Current").Single(); var disp1 = (IMethodSymbol)e1.GetMembers("Dispose").Single(); var conv1 = Conversion.Identity; var e2 = (ITypeSymbol)c.GlobalNamespace.GetMembers("E2").Single(); var ge2 = (IMethodSymbol)e2.GetMembers("GetEnumerator").Single(); var mn2 = (IMethodSymbol)e2.GetMembers("MoveNext").Single(); var cur2 = (IPropertySymbol)e2.GetMembers("Current").Single(); var disp2 = (IMethodSymbol)e2.GetMembers("Dispose").Single(); var conv2 = Conversion.NoConversion; EqualityTesting.AssertEqual(default(ForEachStatementInfo), default(ForEachStatementInfo)); EqualityTesting.AssertEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1)); EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge2, mn1, cur1, disp1, e1, conv1, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1)); EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn2, cur1, disp1, e1, conv1, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1)); EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur2, disp1, e1, conv1, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1)); EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp2, e1, conv1, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1)); EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv2, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1)); EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv2), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1)); EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1), new ForEachStatementInfo(isAsync: false, ge1, mn1, cur1, disp1, e1, conv1, conv1)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp { public class ForEachStatementInfoTests : CSharpTestBase { [Fact] public void Equality() { var c = (Compilation)CreateCompilation(@" class E1 { public E GetEnumerator() { return null; } public bool MoveNext() { return false; } public object Current { get; } public void Dispose() { } } class E2 { public E GetEnumerator() { return null; } public bool MoveNext() { return false; } public object Current { get; } public void Dispose() { } } "); var e1 = (ITypeSymbol)c.GlobalNamespace.GetMembers("E1").Single(); var ge1 = (IMethodSymbol)e1.GetMembers("GetEnumerator").Single(); var mn1 = (IMethodSymbol)e1.GetMembers("MoveNext").Single(); var cur1 = (IPropertySymbol)e1.GetMembers("Current").Single(); var disp1 = (IMethodSymbol)e1.GetMembers("Dispose").Single(); var conv1 = Conversion.Identity; var e2 = (ITypeSymbol)c.GlobalNamespace.GetMembers("E2").Single(); var ge2 = (IMethodSymbol)e2.GetMembers("GetEnumerator").Single(); var mn2 = (IMethodSymbol)e2.GetMembers("MoveNext").Single(); var cur2 = (IPropertySymbol)e2.GetMembers("Current").Single(); var disp2 = (IMethodSymbol)e2.GetMembers("Dispose").Single(); var conv2 = Conversion.NoConversion; EqualityTesting.AssertEqual(default(ForEachStatementInfo), default(ForEachStatementInfo)); EqualityTesting.AssertEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1)); EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge2, mn1, cur1, disp1, e1, conv1, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1)); EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn2, cur1, disp1, e1, conv1, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1)); EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur2, disp1, e1, conv1, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1)); EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp2, e1, conv1, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1)); EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv2, conv1), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1)); EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv2), new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1)); EqualityTesting.AssertNotEqual(new ForEachStatementInfo(isAsync: true, ge1, mn1, cur1, disp1, e1, conv1, conv1), new ForEachStatementInfo(isAsync: false, ge1, mn1, cur1, disp1, e1, conv1, conv1)); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/CSharpTest/EditorConfigSettings/DataProvider/DataProviderTests.TestViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EditorConfigSettings.DataProvider { public partial class DataProviderTests { private class TestViewModel : ISettingsEditorViewModel { public void NotifyOfUpdate() { } Task<SourceText> ISettingsEditorViewModel.UpdateEditorConfigAsync(SourceText sourceText) { throw new NotImplementedException(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EditorConfigSettings.DataProvider { public partial class DataProviderTests { private class TestViewModel : ISettingsEditorViewModel { public void NotifyOfUpdate() { } Task<SourceText> ISettingsEditorViewModel.UpdateEditorConfigAsync(SourceText sourceText) { throw new NotImplementedException(); } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/IntegrationTest/IntegrationService/IntegrationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Reflection; using System.Runtime.Remoting; namespace Microsoft.VisualStudio.IntegrationTest.Utilities { /// <summary> /// Provides a means of executing code in the Visual Studio host process. /// </summary> /// <remarks> /// This object exists in the Visual Studio host and is marhsalled across the process boundary. /// </remarks> internal class IntegrationService : MarshalByRefObject { public string PortName { get; } /// <summary> /// The base Uri of the service. This resolves to a string such as <c>ipc://IntegrationService_{HostProcessId}"</c> /// </summary> public string BaseUri { get; } private readonly ConcurrentDictionary<string, ObjRef> _marshalledObjects = new ConcurrentDictionary<string, ObjRef>(); public IntegrationService() { AppContext.SetSwitch("Switch.System.Diagnostics.IgnorePortablePDBsInStackTraces", false); PortName = GetPortName(Process.GetCurrentProcess().Id); BaseUri = "ipc://" + this.PortName; } private static string GetPortName(int hostProcessId) { // Make the channel name well-known by using a static base and appending the process ID of the host return $"{nameof(IntegrationService)}_{{{hostProcessId}}}"; } public static IntegrationService GetInstanceFromHostProcess(Process hostProcess) { var uri = $"ipc://{GetPortName(hostProcess.Id)}/{typeof(IntegrationService).FullName}"; return (IntegrationService)Activator.GetObject(typeof(IntegrationService), uri); } public string? Execute(string assemblyFilePath, string typeFullName, string methodName) { var assembly = Assembly.LoadFrom(assemblyFilePath); var type = assembly.GetType(typeFullName); var methodInfo = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static); var result = methodInfo.Invoke(null, null); if (methodInfo.ReturnType == typeof(void)) { return null; } // Create a unique URL for each object returned, so that we can communicate with each object individually var resultType = result.GetType(); var marshallableResult = (MarshalByRefObject)result; var objectUri = $"{resultType.FullName}_{Guid.NewGuid()}"; var marshalledObject = RemotingServices.Marshal(marshallableResult, objectUri, resultType); if (!_marshalledObjects.TryAdd(objectUri, marshalledObject)) { throw new InvalidOperationException($"An object with the specified URI has already been marshalled. (URI: {objectUri})"); } return objectUri; } // Ensure InProcComponents live forever public override object? InitializeLifetimeService() => null; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Reflection; using System.Runtime.Remoting; namespace Microsoft.VisualStudio.IntegrationTest.Utilities { /// <summary> /// Provides a means of executing code in the Visual Studio host process. /// </summary> /// <remarks> /// This object exists in the Visual Studio host and is marhsalled across the process boundary. /// </remarks> internal class IntegrationService : MarshalByRefObject { public string PortName { get; } /// <summary> /// The base Uri of the service. This resolves to a string such as <c>ipc://IntegrationService_{HostProcessId}"</c> /// </summary> public string BaseUri { get; } private readonly ConcurrentDictionary<string, ObjRef> _marshalledObjects = new ConcurrentDictionary<string, ObjRef>(); public IntegrationService() { AppContext.SetSwitch("Switch.System.Diagnostics.IgnorePortablePDBsInStackTraces", false); PortName = GetPortName(Process.GetCurrentProcess().Id); BaseUri = "ipc://" + this.PortName; } private static string GetPortName(int hostProcessId) { // Make the channel name well-known by using a static base and appending the process ID of the host return $"{nameof(IntegrationService)}_{{{hostProcessId}}}"; } public static IntegrationService GetInstanceFromHostProcess(Process hostProcess) { var uri = $"ipc://{GetPortName(hostProcess.Id)}/{typeof(IntegrationService).FullName}"; return (IntegrationService)Activator.GetObject(typeof(IntegrationService), uri); } public string? Execute(string assemblyFilePath, string typeFullName, string methodName) { var assembly = Assembly.LoadFrom(assemblyFilePath); var type = assembly.GetType(typeFullName); var methodInfo = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static); var result = methodInfo.Invoke(null, null); if (methodInfo.ReturnType == typeof(void)) { return null; } // Create a unique URL for each object returned, so that we can communicate with each object individually var resultType = result.GetType(); var marshallableResult = (MarshalByRefObject)result; var objectUri = $"{resultType.FullName}_{Guid.NewGuid()}"; var marshalledObject = RemotingServices.Marshal(marshallableResult, objectUri, resultType); if (!_marshalledObjects.TryAdd(objectUri, marshalledObject)) { throw new InvalidOperationException($"An object with the specified URI has already been marshalled. (URI: {objectUri})"); } return objectUri; } // Ensure InProcComponents live forever public override object? InitializeLifetimeService() => null; } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/Core/Def/EditorConfigSettings/Analyzers/ViewModel/AnalyzerSettingsViewModel.SettingsSnapshotFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Analyzers.ViewModel { internal partial class AnalyzerSettingsViewModel : SettingsViewModelBase< AnalyzerSetting, AnalyzerSettingsViewModel.SettingsSnapshotFactory, AnalyzerSettingsViewModel.SettingsEntriesSnapshot> { internal sealed class SettingsSnapshotFactory : SettingsSnapshotFactoryBase<AnalyzerSetting, SettingsEntriesSnapshot> { public SettingsSnapshotFactory(ISettingsProvider<AnalyzerSetting> data) : base(data) { } protected override SettingsEntriesSnapshot CreateSnapshot(ImmutableArray<AnalyzerSetting> data, int currentVersionNumber) => new(data, currentVersionNumber); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Analyzers.ViewModel { internal partial class AnalyzerSettingsViewModel : SettingsViewModelBase< AnalyzerSetting, AnalyzerSettingsViewModel.SettingsSnapshotFactory, AnalyzerSettingsViewModel.SettingsEntriesSnapshot> { internal sealed class SettingsSnapshotFactory : SettingsSnapshotFactoryBase<AnalyzerSetting, SettingsEntriesSnapshot> { public SettingsSnapshotFactory(ISettingsProvider<AnalyzerSetting> data) : base(data) { } protected override SettingsEntriesSnapshot CreateSnapshot(ImmutableArray<AnalyzerSetting> data, int currentVersionNumber) => new(data, currentVersionNumber); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Analyzers/VisualBasic/CodeFixes/RemoveUnnecessaryParentheses/VisualBasicRemoveUnnecessaryParenthesesCodeFixProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryParentheses <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.RemoveUnnecessaryParentheses), [Shared]> Friend Class VisualBasicRemoveUnnecessaryParenthesesCodeFixProvider Inherits AbstractRemoveUnnecessaryParenthesesCodeFixProvider(Of ParenthesizedExpressionSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function CanRemoveParentheses(current As ParenthesizedExpressionSyntax, semanticModel As SemanticModel, cancellationtoken As CancellationToken) As Boolean Return VisualBasicRemoveUnnecessaryParenthesesDiagnosticAnalyzer.CanRemoveParenthesesHelper( current, semanticModel, precedence:=Nothing, clarifiesPrecedence:=Nothing) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryParentheses <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.RemoveUnnecessaryParentheses), [Shared]> Friend Class VisualBasicRemoveUnnecessaryParenthesesCodeFixProvider Inherits AbstractRemoveUnnecessaryParenthesesCodeFixProvider(Of ParenthesizedExpressionSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function CanRemoveParentheses(current As ParenthesizedExpressionSyntax, semanticModel As SemanticModel, cancellationtoken As CancellationToken) As Boolean Return VisualBasicRemoveUnnecessaryParenthesesDiagnosticAnalyzer.CanRemoveParenthesesHelper( current, semanticModel, precedence:=Nothing, clarifiesPrecedence:=Nothing) End Function End Class End Namespace
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/CSharpTest/KeywordHighlighting/SwitchStatementHighlighterTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting { public class SwitchStatementHighlighterTests : AbstractCSharpKeywordHighlighterTests { internal override Type GetHighlighterType() => typeof(SwitchStatementHighlighter); [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_OnSwitchKeyword() { await TestAsync( @"class C { void M() { {|Cursor:[|switch|]|} (i) { [|case|] 0: CaseZero(); [|break|]; [|case|] 1: CaseOne(); [|break|]; [|default|]: CaseOthers(); [|break|]; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_OnCaseKeyword() { await TestAsync( @"class C { void M() { [|switch|] (i) { {|Cursor:[|case|]|} 0: CaseZero(); [|break|]; [|case|] 1: CaseOne(); [|break|]; [|default|]: CaseOthers(); [|break|]; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_AfterCaseColon() { await TestAsync( @"class C { void M() { [|switch|] (i) { [|case|] 0:{|Cursor:|} CaseZero(); [|break|]; [|case|] 1: CaseOne(); [|break|]; [|default|]: CaseOthers(); [|break|]; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_NotOnCaseValue() { await TestAsync( @"class C { void M() { switch (i) { case {|Cursor:0|}: CaseZero(); break; case 1: CaseOne(); break; default: CaseOthers(); break; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_OnBreakStatement() { await TestAsync( @"class C { void M() { [|switch|] (i) { [|case|] 0: CaseZero(); {|Cursor:[|break|];|} [|case|] 1: CaseOne(); [|break|]; [|default|]: CaseOthers(); [|break|]; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_OnDefaultLabel() { await TestAsync( @"class C { void M() { [|switch|] (i) { [|case|] 0: CaseZero(); [|break|]; [|case|] 1: CaseOne(); [|break|]; {|Cursor:[|default|]:|} CaseOthers(); [|break|]; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_OnGotoCaseKeywords() { await TestAsync( @"class C { void M() { [|switch|] (i) { [|case|] 0: CaseZero(); {|Cursor:[|goto case|]|} 1; [|case|] 1: CaseOne(); [|goto default|]; [|default|]: CaseOthers(); [|break|]; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_AfterGotoCaseSemicolon() { await TestAsync( @"class C { void M() { [|switch|] (i) { [|case|] 0: CaseZero(); [|goto case|] 1;{|Cursor:|} [|case|] 1: CaseOne(); [|goto default|]; [|default|]: CaseOthers(); [|break|]; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_NotOnGotoCaseValue() { await TestAsync( @"class C { void M() { switch (i) { case 0: CaseZero(); goto case {|Cursor:1|}; case 1: CaseOne(); goto default; default: CaseOthers(); break; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_OnGotoDefaultStatement() { await TestAsync( @"class C { void M() { [|switch|] (i) { [|case|] 0: CaseZero(); [|goto case|] 1; [|case|] 1: CaseOne(); {|Cursor:[|goto default|];|} [|default|]: CaseOthers(); [|break|]; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_OnSwitchKeyword() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { {|Cursor:[|switch|]|} (b) { [|case|] 0: while (true) { do { break; } while (false); break; } [|break|]; } } for (int i = 0; i < 10; i++) { break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_OnCaseKeyword() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { [|switch|] (b) { {|Cursor:[|case|]|} 0: while (true) { do { break; } while (false); break; } [|break|]; } } for (int i = 0; i < 10; i++) { break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_NotBeforeCaseValue() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { switch (b) { case {|Cursor:|}0: while (true) { do { break; } while (false); break; } break; } } for (int i = 0; i < 10; i++) { break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_AfterCaseColon() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { [|switch|] (b) { [|case|] 0:{|Cursor:|} while (true) { do { break; } while (false); break; } [|break|]; } } for (int i = 0; i < 10; i++) { break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_OnBreakStatement() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { [|switch|] (b) { [|case|] 0: while (true) { do { break; } while (false); break; } {|Cursor:[|break|];|} } } for (int i = 0; i < 10; i++) { break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task Bug3483() { await TestAsync( @"class C { static void M() { [|switch|] (2) { [|case|] 1: {|Cursor:[|goto|]|} } } }"); } [WorkItem(25039, "https://github.com/dotnet/roslyn/issues/25039")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithUnrelatedGotoStatement_OnGotoCaseGotoKeyword() { await TestAsync( @"class C { void M() { label: [|switch|] (i) { [|case|] 0: CaseZero(); [|{|Cursor:goto|} case|] 1; [|case|] 1: CaseOne(); [|goto default|]; [|default|]: CaseOthers(); goto label; } } }"); } [WorkItem(25039, "https://github.com/dotnet/roslyn/issues/25039")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithUnrelatedGotoStatement_OnGotoDefaultGotoKeyword() { await TestAsync( @"class C { void M() { label: [|switch|] (i) { [|case|] 0: CaseZero(); [|goto case|] 1; [|case|] 1: CaseOne(); [|{|Cursor:goto|} default|]; [|default|]: CaseOthers(); goto label; } } }"); } [WorkItem(25039, "https://github.com/dotnet/roslyn/issues/25039")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithUnrelatedGotoStatement_NotOnGotoLabelGotoKeyword() { await TestAsync( @"class C { void M() { label: switch (i) { case 0: CaseZero(); goto case 1; case 1: CaseOne(); goto default; default: CaseOthers(); {|Cursor:goto|} label; } } }"); } [WorkItem(25039, "https://github.com/dotnet/roslyn/issues/25039")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithNestedStatements_OnSwitchKeyword() { await TestAsync( @"class C { void M() { {|Cursor:[|switch|]|} (i) { [|case|] 0: { CaseZero(); [|goto case|] 1; } [|case|] 1: { CaseOne(); [|goto default|]; } [|default|]: { CaseOthers(); [|break|]; } } } }"); } [WorkItem(25039, "https://github.com/dotnet/roslyn/issues/25039")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithNestedStatements_OnBreakKeyword() { await TestAsync( @"class C { void M() { [|switch|] (i) { [|case|] 0: { CaseZero(); [|goto case|] 1; } [|case|] 1: { CaseOne(); [|goto default|]; } [|default|]: { CaseOthers(); {|Cursor:[|break|]|}; } } } }"); } [WorkItem(25039, "https://github.com/dotnet/roslyn/issues/25039")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithGotoCaseAndBreakInsideLoop_OnSwitchKeyword() { await TestAsync( @"class C { void M() { {|Cursor:[|switch|]|} (true) { [|case|] true: while (true) { [|goto case|] true; break; switch (true) { case true: goto case true; break; } } } } }"); } [WorkItem(25039, "https://github.com/dotnet/roslyn/issues/25039")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithGotoCaseAndBreakInsideLoop_OnGotoCaseGotoKeyword() { await TestAsync( @"class C { void M() { [|switch|] (true) { [|case|] true: while (true) { [|{|Cursor:goto|} case|] true; break; switch (true) { case true: goto case true; break; } } } } }"); } [WorkItem(25039, "https://github.com/dotnet/roslyn/issues/25039")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithGotoCaseAndBreakInsideLoop_NotOnLoopBreakKeyword() { await TestAsync( @"class C { void M() { switch (true) { case true: while (true) { goto case true; {|Cursor:break|}; switch (true) { case true: goto case true; break; } } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithWhenClauseAndPattern_OnSwitchKeyword() { await TestAsync( @"class C { void M() { {|Cursor:[|switch|]|} (true) { [|case|] true when true: [|break|]; [|case|] bool b: [|break|]; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithWhenClauseAndPattern_NotOnWhenKeyword() { await TestAsync( @"class C { void M() { switch (true) { case true {|Cursor:when|} true: break; case bool b: break; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithWhenClauseAndPattern_AfterWhenCaseColon() { await TestAsync( @"class C { void M() { [|switch|] (true) { [|case|] true when true:{|Cursor:|} [|break|]; [|case|] bool b: [|break|]; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithWhenClauseAndPattern_AfterPatternCaseColon() { await TestAsync( @"class C { void M() { [|switch|] (true) { [|case|] true when true: [|break|]; [|case|] bool b:{|Cursor:|} [|break|]; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithWhenClauseAndPattern_NotOnWhenValue() { await TestAsync( @"class C { void M() { switch (true) { case true when {|Cursor:true|}: break; case bool b: break; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithWhenClauseAndPattern_NotOnPattern() { await TestAsync( @"class C { void M() { switch (true) { case true when true: break; case {|Cursor:bool b|}: break; } } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting { public class SwitchStatementHighlighterTests : AbstractCSharpKeywordHighlighterTests { internal override Type GetHighlighterType() => typeof(SwitchStatementHighlighter); [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_OnSwitchKeyword() { await TestAsync( @"class C { void M() { {|Cursor:[|switch|]|} (i) { [|case|] 0: CaseZero(); [|break|]; [|case|] 1: CaseOne(); [|break|]; [|default|]: CaseOthers(); [|break|]; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_OnCaseKeyword() { await TestAsync( @"class C { void M() { [|switch|] (i) { {|Cursor:[|case|]|} 0: CaseZero(); [|break|]; [|case|] 1: CaseOne(); [|break|]; [|default|]: CaseOthers(); [|break|]; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_AfterCaseColon() { await TestAsync( @"class C { void M() { [|switch|] (i) { [|case|] 0:{|Cursor:|} CaseZero(); [|break|]; [|case|] 1: CaseOne(); [|break|]; [|default|]: CaseOthers(); [|break|]; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_NotOnCaseValue() { await TestAsync( @"class C { void M() { switch (i) { case {|Cursor:0|}: CaseZero(); break; case 1: CaseOne(); break; default: CaseOthers(); break; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_OnBreakStatement() { await TestAsync( @"class C { void M() { [|switch|] (i) { [|case|] 0: CaseZero(); {|Cursor:[|break|];|} [|case|] 1: CaseOne(); [|break|]; [|default|]: CaseOthers(); [|break|]; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_OnDefaultLabel() { await TestAsync( @"class C { void M() { [|switch|] (i) { [|case|] 0: CaseZero(); [|break|]; [|case|] 1: CaseOne(); [|break|]; {|Cursor:[|default|]:|} CaseOthers(); [|break|]; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_OnGotoCaseKeywords() { await TestAsync( @"class C { void M() { [|switch|] (i) { [|case|] 0: CaseZero(); {|Cursor:[|goto case|]|} 1; [|case|] 1: CaseOne(); [|goto default|]; [|default|]: CaseOthers(); [|break|]; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_AfterGotoCaseSemicolon() { await TestAsync( @"class C { void M() { [|switch|] (i) { [|case|] 0: CaseZero(); [|goto case|] 1;{|Cursor:|} [|case|] 1: CaseOne(); [|goto default|]; [|default|]: CaseOthers(); [|break|]; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_NotOnGotoCaseValue() { await TestAsync( @"class C { void M() { switch (i) { case 0: CaseZero(); goto case {|Cursor:1|}; case 1: CaseOne(); goto default; default: CaseOthers(); break; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample2_OnGotoDefaultStatement() { await TestAsync( @"class C { void M() { [|switch|] (i) { [|case|] 0: CaseZero(); [|goto case|] 1; [|case|] 1: CaseOne(); {|Cursor:[|goto default|];|} [|default|]: CaseOthers(); [|break|]; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_OnSwitchKeyword() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { {|Cursor:[|switch|]|} (b) { [|case|] 0: while (true) { do { break; } while (false); break; } [|break|]; } } for (int i = 0; i < 10; i++) { break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_OnCaseKeyword() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { [|switch|] (b) { {|Cursor:[|case|]|} 0: while (true) { do { break; } while (false); break; } [|break|]; } } for (int i = 0; i < 10; i++) { break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_NotBeforeCaseValue() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { switch (b) { case {|Cursor:|}0: while (true) { do { break; } while (false); break; } break; } } for (int i = 0; i < 10; i++) { break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_AfterCaseColon() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { [|switch|] (b) { [|case|] 0:{|Cursor:|} while (true) { do { break; } while (false); break; } [|break|]; } } for (int i = 0; i < 10; i++) { break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestNestedExample1_OnBreakStatement() { await TestAsync( @"class C { void M() { foreach (var a in x) { if (a) { break; } else { [|switch|] (b) { [|case|] 0: while (true) { do { break; } while (false); break; } {|Cursor:[|break|];|} } } for (int i = 0; i < 10; i++) { break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task Bug3483() { await TestAsync( @"class C { static void M() { [|switch|] (2) { [|case|] 1: {|Cursor:[|goto|]|} } } }"); } [WorkItem(25039, "https://github.com/dotnet/roslyn/issues/25039")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithUnrelatedGotoStatement_OnGotoCaseGotoKeyword() { await TestAsync( @"class C { void M() { label: [|switch|] (i) { [|case|] 0: CaseZero(); [|{|Cursor:goto|} case|] 1; [|case|] 1: CaseOne(); [|goto default|]; [|default|]: CaseOthers(); goto label; } } }"); } [WorkItem(25039, "https://github.com/dotnet/roslyn/issues/25039")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithUnrelatedGotoStatement_OnGotoDefaultGotoKeyword() { await TestAsync( @"class C { void M() { label: [|switch|] (i) { [|case|] 0: CaseZero(); [|goto case|] 1; [|case|] 1: CaseOne(); [|{|Cursor:goto|} default|]; [|default|]: CaseOthers(); goto label; } } }"); } [WorkItem(25039, "https://github.com/dotnet/roslyn/issues/25039")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithUnrelatedGotoStatement_NotOnGotoLabelGotoKeyword() { await TestAsync( @"class C { void M() { label: switch (i) { case 0: CaseZero(); goto case 1; case 1: CaseOne(); goto default; default: CaseOthers(); {|Cursor:goto|} label; } } }"); } [WorkItem(25039, "https://github.com/dotnet/roslyn/issues/25039")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithNestedStatements_OnSwitchKeyword() { await TestAsync( @"class C { void M() { {|Cursor:[|switch|]|} (i) { [|case|] 0: { CaseZero(); [|goto case|] 1; } [|case|] 1: { CaseOne(); [|goto default|]; } [|default|]: { CaseOthers(); [|break|]; } } } }"); } [WorkItem(25039, "https://github.com/dotnet/roslyn/issues/25039")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithNestedStatements_OnBreakKeyword() { await TestAsync( @"class C { void M() { [|switch|] (i) { [|case|] 0: { CaseZero(); [|goto case|] 1; } [|case|] 1: { CaseOne(); [|goto default|]; } [|default|]: { CaseOthers(); {|Cursor:[|break|]|}; } } } }"); } [WorkItem(25039, "https://github.com/dotnet/roslyn/issues/25039")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithGotoCaseAndBreakInsideLoop_OnSwitchKeyword() { await TestAsync( @"class C { void M() { {|Cursor:[|switch|]|} (true) { [|case|] true: while (true) { [|goto case|] true; break; switch (true) { case true: goto case true; break; } } } } }"); } [WorkItem(25039, "https://github.com/dotnet/roslyn/issues/25039")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithGotoCaseAndBreakInsideLoop_OnGotoCaseGotoKeyword() { await TestAsync( @"class C { void M() { [|switch|] (true) { [|case|] true: while (true) { [|{|Cursor:goto|} case|] true; break; switch (true) { case true: goto case true; break; } } } } }"); } [WorkItem(25039, "https://github.com/dotnet/roslyn/issues/25039")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithGotoCaseAndBreakInsideLoop_NotOnLoopBreakKeyword() { await TestAsync( @"class C { void M() { switch (true) { case true: while (true) { goto case true; {|Cursor:break|}; switch (true) { case true: goto case true; break; } } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithWhenClauseAndPattern_OnSwitchKeyword() { await TestAsync( @"class C { void M() { {|Cursor:[|switch|]|} (true) { [|case|] true when true: [|break|]; [|case|] bool b: [|break|]; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithWhenClauseAndPattern_NotOnWhenKeyword() { await TestAsync( @"class C { void M() { switch (true) { case true {|Cursor:when|} true: break; case bool b: break; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithWhenClauseAndPattern_AfterWhenCaseColon() { await TestAsync( @"class C { void M() { [|switch|] (true) { [|case|] true when true:{|Cursor:|} [|break|]; [|case|] bool b: [|break|]; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithWhenClauseAndPattern_AfterPatternCaseColon() { await TestAsync( @"class C { void M() { [|switch|] (true) { [|case|] true when true: [|break|]; [|case|] bool b:{|Cursor:|} [|break|]; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithWhenClauseAndPattern_NotOnWhenValue() { await TestAsync( @"class C { void M() { switch (true) { case true when {|Cursor:true|}: break; case bool b: break; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestWithWhenClauseAndPattern_NotOnPattern() { await TestAsync( @"class C { void M() { switch (true) { case true when true: break; case {|Cursor:bool b|}: break; } } }"); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/Core/Implementation/Interactive/InteractiveWorkspace.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Interactive { internal partial class InteractiveWorkspace : Workspace { private readonly ISolutionCrawlerRegistrationService _registrationService; private SourceTextContainer? _openTextContainer; private DocumentId? _openDocumentId; internal InteractiveWorkspace(HostServices hostServices) : base(hostServices, WorkspaceKind.Interactive) { // register work coordinator for this workspace _registrationService = Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); _registrationService.Register(this); } protected override void Dispose(bool finalize) { // workspace is going away. unregister this workspace from work coordinator _registrationService.Unregister(this, blockingShutdown: true); base.Dispose(finalize); } public override bool CanOpenDocuments => true; public override bool CanApplyChange(ApplyChangesKind feature) => feature == ApplyChangesKind.ChangeDocument; public void OpenDocument(DocumentId documentId, SourceTextContainer textContainer) { _openTextContainer = textContainer; _openDocumentId = documentId; OnDocumentOpened(documentId, textContainer); } protected override void ApplyDocumentTextChanged(DocumentId document, SourceText newText) { if (_openDocumentId != document) { return; } Contract.ThrowIfNull(_openTextContainer); ITextSnapshot appliedText; using (var edit = _openTextContainer.GetTextBuffer().CreateEdit(EditOptions.DefaultMinimalChange, reiteratedVersionNumber: null, editTag: null)) { var oldText = _openTextContainer.CurrentText; var changes = newText.GetTextChanges(oldText); foreach (var change in changes) { edit.Replace(change.Span.Start, change.Span.Length, change.NewText); } appliedText = edit.Apply(); } OnDocumentTextChanged(document, appliedText.AsText(), PreservationMode.PreserveIdentity); } /// <summary> /// Closes all open documents and empties the solution but keeps all solution-level analyzers. /// </summary> public void ResetSolution() { ClearOpenDocuments(); var emptySolution = CreateSolution(SolutionId.CreateNewId("InteractiveSolution")); SetCurrentSolution(solution => emptySolution.WithAnalyzerReferences(solution.AnalyzerReferences), WorkspaceChangeKind.SolutionCleared); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Interactive { internal partial class InteractiveWorkspace : Workspace { private readonly ISolutionCrawlerRegistrationService _registrationService; private SourceTextContainer? _openTextContainer; private DocumentId? _openDocumentId; internal InteractiveWorkspace(HostServices hostServices) : base(hostServices, WorkspaceKind.Interactive) { // register work coordinator for this workspace _registrationService = Services.GetRequiredService<ISolutionCrawlerRegistrationService>(); _registrationService.Register(this); } protected override void Dispose(bool finalize) { // workspace is going away. unregister this workspace from work coordinator _registrationService.Unregister(this, blockingShutdown: true); base.Dispose(finalize); } public override bool CanOpenDocuments => true; public override bool CanApplyChange(ApplyChangesKind feature) => feature == ApplyChangesKind.ChangeDocument; public void OpenDocument(DocumentId documentId, SourceTextContainer textContainer) { _openTextContainer = textContainer; _openDocumentId = documentId; OnDocumentOpened(documentId, textContainer); } protected override void ApplyDocumentTextChanged(DocumentId document, SourceText newText) { if (_openDocumentId != document) { return; } Contract.ThrowIfNull(_openTextContainer); ITextSnapshot appliedText; using (var edit = _openTextContainer.GetTextBuffer().CreateEdit(EditOptions.DefaultMinimalChange, reiteratedVersionNumber: null, editTag: null)) { var oldText = _openTextContainer.CurrentText; var changes = newText.GetTextChanges(oldText); foreach (var change in changes) { edit.Replace(change.Span.Start, change.Span.Length, change.NewText); } appliedText = edit.Apply(); } OnDocumentTextChanged(document, appliedText.AsText(), PreservationMode.PreserveIdentity); } /// <summary> /// Closes all open documents and empties the solution but keeps all solution-level analyzers. /// </summary> public void ResetSolution() { ClearOpenDocuments(); var emptySolution = CreateSolution(SolutionId.CreateNewId("InteractiveSolution")); SetCurrentSolution(solution => emptySolution.WithAnalyzerReferences(solution.AnalyzerReferences), WorkspaceChangeKind.SolutionCleared); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/Core/EmbeddedLanguages/IEmbeddedLanguageEditorFeatures.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Features.EmbeddedLanguages; namespace Microsoft.CodeAnalysis.Editor.EmbeddedLanguages { /// <summary> /// Services related to a specific embedded language. /// </summary> internal interface IEmbeddedLanguageEditorFeatures : IEmbeddedLanguageFeatures { /// <summary> /// A optional brace matcher that can match braces in an embedded language string. /// </summary> IBraceMatcher BraceMatcher { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Features.EmbeddedLanguages; namespace Microsoft.CodeAnalysis.Editor.EmbeddedLanguages { /// <summary> /// Services related to a specific embedded language. /// </summary> internal interface IEmbeddedLanguageEditorFeatures : IEmbeddedLanguageFeatures { /// <summary> /// A optional brace matcher that can match braces in an embedded language string. /// </summary> IBraceMatcher BraceMatcher { get; } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/AbstractFormattingRule.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Formatting.Rules { /// <summary> /// Provide a custom formatting operation provider that can intercept/filter/replace default formatting operations. /// </summary> /// <remarks>All methods defined in this class can be called concurrently. Must be thread-safe.</remarks> internal abstract class AbstractFormattingRule { public virtual AbstractFormattingRule WithOptions(AnalyzerConfigOptions options) => this; /// <summary> /// Returns SuppressWrappingIfOnSingleLineOperations under a node either by itself or by /// filtering/replacing operations returned by NextOperation /// </summary> public virtual void AddSuppressOperations(List<SuppressOperation> list, SyntaxNode node, in NextSuppressOperationAction nextOperation) => nextOperation.Invoke(); /// <summary> /// returns AnchorIndentationOperations under a node either by itself or by filtering/replacing operations returned by NextOperation /// </summary> public virtual void AddAnchorIndentationOperations(List<AnchorIndentationOperation> list, SyntaxNode node, in NextAnchorIndentationOperationAction nextOperation) => nextOperation.Invoke(); /// <summary> /// returns IndentBlockOperations under a node either by itself or by filtering/replacing operations returned by NextOperation /// </summary> public virtual void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node, in NextIndentBlockOperationAction nextOperation) => nextOperation.Invoke(); /// <summary> /// returns AlignTokensOperations under a node either by itself or by filtering/replacing operations returned by NextOperation /// </summary> public virtual void AddAlignTokensOperations(List<AlignTokensOperation> list, SyntaxNode node, in NextAlignTokensOperationAction nextOperation) => nextOperation.Invoke(); /// <summary> /// returns AdjustNewLinesOperation between two tokens either by itself or by filtering/replacing a operation returned by NextOperation /// </summary> public virtual AdjustNewLinesOperation? GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) => nextOperation.Invoke(in previousToken, in currentToken); /// <summary> /// returns AdjustSpacesOperation between two tokens either by itself or by filtering/replacing a operation returned by NextOperation /// </summary> public virtual AdjustSpacesOperation? GetAdjustSpacesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustSpacesOperation nextOperation) => 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 System.Collections.Generic; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Formatting.Rules { /// <summary> /// Provide a custom formatting operation provider that can intercept/filter/replace default formatting operations. /// </summary> /// <remarks>All methods defined in this class can be called concurrently. Must be thread-safe.</remarks> internal abstract class AbstractFormattingRule { public virtual AbstractFormattingRule WithOptions(AnalyzerConfigOptions options) => this; /// <summary> /// Returns SuppressWrappingIfOnSingleLineOperations under a node either by itself or by /// filtering/replacing operations returned by NextOperation /// </summary> public virtual void AddSuppressOperations(List<SuppressOperation> list, SyntaxNode node, in NextSuppressOperationAction nextOperation) => nextOperation.Invoke(); /// <summary> /// returns AnchorIndentationOperations under a node either by itself or by filtering/replacing operations returned by NextOperation /// </summary> public virtual void AddAnchorIndentationOperations(List<AnchorIndentationOperation> list, SyntaxNode node, in NextAnchorIndentationOperationAction nextOperation) => nextOperation.Invoke(); /// <summary> /// returns IndentBlockOperations under a node either by itself or by filtering/replacing operations returned by NextOperation /// </summary> public virtual void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node, in NextIndentBlockOperationAction nextOperation) => nextOperation.Invoke(); /// <summary> /// returns AlignTokensOperations under a node either by itself or by filtering/replacing operations returned by NextOperation /// </summary> public virtual void AddAlignTokensOperations(List<AlignTokensOperation> list, SyntaxNode node, in NextAlignTokensOperationAction nextOperation) => nextOperation.Invoke(); /// <summary> /// returns AdjustNewLinesOperation between two tokens either by itself or by filtering/replacing a operation returned by NextOperation /// </summary> public virtual AdjustNewLinesOperation? GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) => nextOperation.Invoke(in previousToken, in currentToken); /// <summary> /// returns AdjustSpacesOperation between two tokens either by itself or by filtering/replacing a operation returned by NextOperation /// </summary> public virtual AdjustSpacesOperation? GetAdjustSpacesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustSpacesOperation nextOperation) => nextOperation.Invoke(in previousToken, in currentToken); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/Test/Resources/Core/SymbolsTests/ExplicitInterfaceImplementation/CSharpExplicitInterfaceImplementation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //csc /target:library interface Interface { void Method(); } class Class : Interface { void Interface.Method() { } } interface IGeneric<T> { void Method<U, Z>(T t, U u); //wrong number of type parameters void Method<U>(T t); //wrong number of parameters void Method<U>(U u, T t); //wrong parameter types void Method<U>(T t, ref U u); //wrong parameter refness T Method<U>(T t1, T t2); //wrong return type void Method<U>(T t, U u); //match } class Generic<S> : IGeneric<S> { void IGeneric<S>.Method<U, Z>(S s, U u) { } void IGeneric<S>.Method<U>(S s) { } void IGeneric<S>.Method<U>(U u, S s) { } void IGeneric<S>.Method<U>(S s, ref U u) { } S IGeneric<S>.Method<U>(S s1, S s2) { return s1; } void IGeneric<S>.Method<V>(S s, V v) { } } class Constructed : IGeneric<int> { void IGeneric<int>.Method<U, Z>(int i, U u) { } void IGeneric<int>.Method<U>(int i) { } void IGeneric<int>.Method<U>(U u, int i) { } void IGeneric<int>.Method<U>(int i, ref U u) { } int IGeneric<int>.Method<U>(int i1, int i2) { return i1; } void IGeneric<int>.Method<W>(int i, W w) { } } interface IGenericInterface<T> : Interface { } //we'll see a type def for this class, a type ref for IGenericInterface<int>, //and then a type def for Interface (i.e. back and forth) class IndirectImplementation : IGenericInterface<int> { void Interface.Method() { } } interface IGeneric2<T> { void Method(T t); } class Outer<T> { internal interface IInner<U> { void Method(U u); } internal class Inner1<A> : IGeneric2<A> //outer interface, inner type param { void IGeneric2<A>.Method(A a) { } } internal class Inner2<B> : IGeneric2<T> //outer interface, outer type param { void IGeneric2<T>.Method(T t) { } } internal class Inner3<C> : IInner<C> //inner interface, inner type param { void IInner<C>.Method(C b) { } } internal class Inner4<D> : IInner<T> //inner interface, outer type param { void IInner<T>.Method(T t) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //csc /target:library interface Interface { void Method(); } class Class : Interface { void Interface.Method() { } } interface IGeneric<T> { void Method<U, Z>(T t, U u); //wrong number of type parameters void Method<U>(T t); //wrong number of parameters void Method<U>(U u, T t); //wrong parameter types void Method<U>(T t, ref U u); //wrong parameter refness T Method<U>(T t1, T t2); //wrong return type void Method<U>(T t, U u); //match } class Generic<S> : IGeneric<S> { void IGeneric<S>.Method<U, Z>(S s, U u) { } void IGeneric<S>.Method<U>(S s) { } void IGeneric<S>.Method<U>(U u, S s) { } void IGeneric<S>.Method<U>(S s, ref U u) { } S IGeneric<S>.Method<U>(S s1, S s2) { return s1; } void IGeneric<S>.Method<V>(S s, V v) { } } class Constructed : IGeneric<int> { void IGeneric<int>.Method<U, Z>(int i, U u) { } void IGeneric<int>.Method<U>(int i) { } void IGeneric<int>.Method<U>(U u, int i) { } void IGeneric<int>.Method<U>(int i, ref U u) { } int IGeneric<int>.Method<U>(int i1, int i2) { return i1; } void IGeneric<int>.Method<W>(int i, W w) { } } interface IGenericInterface<T> : Interface { } //we'll see a type def for this class, a type ref for IGenericInterface<int>, //and then a type def for Interface (i.e. back and forth) class IndirectImplementation : IGenericInterface<int> { void Interface.Method() { } } interface IGeneric2<T> { void Method(T t); } class Outer<T> { internal interface IInner<U> { void Method(U u); } internal class Inner1<A> : IGeneric2<A> //outer interface, inner type param { void IGeneric2<A>.Method(A a) { } } internal class Inner2<B> : IGeneric2<T> //outer interface, outer type param { void IGeneric2<T>.Method(T t) { } } internal class Inner3<C> : IInner<C> //inner interface, inner type param { void IInner<C>.Method(C b) { } } internal class Inner4<D> : IInner<T> //inner interface, outer type param { void IInner<T>.Method(T t) { } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicParenthesesReducer.Rewriter.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.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend Class VisualBasicParenthesesReducer Private Class Rewriter Inherits AbstractReductionRewriter Public Sub New(pool As ObjectPool(Of IReductionRewriter)) MyBase.New(pool) End Sub Public Overrides Function VisitParenthesizedExpression(node As ParenthesizedExpressionSyntax) As SyntaxNode Return SimplifyExpression( node, newNode:=MyBase.VisitParenthesizedExpression(node), simplifier:=s_reduceParentheses) 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 Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend Class VisualBasicParenthesesReducer Private Class Rewriter Inherits AbstractReductionRewriter Public Sub New(pool As ObjectPool(Of IReductionRewriter)) MyBase.New(pool) End Sub Public Overrides Function VisitParenthesizedExpression(node As ParenthesizedExpressionSyntax) As SyntaxNode Return SimplifyExpression( node, newNode:=MyBase.VisitParenthesizedExpression(node), simplifier:=s_reduceParentheses) End Function End Class End Class End Namespace
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer_GetDiagnostics.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { public Task<ImmutableArray<DiagnosticData>> GetSpecificCachedDiagnosticsAsync(Solution solution, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) { if (id is not LiveDiagnosticUpdateArgsId argsId) { return SpecializedTasks.EmptyImmutableArray<DiagnosticData>(); } var (documentId, projectId) = (argsId.ProjectOrDocumentId is DocumentId docId) ? (docId, docId.ProjectId) : (null, (ProjectId)argsId.ProjectOrDocumentId); return new IdeCachedDiagnosticGetter(this, solution, projectId, documentId, includeSuppressedDiagnostics).GetSpecificDiagnosticsAsync(argsId.Analyzer, (AnalysisKind)argsId.Kind, cancellationToken); } public Task<ImmutableArray<DiagnosticData>> GetCachedDiagnosticsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeCachedDiagnosticGetter(this, solution, projectId, documentId, includeSuppressedDiagnostics).GetDiagnosticsAsync(cancellationToken); public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeLatestDiagnosticGetter(this, solution, projectId, documentId, diagnosticIds: null, includeSuppressedDiagnostics).GetDiagnosticsAsync(cancellationToken); public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, ImmutableHashSet<string>? diagnosticIds, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeLatestDiagnosticGetter(this, solution, projectId, documentId, diagnosticIds, includeSuppressedDiagnostics).GetDiagnosticsAsync(cancellationToken); public Task<ImmutableArray<DiagnosticData>> GetProjectDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId, ImmutableHashSet<string>? diagnosticIds, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeLatestDiagnosticGetter(this, solution, projectId, documentId: null, diagnosticIds: diagnosticIds, includeSuppressedDiagnostics).GetProjectDiagnosticsAsync(cancellationToken); private abstract class DiagnosticGetter { protected readonly DiagnosticIncrementalAnalyzer Owner; protected readonly Solution Solution; protected readonly ProjectId? ProjectId; protected readonly DocumentId? DocumentId; protected readonly bool IncludeSuppressedDiagnostics; private ImmutableArray<DiagnosticData>.Builder? _lazyDataBuilder; public DiagnosticGetter( DiagnosticIncrementalAnalyzer owner, Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics) { Owner = owner; Solution = solution; DocumentId = documentId; ProjectId = projectId ?? documentId?.ProjectId; IncludeSuppressedDiagnostics = includeSuppressedDiagnostics; } protected StateManager StateManager => Owner._stateManager; protected virtual bool ShouldIncludeDiagnostic(DiagnosticData diagnostic) => true; protected ImmutableArray<DiagnosticData> GetDiagnosticData() => (_lazyDataBuilder != null) ? _lazyDataBuilder.ToImmutableArray() : ImmutableArray<DiagnosticData>.Empty; protected abstract Task AppendDiagnosticsAsync(Project project, IEnumerable<DocumentId> documentIds, bool includeProjectNonLocalResult, CancellationToken cancellationToken); public async Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(CancellationToken cancellationToken) { if (ProjectId != null) { var project = Solution.GetProject(ProjectId); if (project == null) { return GetDiagnosticData(); } var documentIds = (DocumentId != null) ? SpecializedCollections.SingletonEnumerable(DocumentId) : project.DocumentIds; // return diagnostics specific to one project or document var includeProjectNonLocalResult = DocumentId == null; await AppendDiagnosticsAsync(project, documentIds, includeProjectNonLocalResult, cancellationToken).ConfigureAwait(false); return GetDiagnosticData(); } await AppendDiagnosticsAsync(Solution, cancellationToken).ConfigureAwait(false); return GetDiagnosticData(); } protected async Task AppendDiagnosticsAsync(Solution solution, CancellationToken cancellationToken) { // PERF: run projects in parallel rather than running CompilationWithAnalyzer with concurrency == true. // We do this to not get into thread starvation causing hundreds of threads to be spawned. var includeProjectNonLocalResult = true; var tasks = new Task[solution.ProjectIds.Count]; var index = 0; foreach (var project in solution.Projects) { var localProject = project; tasks[index++] = Task.Run( () => AppendDiagnosticsAsync( localProject, localProject.DocumentIds, includeProjectNonLocalResult, cancellationToken), cancellationToken); } await Task.WhenAll(tasks).ConfigureAwait(false); } protected void AppendDiagnostics(ImmutableArray<DiagnosticData> items) { Debug.Assert(!items.IsDefault); if (_lazyDataBuilder == null) { Interlocked.CompareExchange(ref _lazyDataBuilder, ImmutableArray.CreateBuilder<DiagnosticData>(), null); } lock (_lazyDataBuilder) { _lazyDataBuilder.AddRange(items.Where(ShouldIncludeSuppressedDiagnostic).Where(ShouldIncludeDiagnostic)); } } private bool ShouldIncludeSuppressedDiagnostic(DiagnosticData diagnostic) => IncludeSuppressedDiagnostics || !diagnostic.IsSuppressed; } private sealed class IdeCachedDiagnosticGetter : DiagnosticGetter { public IdeCachedDiagnosticGetter(DiagnosticIncrementalAnalyzer owner, Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics) : base(owner, solution, projectId, documentId, includeSuppressedDiagnostics) { } protected override async Task AppendDiagnosticsAsync(Project project, IEnumerable<DocumentId> documentIds, bool includeProjectNonLocalResult, CancellationToken cancellationToken) { foreach (var stateSet in StateManager.GetStateSets(project.Id)) { foreach (var documentId in documentIds) { AppendDiagnostics(await GetDiagnosticsAsync(stateSet, project, documentId, AnalysisKind.Syntax, cancellationToken).ConfigureAwait(false)); AppendDiagnostics(await GetDiagnosticsAsync(stateSet, project, documentId, AnalysisKind.Semantic, cancellationToken).ConfigureAwait(false)); AppendDiagnostics(await GetDiagnosticsAsync(stateSet, project, documentId, AnalysisKind.NonLocal, cancellationToken).ConfigureAwait(false)); } if (includeProjectNonLocalResult) { // include project diagnostics if there is no target document AppendDiagnostics(await GetProjectStateDiagnosticsAsync(stateSet, project, documentId: null, AnalysisKind.NonLocal, cancellationToken).ConfigureAwait(false)); } } } public async Task<ImmutableArray<DiagnosticData>> GetSpecificDiagnosticsAsync(DiagnosticAnalyzer analyzer, AnalysisKind analysisKind, CancellationToken cancellationToken) { var project = Solution.GetProject(ProjectId); if (project == null) { // when we return cached result, make sure we at least return something that exist in current solution return ImmutableArray<DiagnosticData>.Empty; } var stateSet = StateManager.GetOrCreateStateSet(project, analyzer); if (stateSet == null) { return ImmutableArray<DiagnosticData>.Empty; } var diagnostics = await GetDiagnosticsAsync(stateSet, project, DocumentId, analysisKind, cancellationToken).ConfigureAwait(false); return IncludeSuppressedDiagnostics ? diagnostics : diagnostics.WhereAsArray(d => !d.IsSuppressed); } private static async Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(StateSet stateSet, Project project, DocumentId? documentId, AnalysisKind kind, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // active file diagnostics: if (documentId != null && kind != AnalysisKind.NonLocal && stateSet.TryGetActiveFileState(documentId, out var state)) { return state.GetAnalysisData(kind).Items; } // project diagnostics: return await GetProjectStateDiagnosticsAsync(stateSet, project, documentId, kind, cancellationToken).ConfigureAwait(false); } private static async Task<ImmutableArray<DiagnosticData>> GetProjectStateDiagnosticsAsync(StateSet stateSet, Project project, DocumentId? documentId, AnalysisKind kind, CancellationToken cancellationToken) { if (!stateSet.TryGetProjectState(project.Id, out var state)) { // never analyzed this project yet. return ImmutableArray<DiagnosticData>.Empty; } if (documentId != null) { // file doesn't exist in current solution var document = project.Solution.GetDocument(documentId); if (document == null) { return ImmutableArray<DiagnosticData>.Empty; } var result = await state.GetAnalysisDataAsync(document, avoidLoadingData: false, cancellationToken).ConfigureAwait(false); return result.GetDocumentDiagnostics(documentId, kind); } Contract.ThrowIfFalse(kind == AnalysisKind.NonLocal); var nonLocalResult = await state.GetProjectAnalysisDataAsync(project, avoidLoadingData: false, cancellationToken: cancellationToken).ConfigureAwait(false); return nonLocalResult.GetOtherDiagnostics(); } } private sealed class IdeLatestDiagnosticGetter : DiagnosticGetter { private readonly ImmutableHashSet<string>? _diagnosticIds; public IdeLatestDiagnosticGetter(DiagnosticIncrementalAnalyzer owner, Solution solution, ProjectId? projectId, DocumentId? documentId, ImmutableHashSet<string>? diagnosticIds, bool includeSuppressedDiagnostics) : base(owner, solution, projectId, documentId, includeSuppressedDiagnostics) { _diagnosticIds = diagnosticIds; } public async Task<ImmutableArray<DiagnosticData>> GetProjectDiagnosticsAsync(CancellationToken cancellationToken) { if (ProjectId != null) { var project = Solution.GetProject(ProjectId); if (project != null) { await AppendDiagnosticsAsync(project, SpecializedCollections.EmptyEnumerable<DocumentId>(), includeProjectNonLocalResult: true, cancellationToken).ConfigureAwait(false); } return GetDiagnosticData(); } await AppendDiagnosticsAsync(Solution, cancellationToken).ConfigureAwait(false); return GetDiagnosticData(); } protected override bool ShouldIncludeDiagnostic(DiagnosticData diagnostic) => _diagnosticIds == null || _diagnosticIds.Contains(diagnostic.Id); protected override async Task AppendDiagnosticsAsync(Project project, IEnumerable<DocumentId> documentIds, bool includeProjectNonLocalResult, CancellationToken cancellationToken) { // get analyzers that are not suppressed. var stateSets = StateManager.GetOrCreateStateSets(project).Where(s => ShouldIncludeStateSet(project, s)).ToImmutableArrayOrEmpty(); // unlike the suppressed (disabled) analyzer, we will include hidden diagnostic only analyzers here. var compilation = await CreateCompilationWithAnalyzersAsync(project, stateSets, IncludeSuppressedDiagnostics, cancellationToken).ConfigureAwait(false); var result = await Owner.GetProjectAnalysisDataAsync(compilation, project, stateSets, forceAnalyzerRun: true, cancellationToken).ConfigureAwait(false); foreach (var stateSet in stateSets) { var analysisResult = result.GetResult(stateSet.Analyzer); foreach (var documentId in documentIds) { AppendDiagnostics(analysisResult.GetDocumentDiagnostics(documentId, AnalysisKind.Syntax)); AppendDiagnostics(analysisResult.GetDocumentDiagnostics(documentId, AnalysisKind.Semantic)); AppendDiagnostics(analysisResult.GetDocumentDiagnostics(documentId, AnalysisKind.NonLocal)); } if (includeProjectNonLocalResult) { // include project diagnostics if there is no target document AppendDiagnostics(analysisResult.GetOtherDiagnostics()); } } } private bool ShouldIncludeStateSet(Project project, StateSet stateSet) { var infoCache = Owner.DiagnosticAnalyzerInfoCache; if (infoCache.IsAnalyzerSuppressed(stateSet.Analyzer, project)) { return false; } if (_diagnosticIds != null && infoCache.GetDiagnosticDescriptors(stateSet.Analyzer).All(d => !_diagnosticIds.Contains(d.Id))) { return false; } return true; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { public Task<ImmutableArray<DiagnosticData>> GetSpecificCachedDiagnosticsAsync(Solution solution, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) { if (id is not LiveDiagnosticUpdateArgsId argsId) { return SpecializedTasks.EmptyImmutableArray<DiagnosticData>(); } var (documentId, projectId) = (argsId.ProjectOrDocumentId is DocumentId docId) ? (docId, docId.ProjectId) : (null, (ProjectId)argsId.ProjectOrDocumentId); return new IdeCachedDiagnosticGetter(this, solution, projectId, documentId, includeSuppressedDiagnostics).GetSpecificDiagnosticsAsync(argsId.Analyzer, (AnalysisKind)argsId.Kind, cancellationToken); } public Task<ImmutableArray<DiagnosticData>> GetCachedDiagnosticsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeCachedDiagnosticGetter(this, solution, projectId, documentId, includeSuppressedDiagnostics).GetDiagnosticsAsync(cancellationToken); public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeLatestDiagnosticGetter(this, solution, projectId, documentId, diagnosticIds: null, includeSuppressedDiagnostics).GetDiagnosticsAsync(cancellationToken); public Task<ImmutableArray<DiagnosticData>> GetDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId, DocumentId? documentId, ImmutableHashSet<string>? diagnosticIds, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeLatestDiagnosticGetter(this, solution, projectId, documentId, diagnosticIds, includeSuppressedDiagnostics).GetDiagnosticsAsync(cancellationToken); public Task<ImmutableArray<DiagnosticData>> GetProjectDiagnosticsForIdsAsync(Solution solution, ProjectId? projectId, ImmutableHashSet<string>? diagnosticIds, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) => new IdeLatestDiagnosticGetter(this, solution, projectId, documentId: null, diagnosticIds: diagnosticIds, includeSuppressedDiagnostics).GetProjectDiagnosticsAsync(cancellationToken); private abstract class DiagnosticGetter { protected readonly DiagnosticIncrementalAnalyzer Owner; protected readonly Solution Solution; protected readonly ProjectId? ProjectId; protected readonly DocumentId? DocumentId; protected readonly bool IncludeSuppressedDiagnostics; private ImmutableArray<DiagnosticData>.Builder? _lazyDataBuilder; public DiagnosticGetter( DiagnosticIncrementalAnalyzer owner, Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics) { Owner = owner; Solution = solution; DocumentId = documentId; ProjectId = projectId ?? documentId?.ProjectId; IncludeSuppressedDiagnostics = includeSuppressedDiagnostics; } protected StateManager StateManager => Owner._stateManager; protected virtual bool ShouldIncludeDiagnostic(DiagnosticData diagnostic) => true; protected ImmutableArray<DiagnosticData> GetDiagnosticData() => (_lazyDataBuilder != null) ? _lazyDataBuilder.ToImmutableArray() : ImmutableArray<DiagnosticData>.Empty; protected abstract Task AppendDiagnosticsAsync(Project project, IEnumerable<DocumentId> documentIds, bool includeProjectNonLocalResult, CancellationToken cancellationToken); public async Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(CancellationToken cancellationToken) { if (ProjectId != null) { var project = Solution.GetProject(ProjectId); if (project == null) { return GetDiagnosticData(); } var documentIds = (DocumentId != null) ? SpecializedCollections.SingletonEnumerable(DocumentId) : project.DocumentIds; // return diagnostics specific to one project or document var includeProjectNonLocalResult = DocumentId == null; await AppendDiagnosticsAsync(project, documentIds, includeProjectNonLocalResult, cancellationToken).ConfigureAwait(false); return GetDiagnosticData(); } await AppendDiagnosticsAsync(Solution, cancellationToken).ConfigureAwait(false); return GetDiagnosticData(); } protected async Task AppendDiagnosticsAsync(Solution solution, CancellationToken cancellationToken) { // PERF: run projects in parallel rather than running CompilationWithAnalyzer with concurrency == true. // We do this to not get into thread starvation causing hundreds of threads to be spawned. var includeProjectNonLocalResult = true; var tasks = new Task[solution.ProjectIds.Count]; var index = 0; foreach (var project in solution.Projects) { var localProject = project; tasks[index++] = Task.Run( () => AppendDiagnosticsAsync( localProject, localProject.DocumentIds, includeProjectNonLocalResult, cancellationToken), cancellationToken); } await Task.WhenAll(tasks).ConfigureAwait(false); } protected void AppendDiagnostics(ImmutableArray<DiagnosticData> items) { Debug.Assert(!items.IsDefault); if (_lazyDataBuilder == null) { Interlocked.CompareExchange(ref _lazyDataBuilder, ImmutableArray.CreateBuilder<DiagnosticData>(), null); } lock (_lazyDataBuilder) { _lazyDataBuilder.AddRange(items.Where(ShouldIncludeSuppressedDiagnostic).Where(ShouldIncludeDiagnostic)); } } private bool ShouldIncludeSuppressedDiagnostic(DiagnosticData diagnostic) => IncludeSuppressedDiagnostics || !diagnostic.IsSuppressed; } private sealed class IdeCachedDiagnosticGetter : DiagnosticGetter { public IdeCachedDiagnosticGetter(DiagnosticIncrementalAnalyzer owner, Solution solution, ProjectId? projectId, DocumentId? documentId, bool includeSuppressedDiagnostics) : base(owner, solution, projectId, documentId, includeSuppressedDiagnostics) { } protected override async Task AppendDiagnosticsAsync(Project project, IEnumerable<DocumentId> documentIds, bool includeProjectNonLocalResult, CancellationToken cancellationToken) { foreach (var stateSet in StateManager.GetStateSets(project.Id)) { foreach (var documentId in documentIds) { AppendDiagnostics(await GetDiagnosticsAsync(stateSet, project, documentId, AnalysisKind.Syntax, cancellationToken).ConfigureAwait(false)); AppendDiagnostics(await GetDiagnosticsAsync(stateSet, project, documentId, AnalysisKind.Semantic, cancellationToken).ConfigureAwait(false)); AppendDiagnostics(await GetDiagnosticsAsync(stateSet, project, documentId, AnalysisKind.NonLocal, cancellationToken).ConfigureAwait(false)); } if (includeProjectNonLocalResult) { // include project diagnostics if there is no target document AppendDiagnostics(await GetProjectStateDiagnosticsAsync(stateSet, project, documentId: null, AnalysisKind.NonLocal, cancellationToken).ConfigureAwait(false)); } } } public async Task<ImmutableArray<DiagnosticData>> GetSpecificDiagnosticsAsync(DiagnosticAnalyzer analyzer, AnalysisKind analysisKind, CancellationToken cancellationToken) { var project = Solution.GetProject(ProjectId); if (project == null) { // when we return cached result, make sure we at least return something that exist in current solution return ImmutableArray<DiagnosticData>.Empty; } var stateSet = StateManager.GetOrCreateStateSet(project, analyzer); if (stateSet == null) { return ImmutableArray<DiagnosticData>.Empty; } var diagnostics = await GetDiagnosticsAsync(stateSet, project, DocumentId, analysisKind, cancellationToken).ConfigureAwait(false); return IncludeSuppressedDiagnostics ? diagnostics : diagnostics.WhereAsArray(d => !d.IsSuppressed); } private static async Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(StateSet stateSet, Project project, DocumentId? documentId, AnalysisKind kind, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // active file diagnostics: if (documentId != null && kind != AnalysisKind.NonLocal && stateSet.TryGetActiveFileState(documentId, out var state)) { return state.GetAnalysisData(kind).Items; } // project diagnostics: return await GetProjectStateDiagnosticsAsync(stateSet, project, documentId, kind, cancellationToken).ConfigureAwait(false); } private static async Task<ImmutableArray<DiagnosticData>> GetProjectStateDiagnosticsAsync(StateSet stateSet, Project project, DocumentId? documentId, AnalysisKind kind, CancellationToken cancellationToken) { if (!stateSet.TryGetProjectState(project.Id, out var state)) { // never analyzed this project yet. return ImmutableArray<DiagnosticData>.Empty; } if (documentId != null) { // file doesn't exist in current solution var document = project.Solution.GetDocument(documentId); if (document == null) { return ImmutableArray<DiagnosticData>.Empty; } var result = await state.GetAnalysisDataAsync(document, avoidLoadingData: false, cancellationToken).ConfigureAwait(false); return result.GetDocumentDiagnostics(documentId, kind); } Contract.ThrowIfFalse(kind == AnalysisKind.NonLocal); var nonLocalResult = await state.GetProjectAnalysisDataAsync(project, avoidLoadingData: false, cancellationToken: cancellationToken).ConfigureAwait(false); return nonLocalResult.GetOtherDiagnostics(); } } private sealed class IdeLatestDiagnosticGetter : DiagnosticGetter { private readonly ImmutableHashSet<string>? _diagnosticIds; public IdeLatestDiagnosticGetter(DiagnosticIncrementalAnalyzer owner, Solution solution, ProjectId? projectId, DocumentId? documentId, ImmutableHashSet<string>? diagnosticIds, bool includeSuppressedDiagnostics) : base(owner, solution, projectId, documentId, includeSuppressedDiagnostics) { _diagnosticIds = diagnosticIds; } public async Task<ImmutableArray<DiagnosticData>> GetProjectDiagnosticsAsync(CancellationToken cancellationToken) { if (ProjectId != null) { var project = Solution.GetProject(ProjectId); if (project != null) { await AppendDiagnosticsAsync(project, SpecializedCollections.EmptyEnumerable<DocumentId>(), includeProjectNonLocalResult: true, cancellationToken).ConfigureAwait(false); } return GetDiagnosticData(); } await AppendDiagnosticsAsync(Solution, cancellationToken).ConfigureAwait(false); return GetDiagnosticData(); } protected override bool ShouldIncludeDiagnostic(DiagnosticData diagnostic) => _diagnosticIds == null || _diagnosticIds.Contains(diagnostic.Id); protected override async Task AppendDiagnosticsAsync(Project project, IEnumerable<DocumentId> documentIds, bool includeProjectNonLocalResult, CancellationToken cancellationToken) { // get analyzers that are not suppressed. var stateSets = StateManager.GetOrCreateStateSets(project).Where(s => ShouldIncludeStateSet(project, s)).ToImmutableArrayOrEmpty(); // unlike the suppressed (disabled) analyzer, we will include hidden diagnostic only analyzers here. var compilation = await CreateCompilationWithAnalyzersAsync(project, stateSets, IncludeSuppressedDiagnostics, cancellationToken).ConfigureAwait(false); var result = await Owner.GetProjectAnalysisDataAsync(compilation, project, stateSets, forceAnalyzerRun: true, cancellationToken).ConfigureAwait(false); foreach (var stateSet in stateSets) { var analysisResult = result.GetResult(stateSet.Analyzer); foreach (var documentId in documentIds) { AppendDiagnostics(analysisResult.GetDocumentDiagnostics(documentId, AnalysisKind.Syntax)); AppendDiagnostics(analysisResult.GetDocumentDiagnostics(documentId, AnalysisKind.Semantic)); AppendDiagnostics(analysisResult.GetDocumentDiagnostics(documentId, AnalysisKind.NonLocal)); } if (includeProjectNonLocalResult) { // include project diagnostics if there is no target document AppendDiagnostics(analysisResult.GetOtherDiagnostics()); } } } private bool ShouldIncludeStateSet(Project project, StateSet stateSet) { var infoCache = Owner.DiagnosticAnalyzerInfoCache; if (infoCache.IsAnalyzerSuppressed(stateSet.Analyzer, project)) { return false; } if (_diagnosticIds != null && infoCache.GetDiagnosticDescriptors(stateSet.Analyzer).All(d => !_diagnosticIds.Contains(d.Id))) { return false; } return true; } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/Grammar/GrammarGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable // We only support grammar generation in the command line version for now which is the netcoreapp target #if NETCOREAPP using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.CSharp; namespace CSharpSyntaxGenerator.Grammar { internal static class GrammarGenerator { public static string Run(List<TreeType> types) { // Syntax.xml refers to a special pseudo-element 'Modifier'. Synthesize that for the grammar. var modifiers = GetMembers<DeclarationModifiers>() .Select(m => m + "Keyword").Where(n => GetSyntaxKind(n) != SyntaxKind.None) .Select(n => new Kind { Name = n }).ToList(); types.Add(new Node { Name = "Modifier", Children = { new Field { Type = "SyntaxToken", Kinds = modifiers } } }); var rules = types.ToDictionary(n => n.Name, _ => new List<Production>()); foreach (var type in types) { if (type.Base != null && rules.TryGetValue(type.Base, out var productions)) productions.Add(RuleReference(type.Name)); if (type is Node && type.Children.Count > 0) { // Convert rules like `a: (x | y) ...` into: // a: x ... // | y ...; if (type.Children[0] is Field field && field.Kinds.Count > 0) { foreach (var kind in field.Kinds) { field.Kinds = new List<Kind> { kind }; rules[type.Name].Add(HandleChildren(type.Children)); } } else { rules[type.Name].Add(HandleChildren(type.Children)); } } } // The grammar will bottom out with certain lexical productions. Create rules for these. var lexicalRules = rules.Values.SelectMany(ps => ps).SelectMany(p => p.ReferencedRules) .Where(r => !rules.TryGetValue(r, out var productions) || productions.Count == 0).ToArray(); foreach (var name in lexicalRules) rules[name] = new List<Production> { new Production("/* see lexical specification */") }; var seen = new HashSet<string>(); // Define a few major sections to help keep the grammar file naturally grouped. var majorRules = ImmutableArray.Create( "CompilationUnitSyntax", "MemberDeclarationSyntax", "TypeSyntax", "StatementSyntax", "ExpressionSyntax", "XmlNodeSyntax", "StructuredTriviaSyntax"); var result = "// <auto-generated />" + Environment.NewLine + "grammar csharp;" + Environment.NewLine; // Handle each major section first and then walk any rules not hit transitively from them. foreach (var rule in majorRules.Concat(rules.Keys.OrderBy(a => a))) processRule(rule, ref result); return result; void processRule(string name, ref string result) { if (name != "CSharpSyntaxNode" && seen.Add(name)) { // Order the productions to keep us independent from whatever changes happen in Syntax.xml. var sorted = rules[name].OrderBy(v => v); result += Environment.NewLine + RuleReference(name).Text + Environment.NewLine + " : " + string.Join(Environment.NewLine + " | ", sorted) + Environment.NewLine + " ;" + Environment.NewLine; // Now proceed in depth-first fashion through the referenced rules to keep related rules // close by. Don't recurse into major-sections to help keep them separated in grammar file. foreach (var production in sorted) foreach (var referencedRule in production.ReferencedRules) if (!majorRules.Concat(lexicalRules).Contains(referencedRule)) processRule(referencedRule, ref result); } } } private static Production Join(string delim, IEnumerable<Production> productions) => new Production(string.Join(delim, productions.Where(p => p.Text.Length > 0)), productions.SelectMany(p => p.ReferencedRules)); private static Production HandleChildren(IEnumerable<TreeTypeChild> children, string delim = " ") => Join(delim, children.Select(child => child is Choice c ? HandleChildren(c.Children, delim: " | ").Parenthesize().Suffix("?", when: c.Optional) : child is Sequence s ? HandleChildren(s.Children).Parenthesize() : child is Field f ? HandleField(f).Suffix("?", when: f.IsOptional) : throw new InvalidOperationException())); private static Production HandleField(Field field) // 'bool' fields are for a few properties we generate on DirectiveTrivia. They're not // relevant to the grammar, so we just return an empty production to ignore them. => field.Type == "bool" ? new Production("") : field.Type == "CSharpSyntaxNode" ? RuleReference(field.Kinds.Single().Name + "Syntax") : field.Type.StartsWith("SeparatedSyntaxList") ? HandleSeparatedList(field, field.Type[("SeparatedSyntaxList".Length + 1)..^1]) : field.Type.StartsWith("SyntaxList") ? HandleList(field, field.Type[("SyntaxList".Length + 1)..^1]) : field.IsToken ? HandleTokenField(field) : RuleReference(field.Type); private static Production HandleSeparatedList(Field field, string elementType) => RuleReference(elementType).Suffix(" (',' " + RuleReference(elementType) + ")") .Suffix("*", when: field.MinCount < 2).Suffix("+", when: field.MinCount >= 2) .Suffix(" ','?", when: field.AllowTrailingSeparator) .Parenthesize(when: field.MinCount == 0).Suffix("?", when: field.MinCount == 0); private static Production HandleList(Field field, string elementType) => (elementType != "SyntaxToken" ? RuleReference(elementType) : field.Name == "Commas" ? new Production("','") : field.Name == "Modifiers" ? RuleReference("Modifier") : field.Name == "TextTokens" ? RuleReference(nameof(SyntaxKind.XmlTextLiteralToken)) : RuleReference(elementType)) .Suffix(field.MinCount == 0 ? "*" : "+"); private static Production HandleTokenField(Field field) => field.Kinds.Count == 0 ? HandleTokenName(field.Name) : Join(" | ", field.Kinds.Select(k => HandleTokenName(k.Name))).Parenthesize(when: field.Kinds.Count >= 2); private static Production HandleTokenName(string tokenName) => GetSyntaxKind(tokenName) is var kind && kind == SyntaxKind.None ? RuleReference("SyntaxToken") : SyntaxFacts.GetText(kind) is var text && text != "" ? new Production(text == "'" ? "'\\''" : $"'{text}'") : tokenName.StartsWith("EndOf") ? new Production("") : tokenName.StartsWith("Omitted") ? new Production("/* epsilon */") : RuleReference(tokenName); private static SyntaxKind GetSyntaxKind(string name) => GetMembers<SyntaxKind>().Where(k => k.ToString() == name).SingleOrDefault(); private static IEnumerable<TEnum> GetMembers<TEnum>() where TEnum : struct, Enum => (IEnumerable<TEnum>)Enum.GetValues(typeof(TEnum)); private static Production RuleReference(string name) => new Production( s_normalizationRegex.Replace(name.EndsWith("Syntax") ? name[..^"Syntax".Length] : name, "_").ToLower(), ImmutableArray.Create(name)); // Converts a PascalCased name into snake_cased name. private static readonly Regex s_normalizationRegex = new Regex( "(?<=[A-Z])(?=[A-Z][a-z]) | (?<=[^A-Z])(?=[A-Z]) | (?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled); } internal struct Production : IComparable<Production> { public readonly string Text; public readonly ImmutableArray<string> ReferencedRules; public Production(string text, IEnumerable<string> referencedRules = null) { Text = text; ReferencedRules = referencedRules?.ToImmutableArray() ?? ImmutableArray<string>.Empty; } public override string ToString() => Text; public int CompareTo(Production other) => StringComparer.Ordinal.Compare(this.Text, other.Text); public Production Prefix(string prefix) => new Production(prefix + this, ReferencedRules); public Production Suffix(string suffix, bool when = true) => when ? new Production(this + suffix, ReferencedRules) : this; public Production Parenthesize(bool when = true) => when ? Prefix("(").Suffix(")") : this; } } namespace Microsoft.CodeAnalysis { internal static class GreenNode { internal const int ListKind = 1; // See SyntaxKind. } } #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. #nullable disable // We only support grammar generation in the command line version for now which is the netcoreapp target #if NETCOREAPP using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.CSharp; namespace CSharpSyntaxGenerator.Grammar { internal static class GrammarGenerator { public static string Run(List<TreeType> types) { // Syntax.xml refers to a special pseudo-element 'Modifier'. Synthesize that for the grammar. var modifiers = GetMembers<DeclarationModifiers>() .Select(m => m + "Keyword").Where(n => GetSyntaxKind(n) != SyntaxKind.None) .Select(n => new Kind { Name = n }).ToList(); types.Add(new Node { Name = "Modifier", Children = { new Field { Type = "SyntaxToken", Kinds = modifiers } } }); var rules = types.ToDictionary(n => n.Name, _ => new List<Production>()); foreach (var type in types) { if (type.Base != null && rules.TryGetValue(type.Base, out var productions)) productions.Add(RuleReference(type.Name)); if (type is Node && type.Children.Count > 0) { // Convert rules like `a: (x | y) ...` into: // a: x ... // | y ...; if (type.Children[0] is Field field && field.Kinds.Count > 0) { foreach (var kind in field.Kinds) { field.Kinds = new List<Kind> { kind }; rules[type.Name].Add(HandleChildren(type.Children)); } } else { rules[type.Name].Add(HandleChildren(type.Children)); } } } // The grammar will bottom out with certain lexical productions. Create rules for these. var lexicalRules = rules.Values.SelectMany(ps => ps).SelectMany(p => p.ReferencedRules) .Where(r => !rules.TryGetValue(r, out var productions) || productions.Count == 0).ToArray(); foreach (var name in lexicalRules) rules[name] = new List<Production> { new Production("/* see lexical specification */") }; var seen = new HashSet<string>(); // Define a few major sections to help keep the grammar file naturally grouped. var majorRules = ImmutableArray.Create( "CompilationUnitSyntax", "MemberDeclarationSyntax", "TypeSyntax", "StatementSyntax", "ExpressionSyntax", "XmlNodeSyntax", "StructuredTriviaSyntax"); var result = "// <auto-generated />" + Environment.NewLine + "grammar csharp;" + Environment.NewLine; // Handle each major section first and then walk any rules not hit transitively from them. foreach (var rule in majorRules.Concat(rules.Keys.OrderBy(a => a))) processRule(rule, ref result); return result; void processRule(string name, ref string result) { if (name != "CSharpSyntaxNode" && seen.Add(name)) { // Order the productions to keep us independent from whatever changes happen in Syntax.xml. var sorted = rules[name].OrderBy(v => v); result += Environment.NewLine + RuleReference(name).Text + Environment.NewLine + " : " + string.Join(Environment.NewLine + " | ", sorted) + Environment.NewLine + " ;" + Environment.NewLine; // Now proceed in depth-first fashion through the referenced rules to keep related rules // close by. Don't recurse into major-sections to help keep them separated in grammar file. foreach (var production in sorted) foreach (var referencedRule in production.ReferencedRules) if (!majorRules.Concat(lexicalRules).Contains(referencedRule)) processRule(referencedRule, ref result); } } } private static Production Join(string delim, IEnumerable<Production> productions) => new Production(string.Join(delim, productions.Where(p => p.Text.Length > 0)), productions.SelectMany(p => p.ReferencedRules)); private static Production HandleChildren(IEnumerable<TreeTypeChild> children, string delim = " ") => Join(delim, children.Select(child => child is Choice c ? HandleChildren(c.Children, delim: " | ").Parenthesize().Suffix("?", when: c.Optional) : child is Sequence s ? HandleChildren(s.Children).Parenthesize() : child is Field f ? HandleField(f).Suffix("?", when: f.IsOptional) : throw new InvalidOperationException())); private static Production HandleField(Field field) // 'bool' fields are for a few properties we generate on DirectiveTrivia. They're not // relevant to the grammar, so we just return an empty production to ignore them. => field.Type == "bool" ? new Production("") : field.Type == "CSharpSyntaxNode" ? RuleReference(field.Kinds.Single().Name + "Syntax") : field.Type.StartsWith("SeparatedSyntaxList") ? HandleSeparatedList(field, field.Type[("SeparatedSyntaxList".Length + 1)..^1]) : field.Type.StartsWith("SyntaxList") ? HandleList(field, field.Type[("SyntaxList".Length + 1)..^1]) : field.IsToken ? HandleTokenField(field) : RuleReference(field.Type); private static Production HandleSeparatedList(Field field, string elementType) => RuleReference(elementType).Suffix(" (',' " + RuleReference(elementType) + ")") .Suffix("*", when: field.MinCount < 2).Suffix("+", when: field.MinCount >= 2) .Suffix(" ','?", when: field.AllowTrailingSeparator) .Parenthesize(when: field.MinCount == 0).Suffix("?", when: field.MinCount == 0); private static Production HandleList(Field field, string elementType) => (elementType != "SyntaxToken" ? RuleReference(elementType) : field.Name == "Commas" ? new Production("','") : field.Name == "Modifiers" ? RuleReference("Modifier") : field.Name == "TextTokens" ? RuleReference(nameof(SyntaxKind.XmlTextLiteralToken)) : RuleReference(elementType)) .Suffix(field.MinCount == 0 ? "*" : "+"); private static Production HandleTokenField(Field field) => field.Kinds.Count == 0 ? HandleTokenName(field.Name) : Join(" | ", field.Kinds.Select(k => HandleTokenName(k.Name))).Parenthesize(when: field.Kinds.Count >= 2); private static Production HandleTokenName(string tokenName) => GetSyntaxKind(tokenName) is var kind && kind == SyntaxKind.None ? RuleReference("SyntaxToken") : SyntaxFacts.GetText(kind) is var text && text != "" ? new Production(text == "'" ? "'\\''" : $"'{text}'") : tokenName.StartsWith("EndOf") ? new Production("") : tokenName.StartsWith("Omitted") ? new Production("/* epsilon */") : RuleReference(tokenName); private static SyntaxKind GetSyntaxKind(string name) => GetMembers<SyntaxKind>().Where(k => k.ToString() == name).SingleOrDefault(); private static IEnumerable<TEnum> GetMembers<TEnum>() where TEnum : struct, Enum => (IEnumerable<TEnum>)Enum.GetValues(typeof(TEnum)); private static Production RuleReference(string name) => new Production( s_normalizationRegex.Replace(name.EndsWith("Syntax") ? name[..^"Syntax".Length] : name, "_").ToLower(), ImmutableArray.Create(name)); // Converts a PascalCased name into snake_cased name. private static readonly Regex s_normalizationRegex = new Regex( "(?<=[A-Z])(?=[A-Z][a-z]) | (?<=[^A-Z])(?=[A-Z]) | (?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled); } internal struct Production : IComparable<Production> { public readonly string Text; public readonly ImmutableArray<string> ReferencedRules; public Production(string text, IEnumerable<string> referencedRules = null) { Text = text; ReferencedRules = referencedRules?.ToImmutableArray() ?? ImmutableArray<string>.Empty; } public override string ToString() => Text; public int CompareTo(Production other) => StringComparer.Ordinal.Compare(this.Text, other.Text); public Production Prefix(string prefix) => new Production(prefix + this, ReferencedRules); public Production Suffix(string suffix, bool when = true) => when ? new Production(this + suffix, ReferencedRules) : this; public Production Parenthesize(bool when = true) => when ? Prefix("(").Suffix(")") : this; } } namespace Microsoft.CodeAnalysis { internal static class GreenNode { internal const int ListKind = 1; // See SyntaxKind. } } #endif
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/Xaml/Impl/Telemetry/IXamlLanguageServerFeedbackService.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Telemetry { /// <summary> /// Service that collects data for Telemetry in XamlLanguageServer /// </summary> internal interface IXamlLanguageServerFeedbackService { /// <summary> /// Create a RequestScope of a request of given documentId /// </summary> IRequestScope CreateRequestScope(DocumentId? documentId, string methodName); } }
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Telemetry { /// <summary> /// Service that collects data for Telemetry in XamlLanguageServer /// </summary> internal interface IXamlLanguageServerFeedbackService { /// <summary> /// Create a RequestScope of a request of given documentId /// </summary> IRequestScope CreateRequestScope(DocumentId? documentId, string methodName); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/Model/TreeType.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Xml.Serialization; namespace CSharpSyntaxGenerator { public class TreeType { [XmlAttribute] public string Name; [XmlAttribute] public string Base; [XmlAttribute] public string SkipConvenienceFactories; [XmlElement] public Comment TypeComment; [XmlElement] public Comment FactoryComment; [XmlElement(ElementName = "Field", Type = typeof(Field))] [XmlElement(ElementName = "Choice", Type = typeof(Choice))] [XmlElement(ElementName = "Sequence", Type = typeof(Sequence))] public List<TreeTypeChild> Children = new List<TreeTypeChild>(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Xml.Serialization; namespace CSharpSyntaxGenerator { public class TreeType { [XmlAttribute] public string Name; [XmlAttribute] public string Base; [XmlAttribute] public string SkipConvenienceFactories; [XmlElement] public Comment TypeComment; [XmlElement] public Comment FactoryComment; [XmlElement(ElementName = "Field", Type = typeof(Field))] [XmlElement(ElementName = "Choice", Type = typeof(Choice))] [XmlElement(ElementName = "Sequence", Type = typeof(Sequence))] public List<TreeTypeChild> Children = new List<TreeTypeChild>(); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/Core/Portable/RQName/Nodes/RQRefParameter.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQRefParameter : RQParameter { public RQRefParameter(RQType type) : base(type) { } public override SimpleTreeNode CreateSimpleTreeForType() => new SimpleGroupNode(RQNameStrings.ParamMod, new SimpleLeafNode(RQNameStrings.Ref), Type.ToSimpleTree()); } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQRefParameter : RQParameter { public RQRefParameter(RQType type) : base(type) { } public override SimpleTreeNode CreateSimpleTreeForType() => new SimpleGroupNode(RQNameStrings.ParamMod, new SimpleLeafNode(RQNameStrings.Ref), Type.ToSimpleTree()); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/IntegrationTest/TestUtilities/Interop/NativeMethods.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using System.Text; using Microsoft.VisualStudio.OLE.Interop; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Interop { internal static class NativeMethods { private const string Kernel32 = "kernel32.dll"; private const string Ole32 = "ole32.dll"; private const string User32 = "User32.dll"; #region kernel32.dll [DllImport(Kernel32)] public static extern uint GetCurrentThreadId(); [DllImport(Kernel32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool AllocConsole(); [DllImport(Kernel32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool FreeConsole(); [DllImport(Kernel32, SetLastError = false)] public static extern IntPtr GetConsoleWindow(); #endregion #region ole32.dll [DllImport(Ole32, PreserveSig = false)] public static extern void CreateBindCtx(int reserved, [MarshalAs(UnmanagedType.Interface)] out IBindCtx bindContext); [DllImport(Ole32, PreserveSig = false)] public static extern void GetRunningObjectTable(int reserved, [MarshalAs(UnmanagedType.Interface)] out IRunningObjectTable runningObjectTable); #endregion #region user32.dll public static readonly int SizeOf_INPUT = Marshal.SizeOf<INPUT>(); public const uint GA_PARENT = 1; public const uint GA_ROOT = 2; public const uint GA_ROOTOWNER = 3; public const uint GW_HWNDFIRST = 0; public const uint GW_HWNDLAST = 1; public const uint GW_HWNDNEXT = 2; public const uint GW_HWNDPREV = 3; public const uint GW_OWNER = 4; public const uint GW_CHILD = 5; public const uint GW_ENABLEDPOPUP = 6; public const uint INPUT_MOUSE = 0; public const uint INPUT_KEYBOARD = 1; public const uint INPUT_HARDWARE = 2; public const uint KEYEVENTF_NONE = 0x0000; public const uint KEYEVENTF_EXTENDEDKEY = 0x0001; public const uint KEYEVENTF_KEYUP = 0x0002; public const uint KEYEVENTF_UNICODE = 0x0004; public const uint KEYEVENTF_SCANCODE = 0x0008; public const uint WM_GETTEXT = 0x000D; public const uint WM_GETTEXTLENGTH = 0x000E; [StructLayout(LayoutKind.Sequential)] public struct INPUT { public uint Type; public InputUnion Input; } [StructLayout(LayoutKind.Explicit)] public struct InputUnion { [FieldOffset(0)] public MOUSEINPUT mi; [FieldOffset(0)] public KEYBDINPUT ki; [FieldOffset(0)] public HARDWAREINPUT hi; } [StructLayout(LayoutKind.Sequential)] public struct HARDWAREINPUT { public uint uMsg; public ushort wParamL; public ushort wParamH; } [StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; } [StructLayout(LayoutKind.Sequential)] public struct MOUSEINPUT { public int dx; public int dy; public uint mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; } [UnmanagedFunctionPointer(CallingConvention.Winapi, SetLastError = false)] [return: MarshalAs(UnmanagedType.Bool)] public delegate bool WNDENUMPROC(IntPtr hWnd, IntPtr lParam); [DllImport(User32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool EnumWindows([MarshalAs(UnmanagedType.FunctionPtr)] WNDENUMPROC lpEnumFunc, IntPtr lParam); [DllImport(User32)] public static extern IntPtr GetAncestor(IntPtr hWnd, uint gaFlags); [DllImport(User32)] public static extern IntPtr GetDesktopWindow(); [DllImport(User32)] public static extern IntPtr GetForegroundWindow(); [DllImport(User32, SetLastError = true)] public static extern IntPtr GetParent(IntPtr hWnd); [DllImport(User32, SetLastError = true)] public static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd); [DllImport(User32)] public static extern IntPtr GetWindowDC(IntPtr hWnd); [DllImport(User32)] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, [Optional] IntPtr lpdwProcessId); [DllImport(User32)] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, [Optional] out uint lpdwProcessId); [DllImport(User32, SetLastError = true)] public static extern uint SendInput(uint nInputs, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] INPUT[] pInputs, int cbSize); [DllImport(User32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern IntPtr SendMessage(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam); [DllImport(User32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern IntPtr SendMessage(IntPtr hWnd, uint uMsg, IntPtr wParam, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder lParam); [DllImport(User32, SetLastError = false)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport(User32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags); public const uint SWP_NOZORDER = 4; [DllImport(User32, SetLastError = true)] public static extern IntPtr GetLastActivePopup(IntPtr hWnd); [DllImport(User32, SetLastError = true)] public static extern void SwitchToThisWindow(IntPtr hWnd, [MarshalAs(UnmanagedType.Bool)] bool fUnknown); [DllImport(User32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsWindowVisible(IntPtr hWnd); [DllImport(User32, CharSet = CharSet.Unicode)] public static extern short VkKeyScan(char ch); public const uint MAPVK_VK_TO_VSC = 0; public const uint MAPVK_VSC_TO_VK = 1; public const uint MAPVK_VK_TO_CHAR = 2; public const uint MAPVK_VSC_TO_KV_EX = 3; [DllImport(User32, CharSet = CharSet.Unicode)] public static extern uint MapVirtualKey(uint uCode, uint uMapType); [DllImport(User32)] public static extern IntPtr GetMessageExtraInfo(); #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.Runtime.InteropServices; using System.Text; using Microsoft.VisualStudio.OLE.Interop; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Interop { internal static class NativeMethods { private const string Kernel32 = "kernel32.dll"; private const string Ole32 = "ole32.dll"; private const string User32 = "User32.dll"; #region kernel32.dll [DllImport(Kernel32)] public static extern uint GetCurrentThreadId(); [DllImport(Kernel32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool AllocConsole(); [DllImport(Kernel32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool FreeConsole(); [DllImport(Kernel32, SetLastError = false)] public static extern IntPtr GetConsoleWindow(); #endregion #region ole32.dll [DllImport(Ole32, PreserveSig = false)] public static extern void CreateBindCtx(int reserved, [MarshalAs(UnmanagedType.Interface)] out IBindCtx bindContext); [DllImport(Ole32, PreserveSig = false)] public static extern void GetRunningObjectTable(int reserved, [MarshalAs(UnmanagedType.Interface)] out IRunningObjectTable runningObjectTable); #endregion #region user32.dll public static readonly int SizeOf_INPUT = Marshal.SizeOf<INPUT>(); public const uint GA_PARENT = 1; public const uint GA_ROOT = 2; public const uint GA_ROOTOWNER = 3; public const uint GW_HWNDFIRST = 0; public const uint GW_HWNDLAST = 1; public const uint GW_HWNDNEXT = 2; public const uint GW_HWNDPREV = 3; public const uint GW_OWNER = 4; public const uint GW_CHILD = 5; public const uint GW_ENABLEDPOPUP = 6; public const uint INPUT_MOUSE = 0; public const uint INPUT_KEYBOARD = 1; public const uint INPUT_HARDWARE = 2; public const uint KEYEVENTF_NONE = 0x0000; public const uint KEYEVENTF_EXTENDEDKEY = 0x0001; public const uint KEYEVENTF_KEYUP = 0x0002; public const uint KEYEVENTF_UNICODE = 0x0004; public const uint KEYEVENTF_SCANCODE = 0x0008; public const uint WM_GETTEXT = 0x000D; public const uint WM_GETTEXTLENGTH = 0x000E; [StructLayout(LayoutKind.Sequential)] public struct INPUT { public uint Type; public InputUnion Input; } [StructLayout(LayoutKind.Explicit)] public struct InputUnion { [FieldOffset(0)] public MOUSEINPUT mi; [FieldOffset(0)] public KEYBDINPUT ki; [FieldOffset(0)] public HARDWAREINPUT hi; } [StructLayout(LayoutKind.Sequential)] public struct HARDWAREINPUT { public uint uMsg; public ushort wParamL; public ushort wParamH; } [StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; } [StructLayout(LayoutKind.Sequential)] public struct MOUSEINPUT { public int dx; public int dy; public uint mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; } [UnmanagedFunctionPointer(CallingConvention.Winapi, SetLastError = false)] [return: MarshalAs(UnmanagedType.Bool)] public delegate bool WNDENUMPROC(IntPtr hWnd, IntPtr lParam); [DllImport(User32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool EnumWindows([MarshalAs(UnmanagedType.FunctionPtr)] WNDENUMPROC lpEnumFunc, IntPtr lParam); [DllImport(User32)] public static extern IntPtr GetAncestor(IntPtr hWnd, uint gaFlags); [DllImport(User32)] public static extern IntPtr GetDesktopWindow(); [DllImport(User32)] public static extern IntPtr GetForegroundWindow(); [DllImport(User32, SetLastError = true)] public static extern IntPtr GetParent(IntPtr hWnd); [DllImport(User32, SetLastError = true)] public static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd); [DllImport(User32)] public static extern IntPtr GetWindowDC(IntPtr hWnd); [DllImport(User32)] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, [Optional] IntPtr lpdwProcessId); [DllImport(User32)] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, [Optional] out uint lpdwProcessId); [DllImport(User32, SetLastError = true)] public static extern uint SendInput(uint nInputs, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] INPUT[] pInputs, int cbSize); [DllImport(User32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern IntPtr SendMessage(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam); [DllImport(User32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern IntPtr SendMessage(IntPtr hWnd, uint uMsg, IntPtr wParam, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder lParam); [DllImport(User32, SetLastError = false)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport(User32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags); public const uint SWP_NOZORDER = 4; [DllImport(User32, SetLastError = true)] public static extern IntPtr GetLastActivePopup(IntPtr hWnd); [DllImport(User32, SetLastError = true)] public static extern void SwitchToThisWindow(IntPtr hWnd, [MarshalAs(UnmanagedType.Bool)] bool fUnknown); [DllImport(User32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsWindowVisible(IntPtr hWnd); [DllImport(User32, CharSet = CharSet.Unicode)] public static extern short VkKeyScan(char ch); public const uint MAPVK_VK_TO_VSC = 0; public const uint MAPVK_VSC_TO_VK = 1; public const uint MAPVK_VK_TO_CHAR = 2; public const uint MAPVK_VSC_TO_KV_EX = 3; [DllImport(User32, CharSet = CharSet.Unicode)] public static extern uint MapVirtualKey(uint uCode, uint uMapType); [DllImport(User32)] public static extern IntPtr GetMessageExtraInfo(); #endregion } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/VisualStudio/Core/Def/Implementation/Options/RoamingVisualStudioProfileOptionPersister.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Xml.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Setup; using Microsoft.VisualStudio.Settings; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { /// <summary> /// Serializes settings marked with <see cref="RoamingProfileStorageLocation"/> to and from the user's roaming profile. /// </summary> internal sealed class RoamingVisualStudioProfileOptionPersister : ForegroundThreadAffinitizedObject, IOptionPersister { // NOTE: This service is not public or intended for use by teams/individuals outside of Microsoft. Any data stored is subject to deletion without warning. [Guid("9B164E40-C3A2-4363-9BC5-EB4039DEF653")] private class SVsSettingsPersistenceManager { }; private readonly ISettingsManager? _settingManager; private readonly IGlobalOptionService _globalOptionService; /// <summary> /// The list of options that have been been fetched from <see cref="_settingManager"/>, by key. We track this so /// if a later change happens, we know to refresh that value. This is synchronized with monitor locks on /// <see cref="_optionsToMonitorForChangesGate" />. /// </summary> private readonly Dictionary<string, List<OptionKey>> _optionsToMonitorForChanges = new(); private readonly object _optionsToMonitorForChangesGate = new(); /// <remarks> /// We make sure this code is from the UI by asking for all <see cref="IOptionPersister"/> in <see cref="RoslynPackage.InitializeAsync"/> /// </remarks> public RoamingVisualStudioProfileOptionPersister(IThreadingContext threadingContext, IGlobalOptionService globalOptionService, ISettingsManager? settingsManager) : base(threadingContext, assertIsForeground: true) { Contract.ThrowIfNull(globalOptionService); _settingManager = settingsManager; _globalOptionService = globalOptionService; // While the settings persistence service should be available in all SKUs it is possible an ISO shell author has undefined the // contributing package. In that case persistence of settings won't work (we don't bother with a backup solution for persistence // as the scenario seems exceedingly unlikely), but we shouldn't crash the IDE. if (_settingManager != null) { var settingsSubset = _settingManager.GetSubset("*"); settingsSubset.SettingChangedAsync += OnSettingChangedAsync; } } private System.Threading.Tasks.Task OnSettingChangedAsync(object sender, PropertyChangedEventArgs args) { List<OptionKey>? optionsToRefresh = null; lock (_optionsToMonitorForChangesGate) { if (_optionsToMonitorForChanges.TryGetValue(args.PropertyName, out var optionsToRefreshInsideLock)) { // Make a copy of the list so we aren't using something that might mutate underneath us. optionsToRefresh = optionsToRefreshInsideLock.ToList(); } } if (optionsToRefresh != null) { // Refresh the actual options outside of our _optionsToMonitorForChangesGate so we avoid any deadlocks by calling back // into the global option service under our lock. There isn't some race here where if we were fetching an option for the first time // while the setting was changed we might not refresh it. Why? We call RecordObservedValueToWatchForChanges before we fetch the value // and since this event is raised after the setting is modified, any new setting would have already been observed in GetFirstOrDefaultValue. // And if it wasn't, this event will then refresh it. foreach (var optionToRefresh in optionsToRefresh) { if (TryFetch(optionToRefresh, out var optionValue)) { _globalOptionService.RefreshOption(optionToRefresh, optionValue); } } } return System.Threading.Tasks.Task.CompletedTask; } private object? GetFirstOrDefaultValue(OptionKey optionKey, IEnumerable<RoamingProfileStorageLocation> roamingSerializations) { Contract.ThrowIfNull(_settingManager); // There can be more than 1 roaming location in the order of their priority. // When fetching a value, we iterate all of them until we find the first one that exists. // When persisting a value, we always use the first location. // This functionality exists for breaking changes to persistence of some options. In such a case, there // will be a new location added to the beginning with a new name. When fetching a value, we might find the old // location (and can upgrade the value accordingly) but we only write to the new location so that // we don't interfere with older versions. This will essentially "fork" the user's options at the time of upgrade. foreach (var roamingSerialization in roamingSerializations) { var storageKey = roamingSerialization.GetKeyNameForLanguage(optionKey.Language); RecordObservedValueToWatchForChanges(optionKey, storageKey); if (_settingManager.TryGetValue(storageKey, out object value) == GetValueResult.Success) { return value; } } return optionKey.Option.DefaultValue; } public bool TryFetch(OptionKey optionKey, out object? value) { if (_settingManager == null) { Debug.Fail("Manager field is unexpectedly null."); value = null; return false; } // Do we roam this at all? var roamingSerializations = optionKey.Option.StorageLocations.OfType<RoamingProfileStorageLocation>(); if (!roamingSerializations.Any()) { value = null; return false; } value = GetFirstOrDefaultValue(optionKey, roamingSerializations); // VS's ISettingsManager has some quirks around storing enums. Specifically, // it *can* persist and retrieve enums, but only if you properly call // GetValueOrDefault<EnumType>. This is because it actually stores enums just // as ints and depends on the type parameter passed in to convert the integral // value back to an enum value. Unfortunately, we call GetValueOrDefault<object> // and so we get the value back as boxed integer. // // Because of that, manually convert the integer to an enum here so we don't // crash later trying to cast a boxed integer to an enum value. if (optionKey.Option.Type.IsEnum) { if (value != null) { value = Enum.ToObject(optionKey.Option.Type, value); } } else if (typeof(ICodeStyleOption).IsAssignableFrom(optionKey.Option.Type)) { return DeserializeCodeStyleOption(ref value, optionKey.Option.Type); } else if (optionKey.Option.Type == typeof(NamingStylePreferences)) { // We store these as strings, so deserialize if (value is string serializedValue) { try { value = NamingStylePreferences.FromXElement(XElement.Parse(serializedValue)); } catch (Exception) { value = null; return false; } } else { value = null; return false; } } else if (optionKey.Option.Type == typeof(bool) && value is int intValue) { // TypeScript used to store some booleans as integers. We now handle them properly for legacy sync scenarios. value = intValue != 0; return true; } else if (optionKey.Option.Type == typeof(bool) && value is long longValue) { // TypeScript used to store some booleans as integers. We now handle them properly for legacy sync scenarios. value = longValue != 0; return true; } else if (optionKey.Option.Type == typeof(bool?)) { // code uses object to hold onto any value which will use boxing on value types. // see boxing on nullable types - https://msdn.microsoft.com/en-us/library/ms228597.aspx return (value is bool) || (value == null); } else if (value != null && optionKey.Option.Type != value.GetType()) { // We got something back different than we expected, so fail to deserialize value = null; return false; } return true; } private bool DeserializeCodeStyleOption(ref object? value, Type type) { if (value is string serializedValue) { try { var fromXElement = type.GetMethod(nameof(CodeStyleOption<object>.FromXElement), BindingFlags.Public | BindingFlags.Static); value = fromXElement.Invoke(null, new object[] { XElement.Parse(serializedValue) }); return true; } catch (Exception) { } } value = null; return false; } private void RecordObservedValueToWatchForChanges(OptionKey optionKey, string storageKey) { // We're about to fetch the value, so make sure that if it changes we'll know about it lock (_optionsToMonitorForChangesGate) { var optionKeysToMonitor = _optionsToMonitorForChanges.GetOrAdd(storageKey, _ => new List<OptionKey>()); if (!optionKeysToMonitor.Contains(optionKey)) { optionKeysToMonitor.Add(optionKey); } } } public bool TryPersist(OptionKey optionKey, object? value) { if (_settingManager == null) { Debug.Fail("Manager field is unexpectedly null."); return false; } // Do we roam this at all? var roamingSerialization = optionKey.Option.StorageLocations.OfType<RoamingProfileStorageLocation>().FirstOrDefault(); if (roamingSerialization == null) { return false; } var storageKey = roamingSerialization.GetKeyNameForLanguage(optionKey.Language); RecordObservedValueToWatchForChanges(optionKey, storageKey); if (value is ICodeStyleOption codeStyleOption) { // We store these as strings, so serialize value = codeStyleOption.ToXElement().ToString(); } else if (optionKey.Option.Type == typeof(NamingStylePreferences)) { // We store these as strings, so serialize if (value is NamingStylePreferences valueToSerialize) { value = valueToSerialize.CreateXElement().ToString(); } } _settingManager.SetValueAsync(storageKey, value, isMachineLocal: false); return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Xml.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Setup; using Microsoft.VisualStudio.Settings; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { /// <summary> /// Serializes settings marked with <see cref="RoamingProfileStorageLocation"/> to and from the user's roaming profile. /// </summary> internal sealed class RoamingVisualStudioProfileOptionPersister : ForegroundThreadAffinitizedObject, IOptionPersister { // NOTE: This service is not public or intended for use by teams/individuals outside of Microsoft. Any data stored is subject to deletion without warning. [Guid("9B164E40-C3A2-4363-9BC5-EB4039DEF653")] private class SVsSettingsPersistenceManager { }; private readonly ISettingsManager? _settingManager; private readonly IGlobalOptionService _globalOptionService; /// <summary> /// The list of options that have been been fetched from <see cref="_settingManager"/>, by key. We track this so /// if a later change happens, we know to refresh that value. This is synchronized with monitor locks on /// <see cref="_optionsToMonitorForChangesGate" />. /// </summary> private readonly Dictionary<string, List<OptionKey>> _optionsToMonitorForChanges = new(); private readonly object _optionsToMonitorForChangesGate = new(); /// <remarks> /// We make sure this code is from the UI by asking for all <see cref="IOptionPersister"/> in <see cref="RoslynPackage.InitializeAsync"/> /// </remarks> public RoamingVisualStudioProfileOptionPersister(IThreadingContext threadingContext, IGlobalOptionService globalOptionService, ISettingsManager? settingsManager) : base(threadingContext, assertIsForeground: true) { Contract.ThrowIfNull(globalOptionService); _settingManager = settingsManager; _globalOptionService = globalOptionService; // While the settings persistence service should be available in all SKUs it is possible an ISO shell author has undefined the // contributing package. In that case persistence of settings won't work (we don't bother with a backup solution for persistence // as the scenario seems exceedingly unlikely), but we shouldn't crash the IDE. if (_settingManager != null) { var settingsSubset = _settingManager.GetSubset("*"); settingsSubset.SettingChangedAsync += OnSettingChangedAsync; } } private System.Threading.Tasks.Task OnSettingChangedAsync(object sender, PropertyChangedEventArgs args) { List<OptionKey>? optionsToRefresh = null; lock (_optionsToMonitorForChangesGate) { if (_optionsToMonitorForChanges.TryGetValue(args.PropertyName, out var optionsToRefreshInsideLock)) { // Make a copy of the list so we aren't using something that might mutate underneath us. optionsToRefresh = optionsToRefreshInsideLock.ToList(); } } if (optionsToRefresh != null) { // Refresh the actual options outside of our _optionsToMonitorForChangesGate so we avoid any deadlocks by calling back // into the global option service under our lock. There isn't some race here where if we were fetching an option for the first time // while the setting was changed we might not refresh it. Why? We call RecordObservedValueToWatchForChanges before we fetch the value // and since this event is raised after the setting is modified, any new setting would have already been observed in GetFirstOrDefaultValue. // And if it wasn't, this event will then refresh it. foreach (var optionToRefresh in optionsToRefresh) { if (TryFetch(optionToRefresh, out var optionValue)) { _globalOptionService.RefreshOption(optionToRefresh, optionValue); } } } return System.Threading.Tasks.Task.CompletedTask; } private object? GetFirstOrDefaultValue(OptionKey optionKey, IEnumerable<RoamingProfileStorageLocation> roamingSerializations) { Contract.ThrowIfNull(_settingManager); // There can be more than 1 roaming location in the order of their priority. // When fetching a value, we iterate all of them until we find the first one that exists. // When persisting a value, we always use the first location. // This functionality exists for breaking changes to persistence of some options. In such a case, there // will be a new location added to the beginning with a new name. When fetching a value, we might find the old // location (and can upgrade the value accordingly) but we only write to the new location so that // we don't interfere with older versions. This will essentially "fork" the user's options at the time of upgrade. foreach (var roamingSerialization in roamingSerializations) { var storageKey = roamingSerialization.GetKeyNameForLanguage(optionKey.Language); RecordObservedValueToWatchForChanges(optionKey, storageKey); if (_settingManager.TryGetValue(storageKey, out object value) == GetValueResult.Success) { return value; } } return optionKey.Option.DefaultValue; } public bool TryFetch(OptionKey optionKey, out object? value) { if (_settingManager == null) { Debug.Fail("Manager field is unexpectedly null."); value = null; return false; } // Do we roam this at all? var roamingSerializations = optionKey.Option.StorageLocations.OfType<RoamingProfileStorageLocation>(); if (!roamingSerializations.Any()) { value = null; return false; } value = GetFirstOrDefaultValue(optionKey, roamingSerializations); // VS's ISettingsManager has some quirks around storing enums. Specifically, // it *can* persist and retrieve enums, but only if you properly call // GetValueOrDefault<EnumType>. This is because it actually stores enums just // as ints and depends on the type parameter passed in to convert the integral // value back to an enum value. Unfortunately, we call GetValueOrDefault<object> // and so we get the value back as boxed integer. // // Because of that, manually convert the integer to an enum here so we don't // crash later trying to cast a boxed integer to an enum value. if (optionKey.Option.Type.IsEnum) { if (value != null) { value = Enum.ToObject(optionKey.Option.Type, value); } } else if (typeof(ICodeStyleOption).IsAssignableFrom(optionKey.Option.Type)) { return DeserializeCodeStyleOption(ref value, optionKey.Option.Type); } else if (optionKey.Option.Type == typeof(NamingStylePreferences)) { // We store these as strings, so deserialize if (value is string serializedValue) { try { value = NamingStylePreferences.FromXElement(XElement.Parse(serializedValue)); } catch (Exception) { value = null; return false; } } else { value = null; return false; } } else if (optionKey.Option.Type == typeof(bool) && value is int intValue) { // TypeScript used to store some booleans as integers. We now handle them properly for legacy sync scenarios. value = intValue != 0; return true; } else if (optionKey.Option.Type == typeof(bool) && value is long longValue) { // TypeScript used to store some booleans as integers. We now handle them properly for legacy sync scenarios. value = longValue != 0; return true; } else if (optionKey.Option.Type == typeof(bool?)) { // code uses object to hold onto any value which will use boxing on value types. // see boxing on nullable types - https://msdn.microsoft.com/en-us/library/ms228597.aspx return (value is bool) || (value == null); } else if (value != null && optionKey.Option.Type != value.GetType()) { // We got something back different than we expected, so fail to deserialize value = null; return false; } return true; } private bool DeserializeCodeStyleOption(ref object? value, Type type) { if (value is string serializedValue) { try { var fromXElement = type.GetMethod(nameof(CodeStyleOption<object>.FromXElement), BindingFlags.Public | BindingFlags.Static); value = fromXElement.Invoke(null, new object[] { XElement.Parse(serializedValue) }); return true; } catch (Exception) { } } value = null; return false; } private void RecordObservedValueToWatchForChanges(OptionKey optionKey, string storageKey) { // We're about to fetch the value, so make sure that if it changes we'll know about it lock (_optionsToMonitorForChangesGate) { var optionKeysToMonitor = _optionsToMonitorForChanges.GetOrAdd(storageKey, _ => new List<OptionKey>()); if (!optionKeysToMonitor.Contains(optionKey)) { optionKeysToMonitor.Add(optionKey); } } } public bool TryPersist(OptionKey optionKey, object? value) { if (_settingManager == null) { Debug.Fail("Manager field is unexpectedly null."); return false; } // Do we roam this at all? var roamingSerialization = optionKey.Option.StorageLocations.OfType<RoamingProfileStorageLocation>().FirstOrDefault(); if (roamingSerialization == null) { return false; } var storageKey = roamingSerialization.GetKeyNameForLanguage(optionKey.Language); RecordObservedValueToWatchForChanges(optionKey, storageKey); if (value is ICodeStyleOption codeStyleOption) { // We store these as strings, so serialize value = codeStyleOption.ToXElement().ToString(); } else if (optionKey.Option.Type == typeof(NamingStylePreferences)) { // We store these as strings, so serialize if (value is NamingStylePreferences valueToSerialize) { value = valueToSerialize.CreateXElement().ToString(); } } _settingManager.SetValueAsync(storageKey, value, isMachineLocal: false); return true; } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/Core/Portable/PEWriter/TypeNameSerializer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using System.Text; using System.Diagnostics; namespace Microsoft.Cci { internal static class TypeNameSerializer { internal static string GetSerializedTypeName(this ITypeReference typeReference, EmitContext context) { bool isAssemblyQualified = true; return GetSerializedTypeName(typeReference, context, ref isAssemblyQualified); } internal static string GetSerializedTypeName(this ITypeReference typeReference, EmitContext context, ref bool isAssemblyQualified) { var pooled = PooledStringBuilder.GetInstance(); StringBuilder sb = pooled.Builder; IArrayTypeReference arrType = typeReference as IArrayTypeReference; if (arrType != null) { typeReference = arrType.GetElementType(context); bool isAssemQual = false; AppendSerializedTypeName(sb, typeReference, ref isAssemQual, context); if (arrType.IsSZArray) { sb.Append("[]"); } else { sb.Append('['); if (arrType.Rank == 1) { sb.Append('*'); } sb.Append(',', (int)arrType.Rank - 1); sb.Append(']'); } goto done; } IPointerTypeReference pointer = typeReference as IPointerTypeReference; if (pointer != null) { typeReference = pointer.GetTargetType(context); bool isAssemQual = false; AppendSerializedTypeName(sb, typeReference, ref isAssemQual, context); sb.Append('*'); goto done; } INamespaceTypeReference namespaceType = typeReference.AsNamespaceTypeReference; if (namespaceType != null) { var name = namespaceType.NamespaceName; if (name.Length != 0) { sb.Append(name); sb.Append('.'); } sb.Append(GetMangledAndEscapedName(namespaceType)); goto done; } if (typeReference.IsTypeSpecification()) { ITypeReference uninstantiatedTypeReference = typeReference.GetUninstantiatedGenericType(context); ArrayBuilder<ITypeReference> consolidatedTypeArguments = ArrayBuilder<ITypeReference>.GetInstance(); typeReference.GetConsolidatedTypeArguments(consolidatedTypeArguments, context); bool uninstantiatedTypeIsAssemblyQualified = false; sb.Append(GetSerializedTypeName(uninstantiatedTypeReference, context, ref uninstantiatedTypeIsAssemblyQualified)); sb.Append('['); bool first = true; foreach (ITypeReference argument in consolidatedTypeArguments) { if (first) { first = false; } else { sb.Append(','); } bool isAssemQual = true; AppendSerializedTypeName(sb, argument, ref isAssemQual, context); } consolidatedTypeArguments.Free(); sb.Append(']'); goto done; } INestedTypeReference nestedType = typeReference.AsNestedTypeReference; if (nestedType != null) { bool nestedTypeIsAssemblyQualified = false; sb.Append(GetSerializedTypeName(nestedType.GetContainingType(context), context, ref nestedTypeIsAssemblyQualified)); sb.Append('+'); sb.Append(GetMangledAndEscapedName(nestedType)); goto done; } // TODO: error done: if (isAssemblyQualified) { AppendAssemblyQualifierIfNecessary(sb, UnwrapTypeReference(typeReference, context), out isAssemblyQualified, context); } return pooled.ToStringAndFree(); } private static void AppendSerializedTypeName(StringBuilder sb, ITypeReference type, ref bool isAssemQualified, EmitContext context) { string argTypeName = GetSerializedTypeName(type, context, ref isAssemQualified); if (isAssemQualified) { sb.Append('['); } sb.Append(argTypeName); if (isAssemQualified) { sb.Append(']'); } } private static void AppendAssemblyQualifierIfNecessary(StringBuilder sb, ITypeReference typeReference, out bool isAssemQualified, EmitContext context) { INestedTypeReference nestedType = typeReference.AsNestedTypeReference; if (nestedType != null) { AppendAssemblyQualifierIfNecessary(sb, nestedType.GetContainingType(context), out isAssemQualified, context); return; } IGenericTypeInstanceReference genInst = typeReference.AsGenericTypeInstanceReference; if (genInst != null) { AppendAssemblyQualifierIfNecessary(sb, genInst.GetGenericType(context), out isAssemQualified, context); return; } IArrayTypeReference arrType = typeReference as IArrayTypeReference; if (arrType != null) { AppendAssemblyQualifierIfNecessary(sb, arrType.GetElementType(context), out isAssemQualified, context); return; } IPointerTypeReference pointer = typeReference as IPointerTypeReference; if (pointer != null) { AppendAssemblyQualifierIfNecessary(sb, pointer.GetTargetType(context), out isAssemQualified, context); return; } isAssemQualified = false; IAssemblyReference referencedAssembly = null; INamespaceTypeReference namespaceType = typeReference.AsNamespaceTypeReference; if (namespaceType != null) { referencedAssembly = namespaceType.GetUnit(context) as IAssemblyReference; } if (referencedAssembly != null) { var containingAssembly = context.Module.GetContainingAssembly(context); if (containingAssembly == null || !ReferenceEquals(referencedAssembly, containingAssembly)) { sb.Append(", "); sb.Append(MetadataWriter.StrongName(referencedAssembly)); isAssemQualified = true; } } } private static string GetMangledAndEscapedName(INamedTypeReference namedType) { var pooled = PooledStringBuilder.GetInstance(); StringBuilder mangledName = pooled.Builder; const string needsEscaping = "\\[]*.+,& "; foreach (var ch in namedType.Name) { if (needsEscaping.IndexOf(ch) >= 0) { mangledName.Append('\\'); } mangledName.Append(ch); } if (namedType.MangleName && namedType.GenericParameterCount > 0) { mangledName.Append(MetadataHelpers.GetAritySuffix(namedType.GenericParameterCount)); } return pooled.ToStringAndFree(); } /// <summary> /// Strip off *, &amp;, and []. /// </summary> private static ITypeReference UnwrapTypeReference(ITypeReference typeReference, EmitContext context) { while (true) { IArrayTypeReference arrType = typeReference as IArrayTypeReference; if (arrType != null) { typeReference = arrType.GetElementType(context); continue; } IPointerTypeReference pointer = typeReference as IPointerTypeReference; if (pointer != null) { typeReference = pointer.GetTargetType(context); continue; } return typeReference; } } /// <summary> /// Qualified name of namespace. /// e.g. "A.B.C" /// </summary> internal static string BuildQualifiedNamespaceName(INamespace @namespace) { Debug.Assert(@namespace != null); if (@namespace.ContainingNamespace == null) { return @namespace.Name; } var namesReversed = ArrayBuilder<string>.GetInstance(); do { string name = @namespace.Name; if (name.Length != 0) { namesReversed.Add(name); } @namespace = @namespace.ContainingNamespace; } while (@namespace != null); var result = PooledStringBuilder.GetInstance(); for (int i = namesReversed.Count - 1; i >= 0; i--) { result.Builder.Append(namesReversed[i]); if (i > 0) { result.Builder.Append('.'); } } namesReversed.Free(); return result.ToStringAndFree(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using System.Text; using System.Diagnostics; namespace Microsoft.Cci { internal static class TypeNameSerializer { internal static string GetSerializedTypeName(this ITypeReference typeReference, EmitContext context) { bool isAssemblyQualified = true; return GetSerializedTypeName(typeReference, context, ref isAssemblyQualified); } internal static string GetSerializedTypeName(this ITypeReference typeReference, EmitContext context, ref bool isAssemblyQualified) { var pooled = PooledStringBuilder.GetInstance(); StringBuilder sb = pooled.Builder; IArrayTypeReference arrType = typeReference as IArrayTypeReference; if (arrType != null) { typeReference = arrType.GetElementType(context); bool isAssemQual = false; AppendSerializedTypeName(sb, typeReference, ref isAssemQual, context); if (arrType.IsSZArray) { sb.Append("[]"); } else { sb.Append('['); if (arrType.Rank == 1) { sb.Append('*'); } sb.Append(',', (int)arrType.Rank - 1); sb.Append(']'); } goto done; } IPointerTypeReference pointer = typeReference as IPointerTypeReference; if (pointer != null) { typeReference = pointer.GetTargetType(context); bool isAssemQual = false; AppendSerializedTypeName(sb, typeReference, ref isAssemQual, context); sb.Append('*'); goto done; } INamespaceTypeReference namespaceType = typeReference.AsNamespaceTypeReference; if (namespaceType != null) { var name = namespaceType.NamespaceName; if (name.Length != 0) { sb.Append(name); sb.Append('.'); } sb.Append(GetMangledAndEscapedName(namespaceType)); goto done; } if (typeReference.IsTypeSpecification()) { ITypeReference uninstantiatedTypeReference = typeReference.GetUninstantiatedGenericType(context); ArrayBuilder<ITypeReference> consolidatedTypeArguments = ArrayBuilder<ITypeReference>.GetInstance(); typeReference.GetConsolidatedTypeArguments(consolidatedTypeArguments, context); bool uninstantiatedTypeIsAssemblyQualified = false; sb.Append(GetSerializedTypeName(uninstantiatedTypeReference, context, ref uninstantiatedTypeIsAssemblyQualified)); sb.Append('['); bool first = true; foreach (ITypeReference argument in consolidatedTypeArguments) { if (first) { first = false; } else { sb.Append(','); } bool isAssemQual = true; AppendSerializedTypeName(sb, argument, ref isAssemQual, context); } consolidatedTypeArguments.Free(); sb.Append(']'); goto done; } INestedTypeReference nestedType = typeReference.AsNestedTypeReference; if (nestedType != null) { bool nestedTypeIsAssemblyQualified = false; sb.Append(GetSerializedTypeName(nestedType.GetContainingType(context), context, ref nestedTypeIsAssemblyQualified)); sb.Append('+'); sb.Append(GetMangledAndEscapedName(nestedType)); goto done; } // TODO: error done: if (isAssemblyQualified) { AppendAssemblyQualifierIfNecessary(sb, UnwrapTypeReference(typeReference, context), out isAssemblyQualified, context); } return pooled.ToStringAndFree(); } private static void AppendSerializedTypeName(StringBuilder sb, ITypeReference type, ref bool isAssemQualified, EmitContext context) { string argTypeName = GetSerializedTypeName(type, context, ref isAssemQualified); if (isAssemQualified) { sb.Append('['); } sb.Append(argTypeName); if (isAssemQualified) { sb.Append(']'); } } private static void AppendAssemblyQualifierIfNecessary(StringBuilder sb, ITypeReference typeReference, out bool isAssemQualified, EmitContext context) { INestedTypeReference nestedType = typeReference.AsNestedTypeReference; if (nestedType != null) { AppendAssemblyQualifierIfNecessary(sb, nestedType.GetContainingType(context), out isAssemQualified, context); return; } IGenericTypeInstanceReference genInst = typeReference.AsGenericTypeInstanceReference; if (genInst != null) { AppendAssemblyQualifierIfNecessary(sb, genInst.GetGenericType(context), out isAssemQualified, context); return; } IArrayTypeReference arrType = typeReference as IArrayTypeReference; if (arrType != null) { AppendAssemblyQualifierIfNecessary(sb, arrType.GetElementType(context), out isAssemQualified, context); return; } IPointerTypeReference pointer = typeReference as IPointerTypeReference; if (pointer != null) { AppendAssemblyQualifierIfNecessary(sb, pointer.GetTargetType(context), out isAssemQualified, context); return; } isAssemQualified = false; IAssemblyReference referencedAssembly = null; INamespaceTypeReference namespaceType = typeReference.AsNamespaceTypeReference; if (namespaceType != null) { referencedAssembly = namespaceType.GetUnit(context) as IAssemblyReference; } if (referencedAssembly != null) { var containingAssembly = context.Module.GetContainingAssembly(context); if (containingAssembly == null || !ReferenceEquals(referencedAssembly, containingAssembly)) { sb.Append(", "); sb.Append(MetadataWriter.StrongName(referencedAssembly)); isAssemQualified = true; } } } private static string GetMangledAndEscapedName(INamedTypeReference namedType) { var pooled = PooledStringBuilder.GetInstance(); StringBuilder mangledName = pooled.Builder; const string needsEscaping = "\\[]*.+,& "; foreach (var ch in namedType.Name) { if (needsEscaping.IndexOf(ch) >= 0) { mangledName.Append('\\'); } mangledName.Append(ch); } if (namedType.MangleName && namedType.GenericParameterCount > 0) { mangledName.Append(MetadataHelpers.GetAritySuffix(namedType.GenericParameterCount)); } return pooled.ToStringAndFree(); } /// <summary> /// Strip off *, &amp;, and []. /// </summary> private static ITypeReference UnwrapTypeReference(ITypeReference typeReference, EmitContext context) { while (true) { IArrayTypeReference arrType = typeReference as IArrayTypeReference; if (arrType != null) { typeReference = arrType.GetElementType(context); continue; } IPointerTypeReference pointer = typeReference as IPointerTypeReference; if (pointer != null) { typeReference = pointer.GetTargetType(context); continue; } return typeReference; } } /// <summary> /// Qualified name of namespace. /// e.g. "A.B.C" /// </summary> internal static string BuildQualifiedNamespaceName(INamespace @namespace) { Debug.Assert(@namespace != null); if (@namespace.ContainingNamespace == null) { return @namespace.Name; } var namesReversed = ArrayBuilder<string>.GetInstance(); do { string name = @namespace.Name; if (name.Length != 0) { namesReversed.Add(name); } @namespace = @namespace.ContainingNamespace; } while (@namespace != null); var result = PooledStringBuilder.GetInstance(); for (int i = namesReversed.Count - 1; i >= 0; i--) { result.Builder.Append(namesReversed[i]); if (i > 0) { result.Builder.Append('.'); } } namesReversed.Free(); return result.ToStringAndFree(); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Test/Syntax/Properties/launchSettings.json
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Analyzers/CSharp/Tests/MatchFolderAndNamespace/CSharpMatchFolderAndNamespaceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; using System.Threading.Tasks; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.CSharp.Analyzers.MatchFolderAndNamespace.CSharpMatchFolderAndNamespaceDiagnosticAnalyzer, Microsoft.CodeAnalysis.CSharp.CodeFixes.MatchFolderAndNamespace.CSharpChangeNamespaceToMatchFolderCodeFixProvider>; namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.MatchFolderAndNamespace { public class CSharpMatchFolderAndNamespaceTests { private static readonly string Directory = Path.Combine("Test", "Directory"); // DefaultNamespace gets exposed as RootNamespace in the build properties private const string DefaultNamespace = "Test.Root.Namespace"; private static readonly string EditorConfig = @$" is_global=true build_property.ProjectDir = {Directory} build_property.RootNamespace = {DefaultNamespace} "; private static string CreateFolderPath(params string[] folders) => Path.Combine(Directory, Path.Combine(folders)); private static Task RunTestAsync(string fileName, string fileContents, string? directory = null, string? editorConfig = null, string? fixedCode = null) { var filePath = Path.Combine(directory ?? Directory, fileName); fixedCode ??= fileContents; return RunTestAsync( new[] { (filePath, fileContents) }, new[] { (filePath, fixedCode) }, editorConfig); } private static Task RunTestAsync(IEnumerable<(string, string)> originalSources, IEnumerable<(string, string)>? fixedSources = null, string? editorconfig = null) { var testState = new VerifyCS.Test { EditorConfig = editorconfig ?? EditorConfig, CodeFixTestBehaviors = CodeAnalysis.Testing.CodeFixTestBehaviors.SkipFixAllInDocumentCheck, LanguageVersion = LanguageVersion.CSharp10, }; foreach (var (fileName, content) in originalSources) testState.TestState.Sources.Add((fileName, content)); fixedSources ??= Array.Empty<(string, string)>(); foreach (var (fileName, content) in fixedSources) testState.FixedState.Sources.Add((fileName, content)); return testState.RunAsync(); } [Fact] public Task InvalidFolderName1_NoDiagnostic() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { "3B", "C" }); var code = @" namespace A.B { class Class1 { } }"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task InvalidFolderName1_NoDiagnostic_FileScopedNamespace() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { "3B", "C" }); var code = @" namespace A.B; class Class1 { } "; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task InvalidFolderName2_NoDiagnostic() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { "B.3C", "D" }); var code = @" namespace A.B { class Class1 { } }"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task InvalidFolderName3_NoDiagnostic() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { ".folder", "..subfolder", "name" }); var code = @" namespace A.B { class Class1 { } }"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task CaseInsensitiveMatch_NoDiagnostic() { var folder = CreateFolderPath(new[] { "A", "B" }); var code = @$" namespace {DefaultNamespace}.a.b {{ class Class1 {{ }} }}"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public async Task SingleDocumentNoReference() { var folder = CreateFolderPath("B", "C"); var code = @"namespace [|A.B|] { class Class1 { } }"; var fixedCode = @$"namespace {DefaultNamespace}.B.C {{ class Class1 {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder, fixedCode: fixedCode); } [Fact] public async Task SingleDocumentNoReference_FileScopedNamespace() { var folder = CreateFolderPath("B", "C"); var code = @"namespace [|A.B|]; class Class1 { } "; var fixedCode = @$"namespace {DefaultNamespace}.B.C; class Class1 {{ }} "; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder, fixedCode: fixedCode); } [Fact] public async Task SingleDocumentNoReference_NoDefaultNamespace() { var editorConfig = @$" is_global=true build_property.ProjectDir = {Directory} "; var folder = CreateFolderPath("B", "C"); var code = @"namespace [|A.B|] { class Class1 { } }"; var fixedCode = @$"namespace B.C {{ class Class1 {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder, fixedCode: fixedCode, editorConfig: editorConfig); } [Fact] public async Task SingleDocumentNoReference_NoDefaultNamespace_FileScopedNamespace() { var editorConfig = @$" is_global=true build_property.ProjectDir = {Directory} "; var folder = CreateFolderPath("B", "C"); var code = @"namespace [|A.B|]; class Class1 { } "; var fixedCode = @$"namespace B.C; class Class1 {{ }} "; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder, fixedCode: fixedCode, editorConfig: editorConfig); } [Fact] public async Task NamespaceWithSpaces_NoDiagnostic() { var folder = CreateFolderPath("A", "B"); var code = @$"namespace {DefaultNamespace}.A . B {{ class Class1 {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder); } [Fact] public async Task NestedNamespaces_NoDiagnostic() { // The code fix doesn't currently support nested namespaces for sync, so // diagnostic does not report. var folder = CreateFolderPath("B", "C"); var code = @"namespace A.B { namespace C.D { class CDClass { } } class ABClass { } }"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder); } [Fact] public async Task PartialTypeWithMultipleDeclarations_NoDiagnostic() { // The code fix doesn't currently support nested namespaces for sync, so // diagnostic does not report. var folder = CreateFolderPath("B", "C"); var code1 = @"namespace A.B { partial class ABClass { void M1() {} } }"; var code2 = @"namespace A.B { partial class ABClass { void M2() {} } }"; var sources = new[] { (Path.Combine(folder, "ABClass1.cs"), code1), (Path.Combine(folder, "ABClass2.cs"), code2), }; await RunTestAsync(sources); } [Fact] public async Task FileNotInProjectFolder_NoDiagnostic() { // Default directory is Test\Directory for the project, // putting the file outside the directory should have no // diagnostic shown. var folder = Path.Combine("B", "C"); var code = $@"namespace A.B {{ class ABClass {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder); } [Fact] public async Task SingleDocumentLocalReference() { var @namespace = "Bar.Baz"; var folder = CreateFolderPath("A", "B", "C"); var code = $@" namespace [|{@namespace}|] {{ delegate void D1(); interface Class1 {{ void M1(); }} class Class2 : {@namespace}.Class1 {{ {@namespace}.D1 d; void {@namespace}.Class1.M1(){{}} }} }}"; var expected = @$"namespace {DefaultNamespace}.A.B.C {{ delegate void D1(); interface Class1 {{ void M1(); }} class Class2 : Class1 {{ D1 d; void Class1.M1() {{ }} }} }}"; await RunTestAsync( "Class1.cs", code, folder, fixedCode: expected); } [Fact] public async Task ChangeUsingsInMultipleContainers() { var declaredNamespace = "Bar.Baz"; var folder = CreateFolderPath("A", "B", "C"); var code1 = $@"namespace [|{declaredNamespace}|] {{ class Class1 {{ }} }}"; var code2 = $@"namespace NS1 {{ using {declaredNamespace}; class Class2 {{ Class1 c2; }} namespace NS2 {{ using {declaredNamespace}; class Class2 {{ Class1 c1; }} }} }}"; var fixed1 = @$"namespace {DefaultNamespace}.A.B.C {{ class Class1 {{ }} }}"; var fixed2 = @$"namespace NS1 {{ using {DefaultNamespace}.A.B.C; class Class2 {{ Class1 c2; }} namespace NS2 {{ class Class2 {{ Class1 c1; }} }} }}"; var originalSources = new[] { (Path.Combine(folder, "Class1.cs"), code1), ("Class2.cs", code2) }; var fixedSources = new[] { (Path.Combine(folder, "Class1.cs"), fixed1), ("Class2.cs", fixed2) }; await RunTestAsync(originalSources, fixedSources); } [Fact] public async Task ChangeNamespace_WithAliasReferencesInOtherDocument() { var declaredNamespace = $"Bar.Baz"; var folder = CreateFolderPath("A", "B", "C"); var code1 = $@"namespace [|{declaredNamespace}|] {{ class Class1 {{ }} }}"; var code2 = $@" using System; using {declaredNamespace}; using Class1Alias = {declaredNamespace}.Class1; namespace Foo {{ class RefClass {{ private Class1Alias c1; }} }}"; var fixed1 = @$"namespace {DefaultNamespace}.A.B.C {{ class Class1 {{ }} }}"; var fixed2 = @$" using System; using Class1Alias = {DefaultNamespace}.A.B.C.Class1; namespace Foo {{ class RefClass {{ private Class1Alias c1; }} }}"; var originalSources = new[] { (Path.Combine(folder, "Class1.cs"), code1), ("Class2.cs", code2) }; var fixedSources = new[] { (Path.Combine(folder, "Class1.cs"), fixed1), ("Class2.cs", fixed2) }; await RunTestAsync(originalSources, fixedSources); } [Fact] public async Task FixAll() { var declaredNamespace = "Bar.Baz"; var folder1 = CreateFolderPath("A", "B", "C"); var fixedNamespace1 = $"{DefaultNamespace}.A.B.C"; var folder2 = CreateFolderPath("Second", "Folder", "Path"); var fixedNamespace2 = $"{DefaultNamespace}.Second.Folder.Path"; var folder3 = CreateFolderPath("Third", "Folder", "Path"); var fixedNamespace3 = $"{DefaultNamespace}.Third.Folder.Path"; var code1 = $@"namespace [|{declaredNamespace}|] {{ class Class1 {{ Class2 C2 {{ get; }} Class3 C3 {{ get; }} }} }}"; var fixed1 = $@"using {fixedNamespace2}; using {fixedNamespace3}; namespace {fixedNamespace1} {{ class Class1 {{ Class2 C2 {{ get; }} Class3 C3 {{ get; }} }} }}"; var code2 = $@"namespace [|{declaredNamespace}|] {{ class Class2 {{ Class1 C1 {{ get; }} Class3 C3 {{ get; }} }} }}"; var fixed2 = $@"using {fixedNamespace1}; using {fixedNamespace3}; namespace {fixedNamespace2} {{ class Class2 {{ Class1 C1 {{ get; }} Class3 C3 {{ get; }} }} }}"; var code3 = $@"namespace [|{declaredNamespace}|] {{ class Class3 {{ Class1 C1 {{ get; }} Class2 C2 {{ get; }} }} }}"; var fixed3 = $@"using {fixedNamespace1}; using {fixedNamespace2}; namespace {fixedNamespace3} {{ class Class3 {{ Class1 C1 {{ get; }} Class2 C2 {{ get; }} }} }}"; var sources = new[] { (Path.Combine(folder1, "Class1.cs"), code1), (Path.Combine(folder2, "Class2.cs"), code2), (Path.Combine(folder3, "Class3.cs"), code3), }; var fixedSources = new[] { (Path.Combine(folder1, "Class1.cs"), fixed1), (Path.Combine(folder2, "Class2.cs"), fixed2), (Path.Combine(folder3, "Class3.cs"), fixed3), }; await RunTestAsync(sources, fixedSources); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; using System.Threading.Tasks; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.CSharp.Analyzers.MatchFolderAndNamespace.CSharpMatchFolderAndNamespaceDiagnosticAnalyzer, Microsoft.CodeAnalysis.CSharp.CodeFixes.MatchFolderAndNamespace.CSharpChangeNamespaceToMatchFolderCodeFixProvider>; namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.MatchFolderAndNamespace { public class CSharpMatchFolderAndNamespaceTests { private static readonly string Directory = Path.Combine("Test", "Directory"); // DefaultNamespace gets exposed as RootNamespace in the build properties private const string DefaultNamespace = "Test.Root.Namespace"; private static readonly string EditorConfig = @$" is_global=true build_property.ProjectDir = {Directory} build_property.RootNamespace = {DefaultNamespace} "; private static string CreateFolderPath(params string[] folders) => Path.Combine(Directory, Path.Combine(folders)); private static Task RunTestAsync(string fileName, string fileContents, string? directory = null, string? editorConfig = null, string? fixedCode = null) { var filePath = Path.Combine(directory ?? Directory, fileName); fixedCode ??= fileContents; return RunTestAsync( new[] { (filePath, fileContents) }, new[] { (filePath, fixedCode) }, editorConfig); } private static Task RunTestAsync(IEnumerable<(string, string)> originalSources, IEnumerable<(string, string)>? fixedSources = null, string? editorconfig = null) { var testState = new VerifyCS.Test { EditorConfig = editorconfig ?? EditorConfig, CodeFixTestBehaviors = CodeAnalysis.Testing.CodeFixTestBehaviors.SkipFixAllInDocumentCheck, LanguageVersion = LanguageVersion.CSharp10, }; foreach (var (fileName, content) in originalSources) testState.TestState.Sources.Add((fileName, content)); fixedSources ??= Array.Empty<(string, string)>(); foreach (var (fileName, content) in fixedSources) testState.FixedState.Sources.Add((fileName, content)); return testState.RunAsync(); } [Fact] public Task InvalidFolderName1_NoDiagnostic() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { "3B", "C" }); var code = @" namespace A.B { class Class1 { } }"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task InvalidFolderName1_NoDiagnostic_FileScopedNamespace() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { "3B", "C" }); var code = @" namespace A.B; class Class1 { } "; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task InvalidFolderName2_NoDiagnostic() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { "B.3C", "D" }); var code = @" namespace A.B { class Class1 { } }"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task InvalidFolderName3_NoDiagnostic() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { ".folder", "..subfolder", "name" }); var code = @" namespace A.B { class Class1 { } }"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task CaseInsensitiveMatch_NoDiagnostic() { var folder = CreateFolderPath(new[] { "A", "B" }); var code = @$" namespace {DefaultNamespace}.a.b {{ class Class1 {{ }} }}"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public async Task SingleDocumentNoReference() { var folder = CreateFolderPath("B", "C"); var code = @"namespace [|A.B|] { class Class1 { } }"; var fixedCode = @$"namespace {DefaultNamespace}.B.C {{ class Class1 {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder, fixedCode: fixedCode); } [Fact] public async Task SingleDocumentNoReference_FileScopedNamespace() { var folder = CreateFolderPath("B", "C"); var code = @"namespace [|A.B|]; class Class1 { } "; var fixedCode = @$"namespace {DefaultNamespace}.B.C; class Class1 {{ }} "; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder, fixedCode: fixedCode); } [Fact] public async Task SingleDocumentNoReference_NoDefaultNamespace() { var editorConfig = @$" is_global=true build_property.ProjectDir = {Directory} "; var folder = CreateFolderPath("B", "C"); var code = @"namespace [|A.B|] { class Class1 { } }"; var fixedCode = @$"namespace B.C {{ class Class1 {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder, fixedCode: fixedCode, editorConfig: editorConfig); } [Fact] public async Task SingleDocumentNoReference_NoDefaultNamespace_FileScopedNamespace() { var editorConfig = @$" is_global=true build_property.ProjectDir = {Directory} "; var folder = CreateFolderPath("B", "C"); var code = @"namespace [|A.B|]; class Class1 { } "; var fixedCode = @$"namespace B.C; class Class1 {{ }} "; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder, fixedCode: fixedCode, editorConfig: editorConfig); } [Fact] public async Task NamespaceWithSpaces_NoDiagnostic() { var folder = CreateFolderPath("A", "B"); var code = @$"namespace {DefaultNamespace}.A . B {{ class Class1 {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder); } [Fact] public async Task NestedNamespaces_NoDiagnostic() { // The code fix doesn't currently support nested namespaces for sync, so // diagnostic does not report. var folder = CreateFolderPath("B", "C"); var code = @"namespace A.B { namespace C.D { class CDClass { } } class ABClass { } }"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder); } [Fact] public async Task PartialTypeWithMultipleDeclarations_NoDiagnostic() { // The code fix doesn't currently support nested namespaces for sync, so // diagnostic does not report. var folder = CreateFolderPath("B", "C"); var code1 = @"namespace A.B { partial class ABClass { void M1() {} } }"; var code2 = @"namespace A.B { partial class ABClass { void M2() {} } }"; var sources = new[] { (Path.Combine(folder, "ABClass1.cs"), code1), (Path.Combine(folder, "ABClass2.cs"), code2), }; await RunTestAsync(sources); } [Fact] public async Task FileNotInProjectFolder_NoDiagnostic() { // Default directory is Test\Directory for the project, // putting the file outside the directory should have no // diagnostic shown. var folder = Path.Combine("B", "C"); var code = $@"namespace A.B {{ class ABClass {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder); } [Fact] public async Task SingleDocumentLocalReference() { var @namespace = "Bar.Baz"; var folder = CreateFolderPath("A", "B", "C"); var code = $@" namespace [|{@namespace}|] {{ delegate void D1(); interface Class1 {{ void M1(); }} class Class2 : {@namespace}.Class1 {{ {@namespace}.D1 d; void {@namespace}.Class1.M1(){{}} }} }}"; var expected = @$"namespace {DefaultNamespace}.A.B.C {{ delegate void D1(); interface Class1 {{ void M1(); }} class Class2 : Class1 {{ D1 d; void Class1.M1() {{ }} }} }}"; await RunTestAsync( "Class1.cs", code, folder, fixedCode: expected); } [Fact] public async Task ChangeUsingsInMultipleContainers() { var declaredNamespace = "Bar.Baz"; var folder = CreateFolderPath("A", "B", "C"); var code1 = $@"namespace [|{declaredNamespace}|] {{ class Class1 {{ }} }}"; var code2 = $@"namespace NS1 {{ using {declaredNamespace}; class Class2 {{ Class1 c2; }} namespace NS2 {{ using {declaredNamespace}; class Class2 {{ Class1 c1; }} }} }}"; var fixed1 = @$"namespace {DefaultNamespace}.A.B.C {{ class Class1 {{ }} }}"; var fixed2 = @$"namespace NS1 {{ using {DefaultNamespace}.A.B.C; class Class2 {{ Class1 c2; }} namespace NS2 {{ class Class2 {{ Class1 c1; }} }} }}"; var originalSources = new[] { (Path.Combine(folder, "Class1.cs"), code1), ("Class2.cs", code2) }; var fixedSources = new[] { (Path.Combine(folder, "Class1.cs"), fixed1), ("Class2.cs", fixed2) }; await RunTestAsync(originalSources, fixedSources); } [Fact] public async Task DocumentAtRoot_NoDiagnostic() { var folder = CreateFolderPath(); var code = $@" namespace {DefaultNamespace} {{ class C {{ }} }}"; await RunTestAsync( "File1.cs", code, folder); } [Fact] public async Task DocumentAtRoot_ChangeNamespace() { var folder = CreateFolderPath(); var code = $@"namespace [|{DefaultNamespace}.Test|] {{ class C {{ }} }}"; var fixedCode = $@"namespace {DefaultNamespace} {{ class C {{ }} }}"; await RunTestAsync( "File1.cs", code, folder, fixedCode: fixedCode); } [Fact] public async Task ChangeNamespace_WithAliasReferencesInOtherDocument() { var declaredNamespace = $"Bar.Baz"; var folder = CreateFolderPath("A", "B", "C"); var code1 = $@"namespace [|{declaredNamespace}|] {{ class Class1 {{ }} }}"; var code2 = $@" using System; using {declaredNamespace}; using Class1Alias = {declaredNamespace}.Class1; namespace Foo {{ class RefClass {{ private Class1Alias c1; }} }}"; var fixed1 = @$"namespace {DefaultNamespace}.A.B.C {{ class Class1 {{ }} }}"; var fixed2 = @$" using System; using Class1Alias = {DefaultNamespace}.A.B.C.Class1; namespace Foo {{ class RefClass {{ private Class1Alias c1; }} }}"; var originalSources = new[] { (Path.Combine(folder, "Class1.cs"), code1), ("Class2.cs", code2) }; var fixedSources = new[] { (Path.Combine(folder, "Class1.cs"), fixed1), ("Class2.cs", fixed2) }; await RunTestAsync(originalSources, fixedSources); } [Fact] public async Task FixAll() { var declaredNamespace = "Bar.Baz"; var folder1 = CreateFolderPath("A", "B", "C"); var fixedNamespace1 = $"{DefaultNamespace}.A.B.C"; var folder2 = CreateFolderPath("Second", "Folder", "Path"); var fixedNamespace2 = $"{DefaultNamespace}.Second.Folder.Path"; var folder3 = CreateFolderPath("Third", "Folder", "Path"); var fixedNamespace3 = $"{DefaultNamespace}.Third.Folder.Path"; var code1 = $@"namespace [|{declaredNamespace}|] {{ class Class1 {{ Class2 C2 {{ get; }} Class3 C3 {{ get; }} }} }}"; var fixed1 = $@"using {fixedNamespace2}; using {fixedNamespace3}; namespace {fixedNamespace1} {{ class Class1 {{ Class2 C2 {{ get; }} Class3 C3 {{ get; }} }} }}"; var code2 = $@"namespace [|{declaredNamespace}|] {{ class Class2 {{ Class1 C1 {{ get; }} Class3 C3 {{ get; }} }} }}"; var fixed2 = $@"using {fixedNamespace1}; using {fixedNamespace3}; namespace {fixedNamespace2} {{ class Class2 {{ Class1 C1 {{ get; }} Class3 C3 {{ get; }} }} }}"; var code3 = $@"namespace [|{declaredNamespace}|] {{ class Class3 {{ Class1 C1 {{ get; }} Class2 C2 {{ get; }} }} }}"; var fixed3 = $@"using {fixedNamespace1}; using {fixedNamespace2}; namespace {fixedNamespace3} {{ class Class3 {{ Class1 C1 {{ get; }} Class2 C2 {{ get; }} }} }}"; var sources = new[] { (Path.Combine(folder1, "Class1.cs"), code1), (Path.Combine(folder2, "Class2.cs"), code2), (Path.Combine(folder3, "Class3.cs"), code3), }; var fixedSources = new[] { (Path.Combine(folder1, "Class1.cs"), fixed1), (Path.Combine(folder2, "Class2.cs"), fixed2), (Path.Combine(folder3, "Class3.cs"), fixed3), }; await RunTestAsync(sources, fixedSources); } } }
1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Analyzers/Core/CodeFixes/MatchFolderAndNamespace/AbstractChangeNamespaceToMatchFolderCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Analyzers.MatchFolderAndNamespace; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes.MatchFolderAndNamespace { internal abstract partial class AbstractChangeNamespaceToMatchFolderCodeFixProvider : CodeFixProvider { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.MatchFolderAndNamespaceDiagnosticId); public override Task RegisterCodeFixesAsync(CodeFixContext context) { if (context.Document.Project.Solution.Workspace.CanApplyChange(ApplyChangesKind.ChangeDocumentInfo)) { context.RegisterCodeFix( new MyCodeAction(AnalyzersResources.Change_namespace_to_match_folder_structure, cancellationToken => FixAllInDocumentAsync(context.Document, context.Diagnostics, cancellationToken)), context.Diagnostics); } return Task.CompletedTask; } private static async Task<Solution> FixAllInDocumentAsync(Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken) { // All the target namespaces should be the same for a given document Debug.Assert(diagnostics.Select(diagnostic => diagnostic.Properties[MatchFolderAndNamespaceConstants.TargetNamespace]).Distinct().Count() == 1); var targetNamespace = diagnostics.First().Properties[MatchFolderAndNamespaceConstants.TargetNamespace]; RoslynDebug.AssertNotNull(targetNamespace); // Use the Renamer.RenameDocumentAsync API to sync namespaces in the document. This allows // us to keep in line with the sync methodology that we have as a public API and not have // to rewrite or move the complex logic. RenameDocumentAsync is designed to behave the same // as the intent of this analyzer/codefix pair. var targetFolders = PathMetadataUtilities.BuildFoldersFromNamespace(targetNamespace); var documentWithNoFolders = document.WithFolders(Array.Empty<string>()); var renameActionSet = await Renamer.RenameDocumentAsync( documentWithNoFolders, documentWithNoFolders.Name, newDocumentFolders: targetFolders, cancellationToken: cancellationToken).ConfigureAwait(false); var newSolution = await renameActionSet.UpdateSolutionAsync(documentWithNoFolders.Project.Solution, cancellationToken).ConfigureAwait(false); Debug.Assert(newSolution != document.Project.Solution); return newSolution; } public override FixAllProvider? GetFixAllProvider() => CustomFixAllProvider.Instance; private sealed class MyCodeAction : CustomCodeActions.SolutionChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution) : base(title, createChangedSolution, 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.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Analyzers.MatchFolderAndNamespace; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes.MatchFolderAndNamespace { internal abstract partial class AbstractChangeNamespaceToMatchFolderCodeFixProvider : CodeFixProvider { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.MatchFolderAndNamespaceDiagnosticId); public override Task RegisterCodeFixesAsync(CodeFixContext context) { if (context.Document.Project.Solution.Workspace.CanApplyChange(ApplyChangesKind.ChangeDocumentInfo)) { context.RegisterCodeFix( new MyCodeAction(AnalyzersResources.Change_namespace_to_match_folder_structure, cancellationToken => FixAllInDocumentAsync(context.Document, context.Diagnostics, cancellationToken)), context.Diagnostics); } return Task.CompletedTask; } private static async Task<Solution> FixAllInDocumentAsync(Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken) { // All the target namespaces should be the same for a given document Debug.Assert(diagnostics.Select(diagnostic => diagnostic.Properties[MatchFolderAndNamespaceConstants.TargetNamespace]).Distinct().Count() == 1); var targetNamespace = diagnostics.First().Properties[MatchFolderAndNamespaceConstants.TargetNamespace]; RoslynDebug.AssertNotNull(targetNamespace); // Use the Renamer.RenameDocumentAsync API to sync namespaces in the document. This allows // us to keep in line with the sync methodology that we have as a public API and not have // to rewrite or move the complex logic. RenameDocumentAsync is designed to behave the same // as the intent of this analyzer/codefix pair. var targetFolders = PathMetadataUtilities.BuildFoldersFromNamespace(targetNamespace, document.Project.DefaultNamespace); var documentWithNoFolders = document.WithFolders(Array.Empty<string>()); var renameActionSet = await Renamer.RenameDocumentAsync( documentWithNoFolders, documentWithNoFolders.Name, newDocumentFolders: targetFolders, cancellationToken: cancellationToken).ConfigureAwait(false); var newSolution = await renameActionSet.UpdateSolutionAsync(documentWithNoFolders.Project.Solution, cancellationToken).ConfigureAwait(false); Debug.Assert(newSolution != document.Project.Solution); return newSolution; } public override FixAllProvider? GetFixAllProvider() => CustomFixAllProvider.Instance; private sealed class MyCodeAction : CustomCodeActions.SolutionChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution) : base(title, createChangedSolution, title) { } } } }
1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractSyncNamespaceCodeRefactoringProvider.State.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ChangeNamespace; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeRefactorings.SyncNamespace { internal abstract partial class AbstractSyncNamespaceCodeRefactoringProvider<TNamespaceDeclarationSyntax, TCompilationUnitSyntax, TMemberDeclarationSyntax> : CodeRefactoringProvider where TNamespaceDeclarationSyntax : SyntaxNode where TCompilationUnitSyntax : SyntaxNode where TMemberDeclarationSyntax : SyntaxNode { internal sealed class State { /// <summary> /// The document in which the refactoring is triggered. /// </summary> public Document Document { get; } /// <summary> /// The applicable container node based on cursor location, /// which will be used to change namespace. /// </summary> public SyntaxNode Container { get; } /// <summary> /// This is the new name we want to change the namespace to. /// Empty string means global namespace, whereas null means change namespace action is not available. /// </summary> public string TargetNamespace { get; } /// <summary> /// This is the part of the declared namespace that is contained in default namespace. /// We will use this to construct target folder to move the file to. /// For example, if default namespace is `A` and declared namespace is `A.B.C`, /// this would be `B.C`. /// </summary> public string RelativeDeclaredNamespace { get; } private State( Document document, SyntaxNode container, string targetNamespace, string relativeDeclaredNamespace) { Document = document; Container = container; TargetNamespace = targetNamespace; RelativeDeclaredNamespace = relativeDeclaredNamespace; } public static async Task<State> CreateAsync( AbstractSyncNamespaceCodeRefactoringProvider<TNamespaceDeclarationSyntax, TCompilationUnitSyntax, TMemberDeclarationSyntax> provider, Document document, TextSpan textSpan, CancellationToken cancellationToken) { // User must put cursor on one of the nodes described below to trigger the refactoring. // For each scenario, all requirements must be met. Some of them are checked by `TryGetApplicableInvocationNodeAsync`, // rest by `IChangeNamespaceService.CanChangeNamespaceAsync`. // // - A namespace declaration node that is the only namespace declaration in the document and all types are declared in it: // 1. No nested namespace declarations (even it's empty). // 2. The cursor is on the name of the namespace declaration. // 3. The name of the namespace is valid (i.e. no errors). // 4. No partial type declared in the namespace. Otherwise its multiple declaration will // end up in different namespace. // // - A compilation unit node that contains no namespace declaration: // 1. The cursor is on the name of first declared type. // 2. No partial type declared in the document. Otherwise its multiple declaration will // end up in different namespace. var applicableNode = await provider.TryGetApplicableInvocationNodeAsync(document, textSpan, cancellationToken).ConfigureAwait(false); if (applicableNode == null) { return null; } var changeNamespaceService = document.GetLanguageService<IChangeNamespaceService>(); var canChange = await changeNamespaceService.CanChangeNamespaceAsync(document, applicableNode, cancellationToken).ConfigureAwait(false); if (!canChange || !IsDocumentPathRootedInProjectFolder(document)) { return null; } var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); // We can't determine what the expected namespace would be without knowing the default namespace. var defaultNamespace = GetDefaultNamespace(document, syntaxFacts); if (defaultNamespace == null) { return null; } string declaredNamespace; if (applicableNode is TCompilationUnitSyntax) { declaredNamespace = string.Empty; } else if (applicableNode is TNamespaceDeclarationSyntax) { var syntaxGenerator = SyntaxGenerator.GetGenerator(document); declaredNamespace = syntaxGenerator.GetName(applicableNode); } else { throw ExceptionUtilities.Unreachable; } // Namespace can't be changed if we can't construct a valid qualified identifier from folder names. // In this case, we might still be able to provide refactoring to move file to new location. var namespaceFromFolders = PathMetadataUtilities.TryBuildNamespaceFromFolders(document.Folders, syntaxFacts); var targetNamespace = namespaceFromFolders == null ? null : ConcatNamespace(defaultNamespace, namespaceFromFolders); // No action required if namespace already matches folders. if (syntaxFacts.StringComparer.Equals(targetNamespace, declaredNamespace)) { return null; } // Only provide "move file" action if default namespace contains declared namespace. // For example, if the default namespace is `Microsoft.CodeAnalysis`, and declared // namespace is `System.Diagnostics`, it's very likely this document is an outlier // in the project and user probably has some special rule for it. var relativeNamespace = GetRelativeNamespace(defaultNamespace, declaredNamespace, syntaxFacts); return new State(document, applicableNode, targetNamespace, relativeNamespace); } /// <summary> /// Determines if the actual file path matches its logical path in project /// which is constructed as [project_root_path]\Logical\Folders\. The refactoring /// is triggered only when the two match. The reason of doing this is we don't really know /// the user's intention of keeping the file path out-of-sync with its logical path. /// </summary> private static bool IsDocumentPathRootedInProjectFolder(Document document) { var projectRoot = PathUtilities.GetDirectoryName(document.Project.FilePath); var folderPath = Path.Combine(document.Folders.ToArray()); var absoluteDircetoryPath = PathUtilities.GetDirectoryName(document.FilePath); var logicalDirectoryPath = PathUtilities.CombineAbsoluteAndRelativePaths(projectRoot, folderPath); return PathUtilities.PathsEqual(absoluteDircetoryPath, logicalDirectoryPath); } private static string GetDefaultNamespace(Document document, ISyntaxFactsService syntaxFacts) { var solution = document.Project.Solution; var linkedIds = document.GetLinkedDocumentIds(); var documents = linkedIds.SelectAsArray(id => solution.GetDocument(id)).Add(document); // For all projects containing all the linked documents, bail if // 1. Any of them doesn't have default namespace, or // 2. Multiple default namespace are found. (this might be possible by tweaking project file). // The refactoring depends on a single default namespace to operate. var defaultNamespaceFromProjects = new HashSet<string>( documents.Select(d => d.Project.DefaultNamespace), syntaxFacts.StringComparer); if (defaultNamespaceFromProjects.Count != 1 || defaultNamespaceFromProjects.First() == null) { return null; } return defaultNamespaceFromProjects.Single(); } private static string ConcatNamespace(string rootNamespace, string namespaceSuffix) { Debug.Assert(rootNamespace != null && namespaceSuffix != null); if (namespaceSuffix.Length == 0) { return rootNamespace; } else if (rootNamespace.Length == 0) { return namespaceSuffix; } else { return rootNamespace + "." + namespaceSuffix; } } /// <summary> /// Try get the relative namespace for <paramref name="namespace"/> based on <paramref name="relativeTo"/>, /// if <paramref name="relativeTo"/> is the containing namespace of <paramref name="namespace"/>. Otherwise, /// Returns null. /// For example: /// - If <paramref name="relativeTo"/> is "A.B" and <paramref name="namespace"/> is "A.B.C.D", then /// the relative namespace is "C.D". /// - If <paramref name="relativeTo"/> is "A.B" and <paramref name="namespace"/> is also "A.B", then /// the relative namespace is "". /// - If <paramref name="relativeTo"/> is "" then the relative namespace us <paramref name="namespace"/>. /// </summary> private static string GetRelativeNamespace(string relativeTo, string @namespace, ISyntaxFactsService syntaxFacts) { Debug.Assert(relativeTo != null && @namespace != null); if (syntaxFacts.StringComparer.Equals(@namespace, relativeTo)) { return string.Empty; } else if (relativeTo.Length == 0) { return @namespace; } else if (relativeTo.Length >= @namespace.Length) { return null; } var containingText = relativeTo + "."; var namespacePrefix = @namespace.Substring(0, containingText.Length); return syntaxFacts.StringComparer.Equals(containingText, namespacePrefix) ? @namespace[(relativeTo.Length + 1)..] : null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ChangeNamespace; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeRefactorings.SyncNamespace { internal abstract partial class AbstractSyncNamespaceCodeRefactoringProvider<TNamespaceDeclarationSyntax, TCompilationUnitSyntax, TMemberDeclarationSyntax> : CodeRefactoringProvider where TNamespaceDeclarationSyntax : SyntaxNode where TCompilationUnitSyntax : SyntaxNode where TMemberDeclarationSyntax : SyntaxNode { internal sealed class State { /// <summary> /// The document in which the refactoring is triggered. /// </summary> public Document Document { get; } /// <summary> /// The applicable container node based on cursor location, /// which will be used to change namespace. /// </summary> public SyntaxNode Container { get; } /// <summary> /// This is the new name we want to change the namespace to. /// Empty string means global namespace, whereas null means change namespace action is not available. /// </summary> public string TargetNamespace { get; } /// <summary> /// This is the part of the declared namespace that is contained in default namespace. /// We will use this to construct target folder to move the file to. /// For example, if default namespace is `A` and declared namespace is `A.B.C`, /// this would be `B.C`. /// </summary> public string RelativeDeclaredNamespace { get; } private State( Document document, SyntaxNode container, string targetNamespace, string relativeDeclaredNamespace) { Document = document; Container = container; TargetNamespace = targetNamespace; RelativeDeclaredNamespace = relativeDeclaredNamespace; } public static async Task<State> CreateAsync( AbstractSyncNamespaceCodeRefactoringProvider<TNamespaceDeclarationSyntax, TCompilationUnitSyntax, TMemberDeclarationSyntax> provider, Document document, TextSpan textSpan, CancellationToken cancellationToken) { // User must put cursor on one of the nodes described below to trigger the refactoring. // For each scenario, all requirements must be met. Some of them are checked by `TryGetApplicableInvocationNodeAsync`, // rest by `IChangeNamespaceService.CanChangeNamespaceAsync`. // // - A namespace declaration node that is the only namespace declaration in the document and all types are declared in it: // 1. No nested namespace declarations (even it's empty). // 2. The cursor is on the name of the namespace declaration. // 3. The name of the namespace is valid (i.e. no errors). // 4. No partial type declared in the namespace. Otherwise its multiple declaration will // end up in different namespace. // // - A compilation unit node that contains no namespace declaration: // 1. The cursor is on the name of first declared type. // 2. No partial type declared in the document. Otherwise its multiple declaration will // end up in different namespace. var applicableNode = await provider.TryGetApplicableInvocationNodeAsync(document, textSpan, cancellationToken).ConfigureAwait(false); if (applicableNode == null) { return null; } var changeNamespaceService = document.GetLanguageService<IChangeNamespaceService>(); var canChange = await changeNamespaceService.CanChangeNamespaceAsync(document, applicableNode, cancellationToken).ConfigureAwait(false); if (!canChange || !IsDocumentPathRootedInProjectFolder(document)) { return null; } var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); // We can't determine what the expected namespace would be without knowing the default namespace. var defaultNamespace = GetDefaultNamespace(document, syntaxFacts); if (defaultNamespace == null) { return null; } string declaredNamespace; if (applicableNode is TCompilationUnitSyntax) { declaredNamespace = string.Empty; } else if (applicableNode is TNamespaceDeclarationSyntax) { var syntaxGenerator = SyntaxGenerator.GetGenerator(document); declaredNamespace = syntaxGenerator.GetName(applicableNode); } else { throw ExceptionUtilities.Unreachable; } // Namespace can't be changed if we can't construct a valid qualified identifier from folder names. // In this case, we might still be able to provide refactoring to move file to new location. var targetNamespace = PathMetadataUtilities.TryBuildNamespaceFromFolders(document.Folders, syntaxFacts, defaultNamespace); // No action required if namespace already matches folders. if (syntaxFacts.StringComparer.Equals(targetNamespace, declaredNamespace)) { return null; } // Only provide "move file" action if default namespace contains declared namespace. // For example, if the default namespace is `Microsoft.CodeAnalysis`, and declared // namespace is `System.Diagnostics`, it's very likely this document is an outlier // in the project and user probably has some special rule for it. var relativeNamespace = GetRelativeNamespace(defaultNamespace, declaredNamespace, syntaxFacts); return new State(document, applicableNode, targetNamespace, relativeNamespace); } /// <summary> /// Determines if the actual file path matches its logical path in project /// which is constructed as [project_root_path]\Logical\Folders\. The refactoring /// is triggered only when the two match. The reason of doing this is we don't really know /// the user's intention of keeping the file path out-of-sync with its logical path. /// </summary> private static bool IsDocumentPathRootedInProjectFolder(Document document) { var projectRoot = PathUtilities.GetDirectoryName(document.Project.FilePath); var folderPath = Path.Combine(document.Folders.ToArray()); var absoluteDircetoryPath = PathUtilities.GetDirectoryName(document.FilePath); var logicalDirectoryPath = PathUtilities.CombineAbsoluteAndRelativePaths(projectRoot, folderPath); return PathUtilities.PathsEqual(absoluteDircetoryPath, logicalDirectoryPath); } private static string GetDefaultNamespace(Document document, ISyntaxFactsService syntaxFacts) { var solution = document.Project.Solution; var linkedIds = document.GetLinkedDocumentIds(); var documents = linkedIds.SelectAsArray(id => solution.GetDocument(id)).Add(document); // For all projects containing all the linked documents, bail if // 1. Any of them doesn't have default namespace, or // 2. Multiple default namespace are found. (this might be possible by tweaking project file). // The refactoring depends on a single default namespace to operate. var defaultNamespaceFromProjects = new HashSet<string>( documents.Select(d => d.Project.DefaultNamespace), syntaxFacts.StringComparer); if (defaultNamespaceFromProjects.Count != 1 || defaultNamespaceFromProjects.First() == null) { return null; } return defaultNamespaceFromProjects.Single(); } /// <summary> /// Try get the relative namespace for <paramref name="namespace"/> based on <paramref name="relativeTo"/>, /// if <paramref name="relativeTo"/> is the containing namespace of <paramref name="namespace"/>. Otherwise, /// Returns null. /// For example: /// - If <paramref name="relativeTo"/> is "A.B" and <paramref name="namespace"/> is "A.B.C.D", then /// the relative namespace is "C.D". /// - If <paramref name="relativeTo"/> is "A.B" and <paramref name="namespace"/> is also "A.B", then /// the relative namespace is "". /// - If <paramref name="relativeTo"/> is "" then the relative namespace us <paramref name="namespace"/>. /// </summary> private static string GetRelativeNamespace(string relativeTo, string @namespace, ISyntaxFactsService syntaxFacts) { Debug.Assert(relativeTo != null && @namespace != null); if (syntaxFacts.StringComparer.Equals(@namespace, relativeTo)) { return string.Empty; } else if (relativeTo.Length == 0) { return @namespace; } else if (relativeTo.Length >= @namespace.Length) { return null; } var containingText = relativeTo + "."; var namespacePrefix = @namespace.Substring(0, containingText.Length); return syntaxFacts.StringComparer.Equals(containingText, namespacePrefix) ? @namespace[(relativeTo.Length + 1)..] : null; } } } }
1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioWorkspaceImpl.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using EnvDTE; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.MetadataReferences; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Projection; using Roslyn.Utilities; using VSLangProj; using VSLangProj140; using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider; using OleInterop = Microsoft.VisualStudio.OLE.Interop; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { /// <summary> /// The Workspace for running inside Visual Studio. /// </summary> internal abstract partial class VisualStudioWorkspaceImpl : VisualStudioWorkspace { private static readonly IntPtr s_docDataExisting_Unknown = new(-1); private const string AppCodeFolderName = "App_Code"; private readonly IThreadingContext _threadingContext; private readonly ITextBufferFactoryService _textBufferFactoryService; private readonly IProjectionBufferFactoryService _projectionBufferFactoryService; [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] private readonly Lazy<VisualStudioProjectFactory> _projectFactory; private readonly ITextBufferCloneService _textBufferCloneService; private readonly object _gate = new(); /// <summary> /// A <see cref="ForegroundThreadAffinitizedObject"/> to make assertions that stuff is on the right thread. /// </summary> private readonly ForegroundThreadAffinitizedObject _foregroundObject; private ImmutableDictionary<ProjectId, IVsHierarchy?> _projectToHierarchyMap = ImmutableDictionary<ProjectId, IVsHierarchy?>.Empty; private ImmutableDictionary<ProjectId, Guid> _projectToGuidMap = ImmutableDictionary<ProjectId, Guid>.Empty; private ImmutableDictionary<ProjectId, string?> _projectToMaxSupportedLangVersionMap = ImmutableDictionary<ProjectId, string?>.Empty; private ImmutableDictionary<ProjectId, string> _projectToDependencyNodeTargetIdentifier = ImmutableDictionary<ProjectId, string>.Empty; /// <summary> /// A map to fetch the path to a rule set file for a project. This right now is only used to implement /// <see cref="TryGetRuleSetPathForProject(ProjectId)"/> and any other use is extremely suspicious, since direct use of this is out of /// sync with the Workspace if there is active batching happening. /// </summary> private readonly Dictionary<ProjectId, Func<string?>> _projectToRuleSetFilePath = new(); private readonly Dictionary<string, List<VisualStudioProject>> _projectSystemNameToProjectsMap = new(); private readonly Dictionary<string, UIContext?> _languageToProjectExistsUIContext = new(); /// <summary> /// A set of documents that were added by <see cref="VisualStudioProject.AddSourceTextContainer"/>, and aren't otherwise /// tracked for opening/closing. /// </summary> private ImmutableHashSet<DocumentId> _documentsNotFromFiles = ImmutableHashSet<DocumentId>.Empty; /// <summary> /// Indicates whether the current solution is closing. /// </summary> private bool _solutionClosing; [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] internal VisualStudioProjectTracker? _projectTracker; private VirtualMemoryNotificationListener? _memoryListener; private OpenFileTracker? _openFileTracker; internal FileChangeWatcher FileChangeWatcher { get; } internal FileWatchedPortableExecutableReferenceFactory FileWatchedReferenceFactory { get; } private readonly Lazy<IProjectCodeModelFactory> _projectCodeModelFactory; private readonly IEnumerable<Lazy<IDocumentOptionsProviderFactory, OrderableMetadata>> _documentOptionsProviderFactories; private bool _documentOptionsProvidersInitialized = false; private readonly Lazy<ExternalErrorDiagnosticUpdateSource> _lazyExternalErrorDiagnosticUpdateSource; private bool _isExternalErrorDiagnosticUpdateSourceSubscribedToSolutionBuildEvents; public VisualStudioWorkspaceImpl(ExportProvider exportProvider, IAsyncServiceProvider asyncServiceProvider) : base(VisualStudioMefHostServices.Create(exportProvider)) { _threadingContext = exportProvider.GetExportedValue<IThreadingContext>(); _textBufferCloneService = exportProvider.GetExportedValue<ITextBufferCloneService>(); _textBufferFactoryService = exportProvider.GetExportedValue<ITextBufferFactoryService>(); _projectionBufferFactoryService = exportProvider.GetExportedValue<IProjectionBufferFactoryService>(); _projectCodeModelFactory = exportProvider.GetExport<IProjectCodeModelFactory>(); _documentOptionsProviderFactories = exportProvider.GetExports<IDocumentOptionsProviderFactory, OrderableMetadata>(); // We fetch this lazily because VisualStudioProjectFactory depends on VisualStudioWorkspaceImpl -- we have a circularity. Since this // exists right now as a compat shim, we'll just do this. #pragma warning disable CS0618 // Type or member is obsolete _projectFactory = exportProvider.GetExport<VisualStudioProjectFactory>(); #pragma warning restore CS0618 // Type or member is obsolete _foregroundObject = new ForegroundThreadAffinitizedObject(_threadingContext); _textBufferFactoryService.TextBufferCreated += AddTextBufferCloneServiceToBuffer; _projectionBufferFactoryService.ProjectionBufferCreated += AddTextBufferCloneServiceToBuffer; _ = Task.Run(() => InitializeUIAffinitizedServicesAsync(asyncServiceProvider)); FileChangeWatcher = exportProvider.GetExportedValue<FileChangeWatcherProvider>().Watcher; FileWatchedReferenceFactory = exportProvider.GetExportedValue<FileWatchedPortableExecutableReferenceFactory>(); FileWatchedReferenceFactory.ReferenceChanged += this.RefreshMetadataReferencesForFile; _lazyExternalErrorDiagnosticUpdateSource = new Lazy<ExternalErrorDiagnosticUpdateSource>(() => new ExternalErrorDiagnosticUpdateSource( this, exportProvider.GetExportedValue<IDiagnosticAnalyzerService>(), exportProvider.GetExportedValue<IDiagnosticUpdateSourceRegistrationService>(), exportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>(), _threadingContext), isThreadSafe: true); } internal ExternalErrorDiagnosticUpdateSource ExternalErrorDiagnosticUpdateSource => _lazyExternalErrorDiagnosticUpdateSource.Value; internal void SubscribeExternalErrorDiagnosticUpdateSourceToSolutionBuildEvents() { _foregroundObject.AssertIsForeground(); if (_isExternalErrorDiagnosticUpdateSourceSubscribedToSolutionBuildEvents) { return; } // TODO: https://github.com/dotnet/roslyn/issues/36065 // UIContextImpl requires IVsMonitorSelection service: if (ServiceProvider.GlobalProvider.GetService(typeof(IVsMonitorSelection)) == null) { return; } // This pattern ensures that we are called whenever the build starts/completes even if it is already in progress. KnownUIContexts.SolutionBuildingContext.WhenActivated(() => { KnownUIContexts.SolutionBuildingContext.UIContextChanged += (object _, UIContextChangedEventArgs e) => { if (e.Activated) { ExternalErrorDiagnosticUpdateSource.OnSolutionBuildStarted(); } else { ExternalErrorDiagnosticUpdateSource.OnSolutionBuildCompleted(); } }; ExternalErrorDiagnosticUpdateSource.OnSolutionBuildStarted(); }); _isExternalErrorDiagnosticUpdateSourceSubscribedToSolutionBuildEvents = true; } public async Task InitializeUIAffinitizedServicesAsync(IAsyncServiceProvider asyncServiceProvider) { // Create services that are bound to the UI thread await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(_threadingContext.DisposalToken); var solutionClosingContext = UIContext.FromUIContextGuid(VSConstants.UICONTEXT.SolutionClosing_guid); solutionClosingContext.UIContextChanged += (_, e) => _solutionClosing = e.Activated; var openFileTracker = await OpenFileTracker.CreateAsync(this, asyncServiceProvider).ConfigureAwait(true); // Update our fields first, so any asynchronous work that needs to use these is able to see the service. lock (_gate) { _openFileTracker = openFileTracker; } var memoryListener = await VirtualMemoryNotificationListener.CreateAsync(this, _threadingContext, asyncServiceProvider, _threadingContext.DisposalToken).ConfigureAwait(true); // Update our fields first, so any asynchronous work that needs to use these is able to see the service. lock (_gate) { _memoryListener = memoryListener; } openFileTracker.ProcessQueuedWorkOnUIThread(); } public void QueueCheckForFilesBeingOpen(ImmutableArray<string> newFileNames) => _openFileTracker?.QueueCheckForFilesBeingOpen(newFileNames); public void ProcessQueuedWorkOnUIThread() => _openFileTracker?.ProcessQueuedWorkOnUIThread(); internal void AddProjectToInternalMaps(VisualStudioProject project, IVsHierarchy? hierarchy, Guid guid, string projectSystemName) { lock (_gate) { _projectToHierarchyMap = _projectToHierarchyMap.Add(project.Id, hierarchy); _projectToGuidMap = _projectToGuidMap.Add(project.Id, guid); _projectSystemNameToProjectsMap.MultiAdd(projectSystemName, project); } } internal void AddProjectRuleSetFileToInternalMaps(VisualStudioProject project, Func<string?> ruleSetFilePathFunc) { lock (_gate) { _projectToRuleSetFilePath.Add(project.Id, ruleSetFilePathFunc); } } internal void AddDocumentToDocumentsNotFromFiles(DocumentId documentId) { lock (_gate) { _documentsNotFromFiles = _documentsNotFromFiles.Add(documentId); } } internal void RemoveDocumentToDocumentsNotFromFiles(DocumentId documentId) { lock (_gate) { _documentsNotFromFiles = _documentsNotFromFiles.Remove(documentId); } } [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] internal VisualStudioProjectTracker GetProjectTrackerAndInitializeIfNecessary() { if (_projectTracker == null) { _projectTracker = new VisualStudioProjectTracker(this, _projectFactory.Value, _threadingContext); } return _projectTracker; } [Obsolete("This is a compatibility shim for TypeScript and F#; please do not use it.")] internal VisualStudioProjectTracker ProjectTracker { get { return GetProjectTrackerAndInitializeIfNecessary(); } } internal ContainedDocument? TryGetContainedDocument(DocumentId documentId) { // TODO: move everybody off of this instance method and replace them with calls to // ContainedDocument.TryGetContainedDocument return ContainedDocument.TryGetContainedDocument(documentId); } internal VisualStudioProject? GetProjectWithHierarchyAndName(IVsHierarchy hierarchy, string projectName) { lock (_gate) { if (_projectSystemNameToProjectsMap.TryGetValue(projectName, out var projects)) { foreach (var project in projects) { if (_projectToHierarchyMap.TryGetValue(project.Id, out var projectHierarchy)) { if (projectHierarchy == hierarchy) { return project; } } } } } return null; } // TODO: consider whether this should be going to the project system directly to get this path. This is only called on interactions from the // Solution Explorer in the SolutionExplorerShim, where if we just could more directly get to the rule set file it'd simplify this. internal override string? TryGetRuleSetPathForProject(ProjectId projectId) { lock (_gate) { if (_projectToRuleSetFilePath.TryGetValue(projectId, out var ruleSetPathFunc)) { return ruleSetPathFunc(); } else { return null; } } } [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] internal IVisualStudioHostDocument? GetHostDocument(DocumentId documentId) { // TypeScript only calls this to immediately check if the document is a ContainedDocument. Because of that we can just check for // ContainedDocuments return ContainedDocument.TryGetContainedDocument(documentId); } public override EnvDTE.FileCodeModel GetFileCodeModel(DocumentId documentId) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } var documentFilePath = GetFilePath(documentId); if (documentFilePath == null) { throw new ArgumentException(ServicesVSResources.The_given_DocumentId_did_not_come_from_the_Visual_Studio_workspace, nameof(documentId)); } return _projectCodeModelFactory.Value.GetOrCreateFileCodeModel(documentId.ProjectId, documentFilePath); } internal override bool TryApplyChanges( Microsoft.CodeAnalysis.Solution newSolution, IProgressTracker progressTracker) { if (!_foregroundObject.IsForeground()) { throw new InvalidOperationException(ServicesVSResources.VisualStudioWorkspace_TryApplyChanges_cannot_be_called_from_a_background_thread); } var currentSolution = this.CurrentSolution; var projectChanges = newSolution.GetChanges(currentSolution).GetProjectChanges().ToList(); // first make sure we can edit the document we will be updating (check them out from source control, etc) var changedDocs = projectChanges.SelectMany(pd => pd.GetChangedDocuments(onlyGetDocumentsWithTextChanges: true).Concat(pd.GetChangedAdditionalDocuments())) .Where(CanApplyChange).ToList(); if (changedDocs.Count > 0) { this.EnsureEditableDocuments(changedDocs); } return base.TryApplyChanges(newSolution, progressTracker); bool CanApplyChange(DocumentId documentId) { var document = newSolution.GetDocument(documentId) ?? currentSolution.GetDocument(documentId); if (document == null) { // we can have null if documentId is for additional files return true; } return document.CanApplyChange(); } } public override bool CanOpenDocuments { get { return true; } } internal override bool CanChangeActiveContextDocument { get { return true; } } internal bool IsCPSProject(CodeAnalysis.Project project) => IsCPSProject(project.Id); internal bool IsCPSProject(ProjectId projectId) { _foregroundObject.AssertIsForeground(); if (this.TryGetHierarchy(projectId, out var hierarchy)) { return hierarchy.IsCapabilityMatch("CPS"); } return false; } internal bool IsPrimaryProject(ProjectId projectId) { lock (_gate) { foreach (var (_, projects) in _projectSystemNameToProjectsMap) { foreach (var project in projects) { if (project.Id == projectId) return project.IsPrimary; } } } return true; } protected override bool CanApplyCompilationOptionChange(CompilationOptions oldOptions, CompilationOptions newOptions, CodeAnalysis.Project project) => project.LanguageServices.GetRequiredService<ICompilationOptionsChangingService>().CanApplyChange(oldOptions, newOptions); public override bool CanApplyParseOptionChange(ParseOptions oldOptions, ParseOptions newOptions, CodeAnalysis.Project project) { _projectToMaxSupportedLangVersionMap.TryGetValue(project.Id, out var maxSupportLangVersion); return project.LanguageServices.GetRequiredService<IParseOptionsChangingService>().CanApplyChange(oldOptions, newOptions, maxSupportLangVersion); } private void AddTextBufferCloneServiceToBuffer(object sender, TextBufferCreatedEventArgs e) => e.TextBuffer.Properties.AddProperty(typeof(ITextBufferCloneService), _textBufferCloneService); public override bool CanApplyChange(ApplyChangesKind feature) { switch (feature) { case ApplyChangesKind.AddDocument: case ApplyChangesKind.RemoveDocument: case ApplyChangesKind.ChangeDocument: case ApplyChangesKind.AddMetadataReference: case ApplyChangesKind.RemoveMetadataReference: case ApplyChangesKind.AddProjectReference: case ApplyChangesKind.RemoveProjectReference: case ApplyChangesKind.AddAnalyzerReference: case ApplyChangesKind.RemoveAnalyzerReference: case ApplyChangesKind.AddAdditionalDocument: case ApplyChangesKind.RemoveAdditionalDocument: case ApplyChangesKind.ChangeAdditionalDocument: case ApplyChangesKind.ChangeCompilationOptions: case ApplyChangesKind.ChangeParseOptions: case ApplyChangesKind.ChangeDocumentInfo: case ApplyChangesKind.AddAnalyzerConfigDocument: case ApplyChangesKind.RemoveAnalyzerConfigDocument: case ApplyChangesKind.ChangeAnalyzerConfigDocument: case ApplyChangesKind.AddSolutionAnalyzerReference: case ApplyChangesKind.RemoveSolutionAnalyzerReference: return true; default: return false; } } private bool TryGetProjectData(ProjectId projectId, [NotNullWhen(returnValue: true)] out IVsHierarchy? hierarchy, [NotNullWhen(returnValue: true)] out EnvDTE.Project? project) { project = null; return this.TryGetHierarchy(projectId, out hierarchy) && hierarchy.TryGetProject(out project); } internal void GetProjectData(ProjectId projectId, out IVsHierarchy hierarchy, out EnvDTE.Project project) { if (!TryGetProjectData(projectId, out hierarchy!, out project!)) { throw new ArgumentException(string.Format(ServicesVSResources.Could_not_find_project_0, projectId)); } } internal EnvDTE.Project? TryGetDTEProject(ProjectId projectId) => TryGetProjectData(projectId, out var _, out var project) ? project : null; internal bool TryAddReferenceToProject(ProjectId projectId, string assemblyName) { if (!TryGetProjectData(projectId, out _, out var project)) { return false; } var vsProject = (VSProject)project.Object; try { vsProject.References.Add(assemblyName); } catch (Exception) { return false; } return true; } private string? GetAnalyzerPath(AnalyzerReference analyzerReference) => analyzerReference.FullPath; protected override void ApplyCompilationOptionsChanged(ProjectId projectId, CompilationOptions options) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } var compilationOptionsService = CurrentSolution.GetRequiredProject(projectId).LanguageServices.GetRequiredService<ICompilationOptionsChangingService>(); var storage = ProjectPropertyStorage.Create(TryGetDTEProject(projectId), ServiceProvider.GlobalProvider); compilationOptionsService.Apply(options, storage); } protected override void ApplyParseOptionsChanged(ProjectId projectId, ParseOptions options) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } var parseOptionsService = CurrentSolution.GetRequiredProject(projectId).LanguageServices.GetRequiredService<IParseOptionsChangingService>(); var storage = ProjectPropertyStorage.Create(TryGetDTEProject(projectId), ServiceProvider.GlobalProvider); parseOptionsService.Apply(options, storage); } protected override void ApplyAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (analyzerReference == null) { throw new ArgumentNullException(nameof(analyzerReference)); } GetProjectData(projectId, out _, out var project); var filePath = GetAnalyzerPath(analyzerReference); if (filePath != null) { var vsProject = (VSProject3)project.Object; vsProject.AnalyzerReferences.Add(filePath); } } protected override void ApplyAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (analyzerReference == null) { throw new ArgumentNullException(nameof(analyzerReference)); } GetProjectData(projectId, out _, out var project); var filePath = GetAnalyzerPath(analyzerReference); if (filePath != null) { var vsProject = (VSProject3)project.Object; vsProject.AnalyzerReferences.Remove(filePath); } } private string? GetMetadataPath(MetadataReference metadataReference) { if (metadataReference is PortableExecutableReference fileMetadata) { return fileMetadata.FilePath; } return null; } protected override void ApplyMetadataReferenceAdded( ProjectId projectId, MetadataReference metadataReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (metadataReference == null) { throw new ArgumentNullException(nameof(metadataReference)); } GetProjectData(projectId, out _, out var project); var filePath = GetMetadataPath(metadataReference); if (filePath != null) { var vsProject = (VSProject)project.Object; vsProject.References.Add(filePath); var undoManager = TryGetUndoManager(); undoManager?.Add(new RemoveMetadataReferenceUndoUnit(this, projectId, filePath)); } } protected override void ApplyMetadataReferenceRemoved( ProjectId projectId, MetadataReference metadataReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (metadataReference == null) { throw new ArgumentNullException(nameof(metadataReference)); } GetProjectData(projectId, out _, out var project); var filePath = GetMetadataPath(metadataReference); if (filePath != null) { var vsProject = (VSProject)project.Object; foreach (Reference reference in vsProject.References) { if (StringComparer.OrdinalIgnoreCase.Equals(reference.Path, filePath)) { reference.Remove(); var undoManager = TryGetUndoManager(); undoManager?.Add(new AddMetadataReferenceUndoUnit(this, projectId, filePath)); break; } } } } internal override void ApplyMappedFileChanges(SolutionChanges solutionChanges) { // Get the original text changes from all documents and call the span mapping service to get span mappings for the text changes. // Create mapped text changes using the mapped spans and original text changes' text. // Mappings for opened razor files are retrieved via the LSP client making a request to the razor server. // If we wait for the result on the UI thread, we will hit a bug in the LSP client that brings us to a code path // using ConfigureAwait(true). This deadlocks as it then attempts to return to the UI thread which is already blocked by us. // Instead, we invoke this in JTF run which will mitigate deadlocks when the ConfigureAwait(true) // tries to switch back to the main thread in the LSP client. // Link to LSP client bug for ConfigureAwait(true) - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1216657 var mappedChanges = _threadingContext.JoinableTaskFactory.Run(() => GetMappedTextChanges(solutionChanges)); // Group the mapped text changes by file, then apply all mapped text changes for the file. foreach (var changesForFile in mappedChanges) { // It doesn't matter which of the file's projectIds we pass to the invisible editor, so just pick the first. var projectId = changesForFile.Value.First().ProjectId; // Make sure we only take distinct changes - we'll have duplicates from different projects for linked files or multi-targeted files. var distinctTextChanges = changesForFile.Value.Select(change => change.TextChange).Distinct().ToImmutableArray(); using var invisibleEditor = new InvisibleEditor(ServiceProvider.GlobalProvider, changesForFile.Key, GetHierarchy(projectId), needsSave: true, needsUndoDisabled: false); TextEditApplication.UpdateText(distinctTextChanges, invisibleEditor.TextBuffer, EditOptions.None); } return; async Task<MultiDictionary<string, (TextChange TextChange, ProjectId ProjectId)>> GetMappedTextChanges(SolutionChanges solutionChanges) { var filePathToMappedTextChanges = new MultiDictionary<string, (TextChange TextChange, ProjectId ProjectId)>(); foreach (var projectChanges in solutionChanges.GetProjectChanges()) { foreach (var changedDocumentId in projectChanges.GetChangedDocuments()) { var oldDocument = projectChanges.OldProject.GetRequiredDocument(changedDocumentId); if (!ShouldApplyChangesToMappedDocuments(oldDocument, out var mappingService)) { continue; } var newDocument = projectChanges.NewProject.GetRequiredDocument(changedDocumentId); var mappedTextChanges = await mappingService.GetMappedTextChangesAsync( oldDocument, newDocument, CancellationToken.None).ConfigureAwait(false); foreach (var (filePath, textChange) in mappedTextChanges) { filePathToMappedTextChanges.Add(filePath, (textChange, projectChanges.ProjectId)); } } } return filePathToMappedTextChanges; } bool ShouldApplyChangesToMappedDocuments(CodeAnalysis.Document document, [NotNullWhen(true)] out ISpanMappingService? spanMappingService) { spanMappingService = document.Services.GetService<ISpanMappingService>(); // Only consider files that are mapped and that we are unable to apply changes to. // TODO - refactor how this is determined - https://github.com/dotnet/roslyn/issues/47908 return spanMappingService != null && document?.CanApplyChange() == false; } } protected override void ApplyProjectReferenceAdded( ProjectId projectId, ProjectReference projectReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } GetProjectData(projectId, out _, out var project); GetProjectData(projectReference.ProjectId, out _, out var refProject); var vsProject = (VSProject)project.Object; vsProject.References.AddProject(refProject); var undoManager = TryGetUndoManager(); undoManager?.Add(new RemoveProjectReferenceUndoUnit( this, projectId, projectReference.ProjectId)); } private OleInterop.IOleUndoManager? TryGetUndoManager() { var documentTrackingService = this.Services.GetRequiredService<IDocumentTrackingService>(); var documentId = documentTrackingService.TryGetActiveDocument() ?? documentTrackingService.GetVisibleDocuments().FirstOrDefault(); if (documentId != null) { var composition = (IComponentModel)ServiceProvider.GlobalProvider.GetService(typeof(SComponentModel)); var exportProvider = composition.DefaultExportProvider; var editorAdaptersService = exportProvider.GetExportedValue<IVsEditorAdaptersFactoryService>(); return editorAdaptersService.TryGetUndoManager(this, documentId, CancellationToken.None); } return null; } protected override void ApplyProjectReferenceRemoved( ProjectId projectId, ProjectReference projectReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } GetProjectData(projectId, out _, out var project); GetProjectData(projectReference.ProjectId, out _, out var refProject); var vsProject = (VSProject)project.Object; foreach (Reference reference in vsProject.References) { if (reference.SourceProject == refProject) { reference.Remove(); var undoManager = TryGetUndoManager(); undoManager?.Add(new AddProjectReferenceUndoUnit(this, projectId, projectReference.ProjectId)); } } } protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text) => AddDocumentCore(info, text, TextDocumentKind.Document); protected override void ApplyAdditionalDocumentAdded(DocumentInfo info, SourceText text) => AddDocumentCore(info, text, TextDocumentKind.AdditionalDocument); protected override void ApplyAnalyzerConfigDocumentAdded(DocumentInfo info, SourceText text) => AddDocumentCore(info, text, TextDocumentKind.AnalyzerConfigDocument); private void AddDocumentCore(DocumentInfo info, SourceText initialText, TextDocumentKind documentKind) { GetProjectData(info.Id.ProjectId, out _, out var project); // If the first namespace name matches the name of the project, then we don't want to // generate a folder for that. The project is implicitly a folder with that name. var folders = info.Folders.AsEnumerable(); if (folders.FirstOrDefault() == project.Name) { folders = folders.Skip(1); } folders = FilterFolderForProjectType(project, folders); if (IsWebsite(project)) { AddDocumentToFolder(project, info.Id, SpecializedCollections.SingletonEnumerable(AppCodeFolderName), info.Name, documentKind, initialText, info.FilePath); } else if (folders.Any()) { AddDocumentToFolder(project, info.Id, folders, info.Name, documentKind, initialText, info.FilePath); } else { AddDocumentToProject(project, info.Id, info.Name, documentKind, initialText, info.FilePath); } var undoManager = TryGetUndoManager(); switch (documentKind) { case TextDocumentKind.AdditionalDocument: undoManager?.Add(new RemoveAdditionalDocumentUndoUnit(this, info.Id)); break; case TextDocumentKind.AnalyzerConfigDocument: undoManager?.Add(new RemoveAnalyzerConfigDocumentUndoUnit(this, info.Id)); break; case TextDocumentKind.Document: undoManager?.Add(new RemoveDocumentUndoUnit(this, info.Id)); break; default: throw ExceptionUtilities.UnexpectedValue(documentKind); } } private bool IsWebsite(EnvDTE.Project project) => project.Kind == VsWebSite.PrjKind.prjKindVenusProject; private IEnumerable<string> FilterFolderForProjectType(EnvDTE.Project project, IEnumerable<string> folders) { foreach (var folder in folders) { var items = GetAllItems(project.ProjectItems); var folderItem = items.FirstOrDefault(p => StringComparer.OrdinalIgnoreCase.Compare(p.Name, folder) == 0); if (folderItem == null || folderItem.Kind != EnvDTE.Constants.vsProjectItemKindPhysicalFile) { yield return folder; } } } private IEnumerable<ProjectItem> GetAllItems(ProjectItems projectItems) { if (projectItems == null) { return SpecializedCollections.EmptyEnumerable<ProjectItem>(); } var items = projectItems.OfType<ProjectItem>(); return items.Concat(items.SelectMany(i => GetAllItems(i.ProjectItems))); } #if false protected override void AddExistingDocument(DocumentId documentId, string filePath, IEnumerable<string> folders) { IVsHierarchy hierarchy; EnvDTE.Project project; IVisualStudioHostProject hostProject; GetProjectData(documentId.ProjectId, out hostProject, out hierarchy, out project); // If the first namespace name matches the name of the project, then we don't want to // generate a folder for that. The project is implicitly a folder with that name. if (folders.FirstOrDefault() == project.Name) { folders = folders.Skip(1); } var name = Path.GetFileName(filePath); if (folders.Any()) { AddDocumentToFolder(hostProject, project, documentId, folders, name, SourceCodeKind.Regular, initialText: null, filePath: filePath); } else { AddDocumentToProject(hostProject, project, documentId, name, SourceCodeKind.Regular, initialText: null, filePath: filePath); } } #endif private ProjectItem AddDocumentToProject( EnvDTE.Project project, DocumentId documentId, string documentName, TextDocumentKind documentKind, SourceText? initialText = null, string? filePath = null) { string? folderPath = null; if (filePath == null && !project.TryGetFullPath(out folderPath)) { // TODO(cyrusn): Throw an appropriate exception here. throw new Exception(ServicesVSResources.Could_not_find_location_of_folder_on_disk); } return AddDocumentToProjectItems(project.ProjectItems, documentId, folderPath, documentName, initialText, filePath, documentKind); } private ProjectItem AddDocumentToFolder( EnvDTE.Project project, DocumentId documentId, IEnumerable<string> folders, string documentName, TextDocumentKind documentKind, SourceText? initialText = null, string? filePath = null) { var folder = project.FindOrCreateFolder(folders); string? folderPath = null; if (filePath == null && !folder.TryGetFullPath(out folderPath)) { // TODO(cyrusn): Throw an appropriate exception here. throw new Exception(ServicesVSResources.Could_not_find_location_of_folder_on_disk); } return AddDocumentToProjectItems(folder.ProjectItems, documentId, folderPath, documentName, initialText, filePath, documentKind); } private ProjectItem AddDocumentToProjectItems( ProjectItems projectItems, DocumentId documentId, string? folderPath, string documentName, SourceText? initialText, string? filePath, TextDocumentKind documentKind) { if (filePath == null) { Contract.ThrowIfNull(folderPath, "If we didn't have a file path, then we expected a folder path to generate the file path from."); var baseName = Path.GetFileNameWithoutExtension(documentName); var extension = documentKind == TextDocumentKind.Document ? GetPreferredExtension(documentId) : Path.GetExtension(documentName); var uniqueName = projectItems.GetUniqueName(baseName, extension); filePath = Path.Combine(folderPath, uniqueName); } if (initialText != null) { using var writer = new StreamWriter(filePath, append: false, encoding: initialText.Encoding ?? Encoding.UTF8); initialText.Write(writer); } // TODO: restore document ID hinting -- we previously ensured that the AddFromFile will introduce the document ID being used here. // (tracked by https://devdiv.visualstudio.com/DevDiv/_workitems/edit/677956) return projectItems.AddFromFile(filePath); } private void RemoveDocumentCore(DocumentId documentId, TextDocumentKind documentKind) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } var document = this.CurrentSolution.GetTextDocument(documentId); if (document != null) { var hierarchy = this.GetHierarchy(documentId.ProjectId); Contract.ThrowIfNull(hierarchy, "Removing files from projects without hierarchies are not supported."); var text = document.GetTextSynchronously(CancellationToken.None); Contract.ThrowIfNull(document.FilePath, "Removing files from projects that don't have file names are not supported."); var itemId = hierarchy.TryGetItemId(document.FilePath); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // it is no longer part of the solution return; } var project = (IVsProject3)hierarchy; project.RemoveItem(0, itemId, out _); var undoManager = TryGetUndoManager(); var docInfo = CreateDocumentInfoWithoutText(document); switch (documentKind) { case TextDocumentKind.AdditionalDocument: undoManager?.Add(new AddAdditionalDocumentUndoUnit(this, docInfo, text)); break; case TextDocumentKind.AnalyzerConfigDocument: undoManager?.Add(new AddAnalyzerConfigDocumentUndoUnit(this, docInfo, text)); break; case TextDocumentKind.Document: undoManager?.Add(new AddDocumentUndoUnit(this, docInfo, text)); break; default: throw ExceptionUtilities.UnexpectedValue(documentKind); } } } protected override void ApplyDocumentRemoved(DocumentId documentId) => RemoveDocumentCore(documentId, TextDocumentKind.Document); protected override void ApplyAdditionalDocumentRemoved(DocumentId documentId) => RemoveDocumentCore(documentId, TextDocumentKind.AdditionalDocument); protected override void ApplyAnalyzerConfigDocumentRemoved(DocumentId documentId) => RemoveDocumentCore(documentId, TextDocumentKind.AnalyzerConfigDocument); public override void OpenDocument(DocumentId documentId, bool activate = true) => OpenDocumentCore(documentId, activate); public override void OpenAdditionalDocument(DocumentId documentId, bool activate = true) => OpenDocumentCore(documentId, activate); public override void OpenAnalyzerConfigDocument(DocumentId documentId, bool activate = true) => OpenDocumentCore(documentId, activate); public override void CloseDocument(DocumentId documentId) => CloseDocumentCore(documentId); public override void CloseAdditionalDocument(DocumentId documentId) => CloseDocumentCore(documentId); public override void CloseAnalyzerConfigDocument(DocumentId documentId) => CloseDocumentCore(documentId); public void OpenDocumentCore(DocumentId documentId, bool activate = true) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } if (!_foregroundObject.IsForeground()) { throw new InvalidOperationException(ServicesVSResources.This_workspace_only_supports_opening_documents_on_the_UI_thread); } var document = this.CurrentSolution.GetTextDocument(documentId); if (document != null) { OpenDocumentFromPath(document.FilePath, document.Project.Id, activate); } } internal void OpenDocumentFromPath(string? filePath, ProjectId projectId, bool activate = true) { if (TryGetFrame(filePath, projectId, out var frame)) { if (activate) { frame.Show(); } else { frame.ShowNoActivate(); } } } /// <summary> /// Opens a file and retrieves the window frame. /// </summary> /// <param name="filePath">the file path of the file to open.</param> /// <param name="projectId">used to retrieve the IVsHierarchy to ensure the file is opened in a matching context.</param> /// <param name="frame">the window frame.</param> /// <returns></returns> private bool TryGetFrame(string? filePath, ProjectId projectId, [NotNullWhen(returnValue: true)] out IVsWindowFrame? frame) { frame = null; if (filePath == null) { return false; } var hierarchy = GetHierarchy(projectId); var itemId = hierarchy?.TryGetItemId(filePath) ?? (uint)VSConstants.VSITEMID.Nil; if (itemId == (uint)VSConstants.VSITEMID.Nil) { // If the ItemId is Nil, then IVsProject would not be able to open the // document using its ItemId. Thus, we must use OpenDocumentViaProject, which only // depends on the file path. var openDocumentService = IServiceProviderExtensions.GetService<SVsUIShellOpenDocument, IVsUIShellOpenDocument>(ServiceProvider.GlobalProvider); return ErrorHandler.Succeeded(openDocumentService.OpenDocumentViaProject( filePath, VSConstants.LOGVIEWID.TextView_guid, out _, out _, out _, out frame)); } else { // If the ItemId is not Nil, then we should not call IVsUIShellDocument // .OpenDocumentViaProject here because that simply takes a file path and opens the // file within the context of the first project it finds. That would cause problems // if the document we're trying to open is actually a linked file in another // project. So, we get the project's hierarchy and open the document using its item // ID. // It's conceivable that IVsHierarchy might not implement IVsProject. However, // OpenDocumentViaProject itself relies upon this QI working, so it should be OK to // use here. return hierarchy is IVsProject vsProject && ErrorHandler.Succeeded(vsProject.OpenItem(itemId, VSConstants.LOGVIEWID.TextView_guid, s_docDataExisting_Unknown, out frame)); } } public void CloseDocumentCore(DocumentId documentId) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } if (this.IsDocumentOpen(documentId)) { var filePath = this.GetFilePath(documentId); if (filePath != null) { var openDocumentService = IServiceProviderExtensions.GetService<SVsUIShellOpenDocument, IVsUIShellOpenDocument>(ServiceProvider.GlobalProvider); if (ErrorHandler.Succeeded(openDocumentService.IsDocumentOpen(null, 0, filePath, Guid.Empty, 0, out _, null, out var frame, out _))) { // TODO: do we need save argument for CloseDocument? frame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave); } } } } protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText newText) => ApplyTextDocumentChange(documentId, newText); protected override void ApplyAdditionalDocumentTextChanged(DocumentId documentId, SourceText newText) => ApplyTextDocumentChange(documentId, newText); protected override void ApplyAnalyzerConfigDocumentTextChanged(DocumentId documentId, SourceText newText) => ApplyTextDocumentChange(documentId, newText); private void ApplyTextDocumentChange(DocumentId documentId, SourceText newText) { EnsureEditableDocuments(documentId); var containedDocument = TryGetContainedDocument(documentId); if (containedDocument != null) { containedDocument.UpdateText(newText); } else { if (IsDocumentOpen(documentId)) { var textBuffer = this.CurrentSolution.GetTextDocument(documentId)!.GetTextSynchronously(CancellationToken.None).Container.TryGetTextBuffer(); if (textBuffer != null) { TextEditApplication.UpdateText(newText, textBuffer, EditOptions.DefaultMinimalChange); return; } } // The document wasn't open in a normal way, so invisible editor time using var invisibleEditor = OpenInvisibleEditor(documentId); TextEditApplication.UpdateText(newText, invisibleEditor.TextBuffer, EditOptions.None); } } protected override void ApplyDocumentInfoChanged(DocumentId documentId, DocumentInfo updatedInfo) { var document = CurrentSolution.GetRequiredDocument(documentId); FailIfDocumentInfoChangesNotSupported(document, updatedInfo); if (document.Name != updatedInfo.Name) { GetProjectData(updatedInfo.Id.ProjectId, out var _, out var dteProject); if (document.FilePath == null) { FatalError.ReportAndCatch(new Exception("Attempting to change the information of a document without a file path.")); return; } var projectItemForDocument = dteProject.FindItemByPath(document.FilePath, StringComparer.OrdinalIgnoreCase); if (projectItemForDocument == null) { // TODO(https://github.com/dotnet/roslyn/issues/34276): Debug.Fail("Attempting to change the name of a file in a Shared Project"); return; } // Must save the document first for things like Breakpoints to be preserved. // WORKAROUND: Check if the document needs to be saved before calling save. // Should remove the if below and just call save() once // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1163405 // is fixed if (!projectItemForDocument.Saved) { projectItemForDocument.Save(); } var uniqueName = projectItemForDocument.Collection .GetUniqueNameIgnoringProjectItem( projectItemForDocument, Path.GetFileNameWithoutExtension(updatedInfo.Name), Path.GetExtension(updatedInfo.Name)); // Get the current undoManager before any file renames/documentId changes happen var undoManager = TryGetUndoManager(); // By setting this property, Visual Studio will perform the file rename, which // will cause the workspace's current solution to update and will fire the // necessary workspace changed events. projectItemForDocument.Name = uniqueName; if (projectItemForDocument.TryGetFullPath(out var newPath)) { undoManager?.Add(new RenameDocumentUndoUnit(this, uniqueName, document.Name, newPath)); } } } /// <summary> /// The <see cref="VisualStudioWorkspace"/> currently supports only a subset of <see cref="DocumentInfo"/> /// changes. /// </summary> private void FailIfDocumentInfoChangesNotSupported(CodeAnalysis.Document document, DocumentInfo updatedInfo) { if (document.SourceCodeKind != updatedInfo.SourceCodeKind) { throw new InvalidOperationException( $"This Workspace does not support changing a document's {nameof(document.SourceCodeKind)}."); } if (document.FilePath != updatedInfo.FilePath) { throw new InvalidOperationException( $"This Workspace does not support changing a document's {nameof(document.FilePath)}."); } if (document.Id != updatedInfo.Id) { throw new InvalidOperationException( $"This Workspace does not support changing a document's {nameof(document.Id)}."); } if (document.Folders != updatedInfo.Folders) { throw new InvalidOperationException( $"This Workspace does not support changing a document's {nameof(document.Folders)}."); } if (document.State.Attributes.IsGenerated != updatedInfo.IsGenerated) { throw new InvalidOperationException( $"This Workspace does not support changing a document's {nameof(document.State.Attributes.IsGenerated)} state."); } } private string GetPreferredExtension(DocumentId documentId) { // No extension was provided. Pick a good one based on the type of host project. return CurrentSolution.GetRequiredProject(documentId.ProjectId).Language switch { // TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325 //return sourceCodeKind == SourceCodeKind.Regular ? ".cs" : ".csx"; LanguageNames.CSharp => ".cs", // TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325 //return sourceCodeKind == SourceCodeKind.Regular ? ".vb" : ".vbx"; LanguageNames.VisualBasic => ".vb", _ => throw new InvalidOperationException(), }; } public override IVsHierarchy? GetHierarchy(ProjectId projectId) { // This doesn't take a lock since _projectToHierarchyMap is immutable return _projectToHierarchyMap.GetValueOrDefault(projectId, defaultValue: null); } internal override Guid GetProjectGuid(ProjectId projectId) { // This doesn't take a lock since _projectToGuidMap is immutable return _projectToGuidMap.GetValueOrDefault(projectId, defaultValue: Guid.Empty); } internal string? TryGetDependencyNodeTargetIdentifier(ProjectId projectId) { // This doesn't take a lock since _projectToDependencyNodeTargetIdentifier is immutable _projectToDependencyNodeTargetIdentifier.TryGetValue(projectId, out var identifier); return identifier; } internal override void SetDocumentContext(DocumentId documentId) { _foregroundObject.AssertIsForeground(); // Note: this method does not actually call into any workspace code here to change the workspace's context. The assumption is updating the running document table or // IVsHierarchies will raise the appropriate events which we are subscribed to. lock (_gate) { var hierarchy = GetHierarchy(documentId.ProjectId); if (hierarchy == null) { // If we don't have a hierarchy then there's nothing we can do return; } // The hierarchy might be supporting multitargeting; in that case, let's update the context. Unfortunately the IVsHierarchies that support this // don't necessarily let us read it first, so we have to fire-and-forget here. foreach (var (projectSystemName, projects) in _projectSystemNameToProjectsMap) { if (projects.Any(p => p.Id == documentId.ProjectId)) { hierarchy.SetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID8.VSHPROPID_ActiveIntellisenseProjectContext, projectSystemName); // We've updated that property, but we still need to continue the rest of this process to ensure the Running Document Table is updated // and any shared asset projects are also updated. break; } } var filePath = GetFilePath(documentId); if (filePath == null) { return; } var itemId = hierarchy.TryGetItemId(filePath); if (itemId != VSConstants.VSITEMID_NIL) { // Is this owned by a shared asset project? If so, we need to put the shared asset project into the running document table, and need to set the // current hierarchy as the active context of that shared hierarchy. This is kept as a loop that we do multiple times in the case that you // have multiple pointers. This used to be the case for multitargeting projects, but that was now handled by setting the active context property // above. Some project systems out there might still be supporting it, so we'll support it too. while (SharedProjectUtilities.TryGetItemInSharedAssetsProject(hierarchy, itemId, out var sharedHierarchy, out var sharedItemId) && hierarchy != sharedHierarchy) { // Ensure the shared context is set correctly if (sharedHierarchy.GetActiveProjectContext() != hierarchy) { ErrorHandler.ThrowOnFailure(sharedHierarchy.SetActiveProjectContext(hierarchy)); } // We now need to ensure the outer project is also set up hierarchy = sharedHierarchy; itemId = sharedItemId; } } // Update the ownership of the file in the Running Document Table var project = (IVsProject3)hierarchy; project.TransferItem(filePath, filePath, punkWindowFrame: null); } } internal bool TryGetHierarchy(ProjectId projectId, [NotNullWhen(returnValue: true)] out IVsHierarchy? hierarchy) { hierarchy = this.GetHierarchy(projectId); return hierarchy != null; } protected override void Dispose(bool finalize) { if (!finalize) { _textBufferFactoryService.TextBufferCreated -= AddTextBufferCloneServiceToBuffer; _projectionBufferFactoryService.ProjectionBufferCreated -= AddTextBufferCloneServiceToBuffer; FileWatchedReferenceFactory.ReferenceChanged -= RefreshMetadataReferencesForFile; if (_lazyExternalErrorDiagnosticUpdateSource.IsValueCreated) { _lazyExternalErrorDiagnosticUpdateSource.Value.Dispose(); } } base.Dispose(finalize); } public void EnsureEditableDocuments(IEnumerable<DocumentId> documents) { var queryEdit = (IVsQueryEditQuerySave2)ServiceProvider.GlobalProvider.GetService(typeof(SVsQueryEditQuerySave)); // make sure given document id actually exist in current solution and the file is marked as supporting modifications // and actually has non null file path var fileNames = documents.Select(GetFilePath).ToArray(); // TODO: meditate about the flags we can pass to this and decide what is most appropriate for Roslyn var result = queryEdit.QueryEditFiles( rgfQueryEdit: 0, cFiles: fileNames.Length, rgpszMkDocuments: fileNames, rgrgf: new uint[fileNames.Length], rgFileInfo: new VSQEQS_FILE_ATTRIBUTE_DATA[fileNames.Length], pfEditVerdict: out var editVerdict, prgfMoreInfo: out var editResultFlags); if (ErrorHandler.Failed(result) || editVerdict != (uint)tagVSQueryEditResult.QER_EditOK) { throw new Exception("Unable to check out the files from source control."); } if ((editResultFlags & (uint)(tagVSQueryEditResultFlags2.QER_Changed | tagVSQueryEditResultFlags2.QER_Reloaded)) != 0) { throw new Exception("A file was reloaded during the source control checkout."); } } public void EnsureEditableDocuments(params DocumentId[] documents) => this.EnsureEditableDocuments((IEnumerable<DocumentId>)documents); internal override bool CanAddProjectReference(ProjectId referencingProject, ProjectId referencedProject) { _foregroundObject.AssertIsForeground(); if (!TryGetHierarchy(referencingProject, out var referencingHierarchy) || !TryGetHierarchy(referencedProject, out var referencedHierarchy)) { // Couldn't even get a hierarchy for this project. So we have to assume // that adding a reference is disallowed. return false; } // First we have to see if either project disallows the reference being added. const int ContextFlags = (int)__VSQUERYFLAVORREFERENCESCONTEXT.VSQUERYFLAVORREFERENCESCONTEXT_RefreshReference; var canAddProjectReference = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN; var canBeReferenced = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN; if (referencingHierarchy is IVsProjectFlavorReferences3 referencingProjectFlavor3) { if (ErrorHandler.Failed(referencingProjectFlavor3.QueryAddProjectReferenceEx(referencedHierarchy, ContextFlags, out canAddProjectReference, out _))) { // Something went wrong even trying to see if the reference would be allowed. // Assume it won't be allowed. return false; } if (canAddProjectReference == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY) { // Adding this project reference is not allowed. return false; } } if (referencedHierarchy is IVsProjectFlavorReferences3 referencedProjectFlavor3) { if (ErrorHandler.Failed(referencedProjectFlavor3.QueryCanBeReferencedEx(referencingHierarchy, ContextFlags, out canBeReferenced, out _))) { // Something went wrong even trying to see if the reference would be allowed. // Assume it won't be allowed. return false; } if (canBeReferenced == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY) { // Adding this project reference is not allowed. return false; } } // Neither project denied the reference being added. At this point, if either project // allows the reference to be added, and the other doesn't block it, then we can add // the reference. if (canAddProjectReference == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW || canBeReferenced == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW) { return true; } // In both directions things are still unknown. Fallback to the reference manager // to make the determination here. var referenceManager = (IVsReferenceManager)ServiceProvider.GlobalProvider.GetService(typeof(SVsReferenceManager)); if (referenceManager == null) { // Couldn't get the reference manager. Have to assume it's not allowed. return false; } // As long as the reference manager does not deny things, then we allow the // reference to be added. var result = referenceManager.QueryCanReferenceProject(referencingHierarchy, referencedHierarchy); return result != (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY; } /// <summary> /// Applies a single operation to the workspace. <paramref name="action"/> should be a call to one of the protected Workspace.On* methods. /// </summary> public void ApplyChangeToWorkspace(Action<Workspace> action) { lock (_gate) { action(this); } } /// <summary> /// Applies a solution transformation to the workspace and triggers workspace changed event for specified <paramref name="projectId"/>. /// The transformation shall only update the project of the solution with the specified <paramref name="projectId"/>. /// </summary> public void ApplyChangeToWorkspace(ProjectId projectId, Func<CodeAnalysis.Solution, CodeAnalysis.Solution> solutionTransformation) { lock (_gate) { SetCurrentSolution(solutionTransformation, WorkspaceChangeKind.ProjectChanged, projectId); } } /// <summary> /// Applies a change to the workspace that can do any number of project changes. /// </summary> /// <remarks>This is needed to synchronize with <see cref="ApplyChangeToWorkspace(Action{Workspace})" /> to avoid any races. This /// method could be moved down to the core Workspace layer and then could use the synchronization lock there.</remarks> public void ApplyBatchChangeToWorkspace(Func<CodeAnalysis.Solution, SolutionChangeAccumulator> mutation) { lock (_gate) { var oldSolution = this.CurrentSolution; var solutionChangeAccumulator = mutation(oldSolution); if (!solutionChangeAccumulator.HasChange) { return; } foreach (var documentId in solutionChangeAccumulator.DocumentIdsRemoved) { this.ClearDocumentData(documentId); } SetCurrentSolution(solutionChangeAccumulator.Solution); RaiseWorkspaceChangedEventAsync( solutionChangeAccumulator.WorkspaceChangeKind, oldSolution, solutionChangeAccumulator.Solution, solutionChangeAccumulator.WorkspaceChangeProjectId, solutionChangeAccumulator.WorkspaceChangeDocumentId); } } private readonly Dictionary<ProjectId, ProjectReferenceInformation> _projectReferenceInfoMap = new(); private ProjectReferenceInformation GetReferenceInfo_NoLock(ProjectId projectId) { Debug.Assert(Monitor.IsEntered(_gate)); return _projectReferenceInfoMap.GetOrAdd(projectId, _ => new ProjectReferenceInformation()); } protected internal override void OnProjectRemoved(ProjectId projectId) { lock (_gate) { var languageName = CurrentSolution.GetRequiredProject(projectId).Language; if (_projectReferenceInfoMap.TryGetValue(projectId, out var projectReferenceInfo)) { // If we still had any output paths, we'll want to remove them to cause conversion back to metadata references. // The call below implicitly is modifying the collection we've fetched, so we'll make a copy. foreach (var outputPath in projectReferenceInfo.OutputPaths.ToList()) { RemoveProjectOutputPath(projectId, outputPath); } _projectReferenceInfoMap.Remove(projectId); } _projectToHierarchyMap = _projectToHierarchyMap.Remove(projectId); _projectToGuidMap = _projectToGuidMap.Remove(projectId); // _projectToMaxSupportedLangVersionMap needs to be updated with ImmutableInterlocked since it can be mutated outside the lock ImmutableInterlocked.TryRemove<ProjectId, string?>(ref _projectToMaxSupportedLangVersionMap, projectId, out _); // _projectToDependencyNodeTargetIdentifier needs to be updated with ImmutableInterlocked since it can be mutated outside the lock ImmutableInterlocked.TryRemove(ref _projectToDependencyNodeTargetIdentifier, projectId, out _); _projectToRuleSetFilePath.Remove(projectId); foreach (var (projectName, projects) in _projectSystemNameToProjectsMap) { if (projects.RemoveAll(p => p.Id == projectId) > 0) { if (projects.Count == 0) { _projectSystemNameToProjectsMap.Remove(projectName); } break; } } base.OnProjectRemoved(projectId); // Try to update the UI context info. But cancel that work if we're shutting down. _threadingContext.RunWithShutdownBlockAsync(async cancellationToken => { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); RefreshProjectExistsUIContextForLanguage(languageName); }); } } private sealed class ProjectReferenceInformation { public readonly List<string> OutputPaths = new(); public readonly List<(string path, ProjectReference projectReference)> ConvertedProjectReferences = new List<(string path, ProjectReference)>(); } /// <summary> /// A multimap from an output path to the project outputting to it. Ideally, this shouldn't ever /// actually be a true multimap, since we shouldn't have two projects outputting to the same path, but /// any bug by a project adding the wrong output path means we could end up with some duplication. /// In that case, we'll temporarily have two until (hopefully) somebody removes it. /// </summary> private readonly Dictionary<string, List<ProjectId>> _projectsByOutputPath = new(StringComparer.OrdinalIgnoreCase); public void AddProjectOutputPath(ProjectId projectId, string outputPath) { lock (_gate) { var projectReferenceInformation = GetReferenceInfo_NoLock(projectId); projectReferenceInformation.OutputPaths.Add(outputPath); _projectsByOutputPath.MultiAdd(outputPath, projectId); var projectsForOutputPath = _projectsByOutputPath[outputPath]; var distinctProjectsForOutputPath = projectsForOutputPath.Distinct().ToList(); // If we have exactly one, then we're definitely good to convert if (projectsForOutputPath.Count == 1) { ConvertMetadataReferencesToProjectReferences_NoLock(projectId, outputPath); } else if (distinctProjectsForOutputPath.Count == 1) { // The same project has multiple output paths that are the same. Any project would have already been converted // by the prior add, so nothing further to do } else { // We have more than one project outputting to the same path. This shouldn't happen but we'll convert back // because now we don't know which project to reference. foreach (var otherProjectId in projectsForOutputPath) { // We know that since we're adding a path to projectId and we're here that we couldn't have already // had a converted reference to us, instead we need to convert things that are pointing to the project // we're colliding with if (otherProjectId != projectId) { ConvertProjectReferencesToMetadataReferences_NoLock(otherProjectId, outputPath); } } } } } /// <summary> /// Attempts to convert all metadata references to <paramref name="outputPath"/> to a project reference to <paramref name="projectId"/>. /// </summary> /// <param name="projectId">The <see cref="ProjectId"/> of the project that could be referenced in place of the output path.</param> /// <param name="outputPath">The output path to replace.</param> [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/31306", Constraint = "Avoid calling " + nameof(CodeAnalysis.Solution.GetProject) + " to avoid realizing all projects.")] private void ConvertMetadataReferencesToProjectReferences_NoLock(ProjectId projectId, string outputPath) { Debug.Assert(Monitor.IsEntered(_gate)); var modifiedSolution = this.CurrentSolution; using var _ = PooledHashSet<ProjectId>.GetInstance(out var projectIdsChanged); foreach (var projectIdToRetarget in this.CurrentSolution.ProjectIds) { if (CanConvertMetadataReferenceToProjectReference_NoLock(projectIdToRetarget, referencedProjectId: projectId)) { // PERF: call GetProjectState instead of GetProject, otherwise creating a new project might force all // Project instances to get created. foreach (PortableExecutableReference reference in modifiedSolution.GetProjectState(projectIdToRetarget)!.MetadataReferences) { if (string.Equals(reference.FilePath, outputPath, StringComparison.OrdinalIgnoreCase)) { FileWatchedReferenceFactory.StopWatchingReference(reference); var projectReference = new ProjectReference(projectId, reference.Properties.Aliases, reference.Properties.EmbedInteropTypes); modifiedSolution = modifiedSolution.RemoveMetadataReference(projectIdToRetarget, reference) .AddProjectReference(projectIdToRetarget, projectReference); projectIdsChanged.Add(projectIdToRetarget); GetReferenceInfo_NoLock(projectIdToRetarget).ConvertedProjectReferences.Add( (reference.FilePath!, projectReference)); // We have converted one, but you could have more than one reference with different aliases // that we need to convert, so we'll keep going } } } } SetSolutionAndRaiseWorkspaceChanged_NoLock(modifiedSolution, projectIdsChanged); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/31306", Constraint = "Avoid calling " + nameof(CodeAnalysis.Solution.GetProject) + " to avoid realizing all projects.")] private bool CanConvertMetadataReferenceToProjectReference_NoLock(ProjectId projectIdWithMetadataReference, ProjectId referencedProjectId) { Debug.Assert(Monitor.IsEntered(_gate)); // We can never make a project reference ourselves. This isn't a meaningful scenario, but if somebody does this by accident // we do want to throw exceptions. if (projectIdWithMetadataReference == referencedProjectId) { return false; } // PERF: call GetProjectState instead of GetProject, otherwise creating a new project might force all // Project instances to get created. var projectWithMetadataReference = CurrentSolution.GetProjectState(projectIdWithMetadataReference); var referencedProject = CurrentSolution.GetProjectState(referencedProjectId); Contract.ThrowIfNull(projectWithMetadataReference); Contract.ThrowIfNull(referencedProject); // We don't want to convert a metadata reference to a project reference if the project being referenced isn't something // we can create a Compilation for. For example, if we have a C# project, and it's referencing a F# project via a metadata reference // everything would be fine if we left it a metadata reference. Converting it to a project reference means we couldn't create a Compilation // anymore in the IDE, since the C# compilation would need to reference an F# compilation. F# projects referencing other F# projects though // do expect this to work, and so we'll always allow references through of the same language. if (projectWithMetadataReference.Language != referencedProject.Language) { if (projectWithMetadataReference.LanguageServices.GetService<ICompilationFactoryService>() != null && referencedProject.LanguageServices.GetService<ICompilationFactoryService>() == null) { // We're referencing something that we can't create a compilation from something that can, so keep the metadata reference return false; } } // If this is going to cause a circular reference, also disallow it if (CurrentSolution.GetProjectDependencyGraph().GetProjectsThatThisProjectTransitivelyDependsOn(referencedProjectId).Contains(projectIdWithMetadataReference)) { return false; } return true; } /// <summary> /// Finds all projects that had a project reference to <paramref name="projectId"/> and convert it back to a metadata reference. /// </summary> /// <param name="projectId">The <see cref="ProjectId"/> of the project being referenced.</param> /// <param name="outputPath">The output path of the given project to remove the link to.</param> [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/37616", Constraint = "Update ConvertedProjectReferences in place to avoid duplicate list allocations.")] private void ConvertProjectReferencesToMetadataReferences_NoLock(ProjectId projectId, string outputPath) { Debug.Assert(Monitor.IsEntered(_gate)); var modifiedSolution = this.CurrentSolution; using var _ = PooledHashSet<ProjectId>.GetInstance(out var projectIdsChanged); foreach (var projectIdToRetarget in this.CurrentSolution.ProjectIds) { var referenceInfo = GetReferenceInfo_NoLock(projectIdToRetarget); // Update ConvertedProjectReferences in place to avoid duplicate list allocations for (var i = 0; i < referenceInfo.ConvertedProjectReferences.Count; i++) { var convertedReference = referenceInfo.ConvertedProjectReferences[i]; if (string.Equals(convertedReference.path, outputPath, StringComparison.OrdinalIgnoreCase) && convertedReference.projectReference.ProjectId == projectId) { var metadataReference = FileWatchedReferenceFactory.CreateReferenceAndStartWatchingFile( convertedReference.path, new MetadataReferenceProperties( aliases: convertedReference.projectReference.Aliases, embedInteropTypes: convertedReference.projectReference.EmbedInteropTypes)); modifiedSolution = modifiedSolution.RemoveProjectReference(projectIdToRetarget, convertedReference.projectReference) .AddMetadataReference(projectIdToRetarget, metadataReference); projectIdsChanged.Add(projectIdToRetarget); referenceInfo.ConvertedProjectReferences.RemoveAt(i); // We have converted one, but you could have more than one reference with different aliases // that we need to convert, so we'll keep going. Make sure to decrement the index so we don't // skip any items. i--; } } } SetSolutionAndRaiseWorkspaceChanged_NoLock(modifiedSolution, projectIdsChanged); } public ProjectReference? TryCreateConvertedProjectReference_NoLock(ProjectId referencingProject, string path, MetadataReferenceProperties properties) { // Any conversion to or from project references must be done under the global workspace lock, // since that needs to be coordinated with updating all projects simultaneously. Debug.Assert(Monitor.IsEntered(_gate)); if (_projectsByOutputPath.TryGetValue(path, out var ids) && ids.Distinct().Count() == 1) { var projectIdToReference = ids.First(); if (CanConvertMetadataReferenceToProjectReference_NoLock(referencingProject, projectIdToReference)) { var projectReference = new ProjectReference( projectIdToReference, aliases: properties.Aliases, embedInteropTypes: properties.EmbedInteropTypes); GetReferenceInfo_NoLock(referencingProject).ConvertedProjectReferences.Add((path, projectReference)); return projectReference; } else { return null; } } else { return null; } } public ProjectReference? TryRemoveConvertedProjectReference_NoLock(ProjectId referencingProject, string path, MetadataReferenceProperties properties) { // Any conversion to or from project references must be done under the global workspace lock, // since that needs to be coordinated with updating all projects simultaneously. Debug.Assert(Monitor.IsEntered(_gate)); var projectReferenceInformation = GetReferenceInfo_NoLock(referencingProject); foreach (var convertedProject in projectReferenceInformation.ConvertedProjectReferences) { if (convertedProject.path == path && convertedProject.projectReference.EmbedInteropTypes == properties.EmbedInteropTypes && convertedProject.projectReference.Aliases.SequenceEqual(properties.Aliases)) { projectReferenceInformation.ConvertedProjectReferences.Remove(convertedProject); return convertedProject.projectReference; } } return null; } private void SetSolutionAndRaiseWorkspaceChanged_NoLock(CodeAnalysis.Solution modifiedSolution, ICollection<ProjectId> projectIdsChanged) { if (projectIdsChanged.Count > 0) { Debug.Assert(modifiedSolution != CurrentSolution); var originalSolution = this.CurrentSolution; SetCurrentSolution(modifiedSolution); if (projectIdsChanged.Count == 1) { RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.ProjectChanged, originalSolution, this.CurrentSolution, projectIdsChanged.Single()); } else { RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.SolutionChanged, originalSolution, this.CurrentSolution); } } else { // If they said nothing changed, than definitely nothing should have changed! Debug.Assert(modifiedSolution == CurrentSolution); } } public void RemoveProjectOutputPath(ProjectId projectId, string outputPath) { lock (_gate) { var projectReferenceInformation = GetReferenceInfo_NoLock(projectId); if (!projectReferenceInformation.OutputPaths.Contains(outputPath)) { throw new ArgumentException($"Project does not contain output path '{outputPath}'", nameof(outputPath)); } projectReferenceInformation.OutputPaths.Remove(outputPath); _projectsByOutputPath.MultiRemove(outputPath, projectId); // When a project is closed, we may need to convert project references to metadata references (or vice // versa). Failure to convert the references could leave a project in the workspace with a project // reference to a project which is not open. // // For the specific case where the entire solution is closing, we do not need to update the state for // remaining projects as each project closes, because we know those projects will be closed without // further use. Avoiding reference conversion when the solution is closing improves performance for both // IDE close scenarios and solution reload scenarios that occur after complex branch switches. if (!_solutionClosing) { if (_projectsByOutputPath.TryGetValue(outputPath, out var remainingProjectsForOutputPath)) { var distinctRemainingProjects = remainingProjectsForOutputPath.Distinct(); if (distinctRemainingProjects.Count() == 1) { // We had more than one project outputting to the same path. Now we're back down to one // so we can reference that one again ConvertMetadataReferencesToProjectReferences_NoLock(distinctRemainingProjects.Single(), outputPath); } } else { // No projects left, we need to convert back to metadata references ConvertProjectReferencesToMetadataReferences_NoLock(projectId, outputPath); } } } } private void RefreshMetadataReferencesForFile(object sender, string fullFilePath) { lock (_gate) { var newSolution = CurrentSolution; using var _ = PooledHashSet<ProjectId>.GetInstance(out var changedProjectIds); foreach (var project in CurrentSolution.Projects) { // Loop to find each reference with the given path. It's possible that there might be multiple references of the same path; // the project system could concievably add the same reference multiple times but with different aliases. It's also possible // we might not find the path at all: when we receive the file changed event, we aren't checking if the file is still // in the workspace at that time; it's possible it might have already been removed. foreach (var portableExecutableReference in project.MetadataReferences.OfType<PortableExecutableReference>()) { if (portableExecutableReference.FilePath == fullFilePath) { FileWatchedReferenceFactory.StopWatchingReference(portableExecutableReference); var newPortableExecutableReference = FileWatchedReferenceFactory.CreateReferenceAndStartWatchingFile( portableExecutableReference.FilePath, portableExecutableReference.Properties); newSolution = newSolution.RemoveMetadataReference(project.Id, portableExecutableReference) .AddMetadataReference(project.Id, newPortableExecutableReference); changedProjectIds.Add(project.Id); } } } SetSolutionAndRaiseWorkspaceChanged_NoLock(newSolution, changedProjectIds); } } internal async Task EnsureDocumentOptionProvidersInitializedAsync(CancellationToken cancellationToken) { // HACK: switch to the UI thread, ensure we initialize our options provider which depends on a // UI-affinitized experimentation service await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); _foregroundObject.AssertIsForeground(); if (_documentOptionsProvidersInitialized) { return; } _documentOptionsProvidersInitialized = true; RegisterDocumentOptionProviders(_documentOptionsProviderFactories); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/54137", AllowLocks = false)] internal void SetMaxLanguageVersion(ProjectId projectId, string? maxLanguageVersion) { ImmutableInterlocked.Update( ref _projectToMaxSupportedLangVersionMap, static (map, arg) => map.SetItem(arg.projectId, arg.maxLanguageVersion), (projectId, maxLanguageVersion)); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/54135", AllowLocks = false)] internal void SetDependencyNodeTargetIdentifier(ProjectId projectId, string targetIdentifier) { ImmutableInterlocked.Update( ref _projectToDependencyNodeTargetIdentifier, static (map, arg) => map.SetItem(arg.projectId, arg.targetIdentifier), (projectId, targetIdentifier)); } internal void RefreshProjectExistsUIContextForLanguage(string language) { // We must assert the call is on the foreground as setting UIContext.IsActive would otherwise do a COM RPC. _foregroundObject.AssertIsForeground(); lock (_gate) { var uiContext = _languageToProjectExistsUIContext.GetOrAdd( language, l => Services.GetLanguageServices(l).GetService<IProjectExistsUIContextProviderLanguageService>()?.GetUIContext()); // UIContexts can be "zombied" if UIContexts aren't supported because we're in a command line build or in other scenarios. if (uiContext != null && !uiContext.IsZombie) { uiContext.IsActive = CurrentSolution.Projects.Any(p => p.Language == 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 System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using EnvDTE; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.MetadataReferences; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Projection; using Roslyn.Utilities; using VSLangProj; using VSLangProj140; using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider; using OleInterop = Microsoft.VisualStudio.OLE.Interop; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { /// <summary> /// The Workspace for running inside Visual Studio. /// </summary> internal abstract partial class VisualStudioWorkspaceImpl : VisualStudioWorkspace { private static readonly IntPtr s_docDataExisting_Unknown = new(-1); private const string AppCodeFolderName = "App_Code"; private readonly IThreadingContext _threadingContext; private readonly ITextBufferFactoryService _textBufferFactoryService; private readonly IProjectionBufferFactoryService _projectionBufferFactoryService; [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] private readonly Lazy<VisualStudioProjectFactory> _projectFactory; private readonly ITextBufferCloneService _textBufferCloneService; private readonly object _gate = new(); /// <summary> /// A <see cref="ForegroundThreadAffinitizedObject"/> to make assertions that stuff is on the right thread. /// </summary> private readonly ForegroundThreadAffinitizedObject _foregroundObject; private ImmutableDictionary<ProjectId, IVsHierarchy?> _projectToHierarchyMap = ImmutableDictionary<ProjectId, IVsHierarchy?>.Empty; private ImmutableDictionary<ProjectId, Guid> _projectToGuidMap = ImmutableDictionary<ProjectId, Guid>.Empty; private ImmutableDictionary<ProjectId, string?> _projectToMaxSupportedLangVersionMap = ImmutableDictionary<ProjectId, string?>.Empty; private ImmutableDictionary<ProjectId, string> _projectToDependencyNodeTargetIdentifier = ImmutableDictionary<ProjectId, string>.Empty; /// <summary> /// A map to fetch the path to a rule set file for a project. This right now is only used to implement /// <see cref="TryGetRuleSetPathForProject(ProjectId)"/> and any other use is extremely suspicious, since direct use of this is out of /// sync with the Workspace if there is active batching happening. /// </summary> private readonly Dictionary<ProjectId, Func<string?>> _projectToRuleSetFilePath = new(); private readonly Dictionary<string, List<VisualStudioProject>> _projectSystemNameToProjectsMap = new(); private readonly Dictionary<string, UIContext?> _languageToProjectExistsUIContext = new(); /// <summary> /// A set of documents that were added by <see cref="VisualStudioProject.AddSourceTextContainer"/>, and aren't otherwise /// tracked for opening/closing. /// </summary> private ImmutableHashSet<DocumentId> _documentsNotFromFiles = ImmutableHashSet<DocumentId>.Empty; /// <summary> /// Indicates whether the current solution is closing. /// </summary> private bool _solutionClosing; [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] internal VisualStudioProjectTracker? _projectTracker; private VirtualMemoryNotificationListener? _memoryListener; private OpenFileTracker? _openFileTracker; internal FileChangeWatcher FileChangeWatcher { get; } internal FileWatchedPortableExecutableReferenceFactory FileWatchedReferenceFactory { get; } private readonly Lazy<IProjectCodeModelFactory> _projectCodeModelFactory; private readonly IEnumerable<Lazy<IDocumentOptionsProviderFactory, OrderableMetadata>> _documentOptionsProviderFactories; private bool _documentOptionsProvidersInitialized = false; private readonly Lazy<ExternalErrorDiagnosticUpdateSource> _lazyExternalErrorDiagnosticUpdateSource; private bool _isExternalErrorDiagnosticUpdateSourceSubscribedToSolutionBuildEvents; public VisualStudioWorkspaceImpl(ExportProvider exportProvider, IAsyncServiceProvider asyncServiceProvider) : base(VisualStudioMefHostServices.Create(exportProvider)) { _threadingContext = exportProvider.GetExportedValue<IThreadingContext>(); _textBufferCloneService = exportProvider.GetExportedValue<ITextBufferCloneService>(); _textBufferFactoryService = exportProvider.GetExportedValue<ITextBufferFactoryService>(); _projectionBufferFactoryService = exportProvider.GetExportedValue<IProjectionBufferFactoryService>(); _projectCodeModelFactory = exportProvider.GetExport<IProjectCodeModelFactory>(); _documentOptionsProviderFactories = exportProvider.GetExports<IDocumentOptionsProviderFactory, OrderableMetadata>(); // We fetch this lazily because VisualStudioProjectFactory depends on VisualStudioWorkspaceImpl -- we have a circularity. Since this // exists right now as a compat shim, we'll just do this. #pragma warning disable CS0618 // Type or member is obsolete _projectFactory = exportProvider.GetExport<VisualStudioProjectFactory>(); #pragma warning restore CS0618 // Type or member is obsolete _foregroundObject = new ForegroundThreadAffinitizedObject(_threadingContext); _textBufferFactoryService.TextBufferCreated += AddTextBufferCloneServiceToBuffer; _projectionBufferFactoryService.ProjectionBufferCreated += AddTextBufferCloneServiceToBuffer; _ = Task.Run(() => InitializeUIAffinitizedServicesAsync(asyncServiceProvider)); FileChangeWatcher = exportProvider.GetExportedValue<FileChangeWatcherProvider>().Watcher; FileWatchedReferenceFactory = exportProvider.GetExportedValue<FileWatchedPortableExecutableReferenceFactory>(); FileWatchedReferenceFactory.ReferenceChanged += this.RefreshMetadataReferencesForFile; _lazyExternalErrorDiagnosticUpdateSource = new Lazy<ExternalErrorDiagnosticUpdateSource>(() => new ExternalErrorDiagnosticUpdateSource( this, exportProvider.GetExportedValue<IDiagnosticAnalyzerService>(), exportProvider.GetExportedValue<IDiagnosticUpdateSourceRegistrationService>(), exportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>(), _threadingContext), isThreadSafe: true); } internal ExternalErrorDiagnosticUpdateSource ExternalErrorDiagnosticUpdateSource => _lazyExternalErrorDiagnosticUpdateSource.Value; internal void SubscribeExternalErrorDiagnosticUpdateSourceToSolutionBuildEvents() { _foregroundObject.AssertIsForeground(); if (_isExternalErrorDiagnosticUpdateSourceSubscribedToSolutionBuildEvents) { return; } // TODO: https://github.com/dotnet/roslyn/issues/36065 // UIContextImpl requires IVsMonitorSelection service: if (ServiceProvider.GlobalProvider.GetService(typeof(IVsMonitorSelection)) == null) { return; } // This pattern ensures that we are called whenever the build starts/completes even if it is already in progress. KnownUIContexts.SolutionBuildingContext.WhenActivated(() => { KnownUIContexts.SolutionBuildingContext.UIContextChanged += (object _, UIContextChangedEventArgs e) => { if (e.Activated) { ExternalErrorDiagnosticUpdateSource.OnSolutionBuildStarted(); } else { ExternalErrorDiagnosticUpdateSource.OnSolutionBuildCompleted(); } }; ExternalErrorDiagnosticUpdateSource.OnSolutionBuildStarted(); }); _isExternalErrorDiagnosticUpdateSourceSubscribedToSolutionBuildEvents = true; } public async Task InitializeUIAffinitizedServicesAsync(IAsyncServiceProvider asyncServiceProvider) { // Create services that are bound to the UI thread await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(_threadingContext.DisposalToken); var solutionClosingContext = UIContext.FromUIContextGuid(VSConstants.UICONTEXT.SolutionClosing_guid); solutionClosingContext.UIContextChanged += (_, e) => _solutionClosing = e.Activated; var openFileTracker = await OpenFileTracker.CreateAsync(this, asyncServiceProvider).ConfigureAwait(true); // Update our fields first, so any asynchronous work that needs to use these is able to see the service. lock (_gate) { _openFileTracker = openFileTracker; } var memoryListener = await VirtualMemoryNotificationListener.CreateAsync(this, _threadingContext, asyncServiceProvider, _threadingContext.DisposalToken).ConfigureAwait(true); // Update our fields first, so any asynchronous work that needs to use these is able to see the service. lock (_gate) { _memoryListener = memoryListener; } openFileTracker.ProcessQueuedWorkOnUIThread(); } public void QueueCheckForFilesBeingOpen(ImmutableArray<string> newFileNames) => _openFileTracker?.QueueCheckForFilesBeingOpen(newFileNames); public void ProcessQueuedWorkOnUIThread() => _openFileTracker?.ProcessQueuedWorkOnUIThread(); internal void AddProjectToInternalMaps(VisualStudioProject project, IVsHierarchy? hierarchy, Guid guid, string projectSystemName) { lock (_gate) { _projectToHierarchyMap = _projectToHierarchyMap.Add(project.Id, hierarchy); _projectToGuidMap = _projectToGuidMap.Add(project.Id, guid); _projectSystemNameToProjectsMap.MultiAdd(projectSystemName, project); } } internal void AddProjectRuleSetFileToInternalMaps(VisualStudioProject project, Func<string?> ruleSetFilePathFunc) { lock (_gate) { _projectToRuleSetFilePath.Add(project.Id, ruleSetFilePathFunc); } } internal void AddDocumentToDocumentsNotFromFiles(DocumentId documentId) { lock (_gate) { _documentsNotFromFiles = _documentsNotFromFiles.Add(documentId); } } internal void RemoveDocumentToDocumentsNotFromFiles(DocumentId documentId) { lock (_gate) { _documentsNotFromFiles = _documentsNotFromFiles.Remove(documentId); } } [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] internal VisualStudioProjectTracker GetProjectTrackerAndInitializeIfNecessary() { if (_projectTracker == null) { _projectTracker = new VisualStudioProjectTracker(this, _projectFactory.Value, _threadingContext); } return _projectTracker; } [Obsolete("This is a compatibility shim for TypeScript and F#; please do not use it.")] internal VisualStudioProjectTracker ProjectTracker { get { return GetProjectTrackerAndInitializeIfNecessary(); } } internal ContainedDocument? TryGetContainedDocument(DocumentId documentId) { // TODO: move everybody off of this instance method and replace them with calls to // ContainedDocument.TryGetContainedDocument return ContainedDocument.TryGetContainedDocument(documentId); } internal VisualStudioProject? GetProjectWithHierarchyAndName(IVsHierarchy hierarchy, string projectName) { lock (_gate) { if (_projectSystemNameToProjectsMap.TryGetValue(projectName, out var projects)) { foreach (var project in projects) { if (_projectToHierarchyMap.TryGetValue(project.Id, out var projectHierarchy)) { if (projectHierarchy == hierarchy) { return project; } } } } } return null; } // TODO: consider whether this should be going to the project system directly to get this path. This is only called on interactions from the // Solution Explorer in the SolutionExplorerShim, where if we just could more directly get to the rule set file it'd simplify this. internal override string? TryGetRuleSetPathForProject(ProjectId projectId) { lock (_gate) { if (_projectToRuleSetFilePath.TryGetValue(projectId, out var ruleSetPathFunc)) { return ruleSetPathFunc(); } else { return null; } } } [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] internal IVisualStudioHostDocument? GetHostDocument(DocumentId documentId) { // TypeScript only calls this to immediately check if the document is a ContainedDocument. Because of that we can just check for // ContainedDocuments return ContainedDocument.TryGetContainedDocument(documentId); } public override EnvDTE.FileCodeModel GetFileCodeModel(DocumentId documentId) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } var documentFilePath = GetFilePath(documentId); if (documentFilePath == null) { throw new ArgumentException(ServicesVSResources.The_given_DocumentId_did_not_come_from_the_Visual_Studio_workspace, nameof(documentId)); } return _projectCodeModelFactory.Value.GetOrCreateFileCodeModel(documentId.ProjectId, documentFilePath); } internal override bool TryApplyChanges( Microsoft.CodeAnalysis.Solution newSolution, IProgressTracker progressTracker) { if (!_foregroundObject.IsForeground()) { throw new InvalidOperationException(ServicesVSResources.VisualStudioWorkspace_TryApplyChanges_cannot_be_called_from_a_background_thread); } var currentSolution = this.CurrentSolution; var projectChanges = newSolution.GetChanges(currentSolution).GetProjectChanges().ToList(); // first make sure we can edit the document we will be updating (check them out from source control, etc) var changedDocs = projectChanges.SelectMany(pd => pd.GetChangedDocuments(onlyGetDocumentsWithTextChanges: true).Concat(pd.GetChangedAdditionalDocuments())) .Where(CanApplyChange).ToList(); if (changedDocs.Count > 0) { this.EnsureEditableDocuments(changedDocs); } return base.TryApplyChanges(newSolution, progressTracker); bool CanApplyChange(DocumentId documentId) { var document = newSolution.GetDocument(documentId) ?? currentSolution.GetDocument(documentId); if (document == null) { // we can have null if documentId is for additional files return true; } return document.CanApplyChange(); } } public override bool CanOpenDocuments { get { return true; } } internal override bool CanChangeActiveContextDocument { get { return true; } } internal bool IsCPSProject(CodeAnalysis.Project project) => IsCPSProject(project.Id); internal bool IsCPSProject(ProjectId projectId) { _foregroundObject.AssertIsForeground(); if (this.TryGetHierarchy(projectId, out var hierarchy)) { return hierarchy.IsCapabilityMatch("CPS"); } return false; } internal bool IsPrimaryProject(ProjectId projectId) { lock (_gate) { foreach (var (_, projects) in _projectSystemNameToProjectsMap) { foreach (var project in projects) { if (project.Id == projectId) return project.IsPrimary; } } } return true; } protected override bool CanApplyCompilationOptionChange(CompilationOptions oldOptions, CompilationOptions newOptions, CodeAnalysis.Project project) => project.LanguageServices.GetRequiredService<ICompilationOptionsChangingService>().CanApplyChange(oldOptions, newOptions); public override bool CanApplyParseOptionChange(ParseOptions oldOptions, ParseOptions newOptions, CodeAnalysis.Project project) { _projectToMaxSupportedLangVersionMap.TryGetValue(project.Id, out var maxSupportLangVersion); return project.LanguageServices.GetRequiredService<IParseOptionsChangingService>().CanApplyChange(oldOptions, newOptions, maxSupportLangVersion); } private void AddTextBufferCloneServiceToBuffer(object sender, TextBufferCreatedEventArgs e) => e.TextBuffer.Properties.AddProperty(typeof(ITextBufferCloneService), _textBufferCloneService); public override bool CanApplyChange(ApplyChangesKind feature) { switch (feature) { case ApplyChangesKind.AddDocument: case ApplyChangesKind.RemoveDocument: case ApplyChangesKind.ChangeDocument: case ApplyChangesKind.AddMetadataReference: case ApplyChangesKind.RemoveMetadataReference: case ApplyChangesKind.AddProjectReference: case ApplyChangesKind.RemoveProjectReference: case ApplyChangesKind.AddAnalyzerReference: case ApplyChangesKind.RemoveAnalyzerReference: case ApplyChangesKind.AddAdditionalDocument: case ApplyChangesKind.RemoveAdditionalDocument: case ApplyChangesKind.ChangeAdditionalDocument: case ApplyChangesKind.ChangeCompilationOptions: case ApplyChangesKind.ChangeParseOptions: case ApplyChangesKind.ChangeDocumentInfo: case ApplyChangesKind.AddAnalyzerConfigDocument: case ApplyChangesKind.RemoveAnalyzerConfigDocument: case ApplyChangesKind.ChangeAnalyzerConfigDocument: case ApplyChangesKind.AddSolutionAnalyzerReference: case ApplyChangesKind.RemoveSolutionAnalyzerReference: return true; default: return false; } } private bool TryGetProjectData(ProjectId projectId, [NotNullWhen(returnValue: true)] out IVsHierarchy? hierarchy, [NotNullWhen(returnValue: true)] out EnvDTE.Project? project) { project = null; return this.TryGetHierarchy(projectId, out hierarchy) && hierarchy.TryGetProject(out project); } internal void GetProjectData(ProjectId projectId, out IVsHierarchy hierarchy, out EnvDTE.Project project) { if (!TryGetProjectData(projectId, out hierarchy!, out project!)) { throw new ArgumentException(string.Format(ServicesVSResources.Could_not_find_project_0, projectId)); } } internal EnvDTE.Project? TryGetDTEProject(ProjectId projectId) => TryGetProjectData(projectId, out var _, out var project) ? project : null; internal bool TryAddReferenceToProject(ProjectId projectId, string assemblyName) { if (!TryGetProjectData(projectId, out _, out var project)) { return false; } var vsProject = (VSProject)project.Object; try { vsProject.References.Add(assemblyName); } catch (Exception) { return false; } return true; } private string? GetAnalyzerPath(AnalyzerReference analyzerReference) => analyzerReference.FullPath; protected override void ApplyCompilationOptionsChanged(ProjectId projectId, CompilationOptions options) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } var compilationOptionsService = CurrentSolution.GetRequiredProject(projectId).LanguageServices.GetRequiredService<ICompilationOptionsChangingService>(); var storage = ProjectPropertyStorage.Create(TryGetDTEProject(projectId), ServiceProvider.GlobalProvider); compilationOptionsService.Apply(options, storage); } protected override void ApplyParseOptionsChanged(ProjectId projectId, ParseOptions options) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } var parseOptionsService = CurrentSolution.GetRequiredProject(projectId).LanguageServices.GetRequiredService<IParseOptionsChangingService>(); var storage = ProjectPropertyStorage.Create(TryGetDTEProject(projectId), ServiceProvider.GlobalProvider); parseOptionsService.Apply(options, storage); } protected override void ApplyAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (analyzerReference == null) { throw new ArgumentNullException(nameof(analyzerReference)); } GetProjectData(projectId, out _, out var project); var filePath = GetAnalyzerPath(analyzerReference); if (filePath != null) { var vsProject = (VSProject3)project.Object; vsProject.AnalyzerReferences.Add(filePath); } } protected override void ApplyAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (analyzerReference == null) { throw new ArgumentNullException(nameof(analyzerReference)); } GetProjectData(projectId, out _, out var project); var filePath = GetAnalyzerPath(analyzerReference); if (filePath != null) { var vsProject = (VSProject3)project.Object; vsProject.AnalyzerReferences.Remove(filePath); } } private string? GetMetadataPath(MetadataReference metadataReference) { if (metadataReference is PortableExecutableReference fileMetadata) { return fileMetadata.FilePath; } return null; } protected override void ApplyMetadataReferenceAdded( ProjectId projectId, MetadataReference metadataReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (metadataReference == null) { throw new ArgumentNullException(nameof(metadataReference)); } GetProjectData(projectId, out _, out var project); var filePath = GetMetadataPath(metadataReference); if (filePath != null) { var vsProject = (VSProject)project.Object; vsProject.References.Add(filePath); var undoManager = TryGetUndoManager(); undoManager?.Add(new RemoveMetadataReferenceUndoUnit(this, projectId, filePath)); } } protected override void ApplyMetadataReferenceRemoved( ProjectId projectId, MetadataReference metadataReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (metadataReference == null) { throw new ArgumentNullException(nameof(metadataReference)); } GetProjectData(projectId, out _, out var project); var filePath = GetMetadataPath(metadataReference); if (filePath != null) { var vsProject = (VSProject)project.Object; foreach (Reference reference in vsProject.References) { if (StringComparer.OrdinalIgnoreCase.Equals(reference.Path, filePath)) { reference.Remove(); var undoManager = TryGetUndoManager(); undoManager?.Add(new AddMetadataReferenceUndoUnit(this, projectId, filePath)); break; } } } } internal override void ApplyMappedFileChanges(SolutionChanges solutionChanges) { // Get the original text changes from all documents and call the span mapping service to get span mappings for the text changes. // Create mapped text changes using the mapped spans and original text changes' text. // Mappings for opened razor files are retrieved via the LSP client making a request to the razor server. // If we wait for the result on the UI thread, we will hit a bug in the LSP client that brings us to a code path // using ConfigureAwait(true). This deadlocks as it then attempts to return to the UI thread which is already blocked by us. // Instead, we invoke this in JTF run which will mitigate deadlocks when the ConfigureAwait(true) // tries to switch back to the main thread in the LSP client. // Link to LSP client bug for ConfigureAwait(true) - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1216657 var mappedChanges = _threadingContext.JoinableTaskFactory.Run(() => GetMappedTextChanges(solutionChanges)); // Group the mapped text changes by file, then apply all mapped text changes for the file. foreach (var changesForFile in mappedChanges) { // It doesn't matter which of the file's projectIds we pass to the invisible editor, so just pick the first. var projectId = changesForFile.Value.First().ProjectId; // Make sure we only take distinct changes - we'll have duplicates from different projects for linked files or multi-targeted files. var distinctTextChanges = changesForFile.Value.Select(change => change.TextChange).Distinct().ToImmutableArray(); using var invisibleEditor = new InvisibleEditor(ServiceProvider.GlobalProvider, changesForFile.Key, GetHierarchy(projectId), needsSave: true, needsUndoDisabled: false); TextEditApplication.UpdateText(distinctTextChanges, invisibleEditor.TextBuffer, EditOptions.None); } return; async Task<MultiDictionary<string, (TextChange TextChange, ProjectId ProjectId)>> GetMappedTextChanges(SolutionChanges solutionChanges) { var filePathToMappedTextChanges = new MultiDictionary<string, (TextChange TextChange, ProjectId ProjectId)>(); foreach (var projectChanges in solutionChanges.GetProjectChanges()) { foreach (var changedDocumentId in projectChanges.GetChangedDocuments()) { var oldDocument = projectChanges.OldProject.GetRequiredDocument(changedDocumentId); if (!ShouldApplyChangesToMappedDocuments(oldDocument, out var mappingService)) { continue; } var newDocument = projectChanges.NewProject.GetRequiredDocument(changedDocumentId); var mappedTextChanges = await mappingService.GetMappedTextChangesAsync( oldDocument, newDocument, CancellationToken.None).ConfigureAwait(false); foreach (var (filePath, textChange) in mappedTextChanges) { filePathToMappedTextChanges.Add(filePath, (textChange, projectChanges.ProjectId)); } } } return filePathToMappedTextChanges; } bool ShouldApplyChangesToMappedDocuments(CodeAnalysis.Document document, [NotNullWhen(true)] out ISpanMappingService? spanMappingService) { spanMappingService = document.Services.GetService<ISpanMappingService>(); // Only consider files that are mapped and that we are unable to apply changes to. // TODO - refactor how this is determined - https://github.com/dotnet/roslyn/issues/47908 return spanMappingService != null && document?.CanApplyChange() == false; } } protected override void ApplyProjectReferenceAdded( ProjectId projectId, ProjectReference projectReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } GetProjectData(projectId, out _, out var project); GetProjectData(projectReference.ProjectId, out _, out var refProject); var vsProject = (VSProject)project.Object; vsProject.References.AddProject(refProject); var undoManager = TryGetUndoManager(); undoManager?.Add(new RemoveProjectReferenceUndoUnit( this, projectId, projectReference.ProjectId)); } private OleInterop.IOleUndoManager? TryGetUndoManager() { var documentTrackingService = this.Services.GetRequiredService<IDocumentTrackingService>(); var documentId = documentTrackingService.TryGetActiveDocument() ?? documentTrackingService.GetVisibleDocuments().FirstOrDefault(); if (documentId != null) { var composition = (IComponentModel)ServiceProvider.GlobalProvider.GetService(typeof(SComponentModel)); var exportProvider = composition.DefaultExportProvider; var editorAdaptersService = exportProvider.GetExportedValue<IVsEditorAdaptersFactoryService>(); return editorAdaptersService.TryGetUndoManager(this, documentId, CancellationToken.None); } return null; } protected override void ApplyProjectReferenceRemoved( ProjectId projectId, ProjectReference projectReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } GetProjectData(projectId, out _, out var project); GetProjectData(projectReference.ProjectId, out _, out var refProject); var vsProject = (VSProject)project.Object; foreach (Reference reference in vsProject.References) { if (reference.SourceProject == refProject) { reference.Remove(); var undoManager = TryGetUndoManager(); undoManager?.Add(new AddProjectReferenceUndoUnit(this, projectId, projectReference.ProjectId)); } } } protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text) => AddDocumentCore(info, text, TextDocumentKind.Document); protected override void ApplyAdditionalDocumentAdded(DocumentInfo info, SourceText text) => AddDocumentCore(info, text, TextDocumentKind.AdditionalDocument); protected override void ApplyAnalyzerConfigDocumentAdded(DocumentInfo info, SourceText text) => AddDocumentCore(info, text, TextDocumentKind.AnalyzerConfigDocument); private void AddDocumentCore(DocumentInfo info, SourceText initialText, TextDocumentKind documentKind) { GetProjectData(info.Id.ProjectId, out _, out var project); // If the first namespace name matches the name of the project, then we don't want to // generate a folder for that. The project is implicitly a folder with that name. var folders = info.Folders.AsEnumerable(); if (folders.FirstOrDefault() == project.Name) { folders = folders.Skip(1); } folders = FilterFolderForProjectType(project, folders); if (IsWebsite(project)) { AddDocumentToFolder(project, info.Id, SpecializedCollections.SingletonEnumerable(AppCodeFolderName), info.Name, documentKind, initialText, info.FilePath); } else if (folders.Any()) { AddDocumentToFolder(project, info.Id, folders, info.Name, documentKind, initialText, info.FilePath); } else { AddDocumentToProject(project, info.Id, info.Name, documentKind, initialText, info.FilePath); } var undoManager = TryGetUndoManager(); switch (documentKind) { case TextDocumentKind.AdditionalDocument: undoManager?.Add(new RemoveAdditionalDocumentUndoUnit(this, info.Id)); break; case TextDocumentKind.AnalyzerConfigDocument: undoManager?.Add(new RemoveAnalyzerConfigDocumentUndoUnit(this, info.Id)); break; case TextDocumentKind.Document: undoManager?.Add(new RemoveDocumentUndoUnit(this, info.Id)); break; default: throw ExceptionUtilities.UnexpectedValue(documentKind); } } private bool IsWebsite(EnvDTE.Project project) => project.Kind == VsWebSite.PrjKind.prjKindVenusProject; private IEnumerable<string> FilterFolderForProjectType(EnvDTE.Project project, IEnumerable<string> folders) { foreach (var folder in folders) { var items = GetAllItems(project.ProjectItems); var folderItem = items.FirstOrDefault(p => StringComparer.OrdinalIgnoreCase.Compare(p.Name, folder) == 0); if (folderItem == null || folderItem.Kind != EnvDTE.Constants.vsProjectItemKindPhysicalFile) { yield return folder; } } } private IEnumerable<ProjectItem> GetAllItems(ProjectItems projectItems) { if (projectItems == null) { return SpecializedCollections.EmptyEnumerable<ProjectItem>(); } var items = projectItems.OfType<ProjectItem>(); return items.Concat(items.SelectMany(i => GetAllItems(i.ProjectItems))); } #if false protected override void AddExistingDocument(DocumentId documentId, string filePath, IEnumerable<string> folders) { IVsHierarchy hierarchy; EnvDTE.Project project; IVisualStudioHostProject hostProject; GetProjectData(documentId.ProjectId, out hostProject, out hierarchy, out project); // If the first namespace name matches the name of the project, then we don't want to // generate a folder for that. The project is implicitly a folder with that name. if (folders.FirstOrDefault() == project.Name) { folders = folders.Skip(1); } var name = Path.GetFileName(filePath); if (folders.Any()) { AddDocumentToFolder(hostProject, project, documentId, folders, name, SourceCodeKind.Regular, initialText: null, filePath: filePath); } else { AddDocumentToProject(hostProject, project, documentId, name, SourceCodeKind.Regular, initialText: null, filePath: filePath); } } #endif private ProjectItem AddDocumentToProject( EnvDTE.Project project, DocumentId documentId, string documentName, TextDocumentKind documentKind, SourceText? initialText = null, string? filePath = null) { string? folderPath = null; if (filePath == null && !project.TryGetFullPath(out folderPath)) { // TODO(cyrusn): Throw an appropriate exception here. throw new Exception(ServicesVSResources.Could_not_find_location_of_folder_on_disk); } return AddDocumentToProjectItems(project.ProjectItems, documentId, folderPath, documentName, initialText, filePath, documentKind); } private ProjectItem AddDocumentToFolder( EnvDTE.Project project, DocumentId documentId, IEnumerable<string> folders, string documentName, TextDocumentKind documentKind, SourceText? initialText = null, string? filePath = null) { var folder = project.FindOrCreateFolder(folders); string? folderPath = null; if (filePath == null && !folder.TryGetFullPath(out folderPath)) { // TODO(cyrusn): Throw an appropriate exception here. throw new Exception(ServicesVSResources.Could_not_find_location_of_folder_on_disk); } return AddDocumentToProjectItems(folder.ProjectItems, documentId, folderPath, documentName, initialText, filePath, documentKind); } private ProjectItem AddDocumentToProjectItems( ProjectItems projectItems, DocumentId documentId, string? folderPath, string documentName, SourceText? initialText, string? filePath, TextDocumentKind documentKind) { if (filePath == null) { Contract.ThrowIfNull(folderPath, "If we didn't have a file path, then we expected a folder path to generate the file path from."); var baseName = Path.GetFileNameWithoutExtension(documentName); var extension = documentKind == TextDocumentKind.Document ? GetPreferredExtension(documentId) : Path.GetExtension(documentName); var uniqueName = projectItems.GetUniqueName(baseName, extension); filePath = Path.Combine(folderPath, uniqueName); } if (initialText != null) { using var writer = new StreamWriter(filePath, append: false, encoding: initialText.Encoding ?? Encoding.UTF8); initialText.Write(writer); } // TODO: restore document ID hinting -- we previously ensured that the AddFromFile will introduce the document ID being used here. // (tracked by https://devdiv.visualstudio.com/DevDiv/_workitems/edit/677956) return projectItems.AddFromFile(filePath); } private void RemoveDocumentCore(DocumentId documentId, TextDocumentKind documentKind) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } var document = this.CurrentSolution.GetTextDocument(documentId); if (document != null) { var hierarchy = this.GetHierarchy(documentId.ProjectId); Contract.ThrowIfNull(hierarchy, "Removing files from projects without hierarchies are not supported."); var text = document.GetTextSynchronously(CancellationToken.None); Contract.ThrowIfNull(document.FilePath, "Removing files from projects that don't have file names are not supported."); var itemId = hierarchy.TryGetItemId(document.FilePath); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // it is no longer part of the solution return; } var project = (IVsProject3)hierarchy; project.RemoveItem(0, itemId, out _); var undoManager = TryGetUndoManager(); var docInfo = CreateDocumentInfoWithoutText(document); switch (documentKind) { case TextDocumentKind.AdditionalDocument: undoManager?.Add(new AddAdditionalDocumentUndoUnit(this, docInfo, text)); break; case TextDocumentKind.AnalyzerConfigDocument: undoManager?.Add(new AddAnalyzerConfigDocumentUndoUnit(this, docInfo, text)); break; case TextDocumentKind.Document: undoManager?.Add(new AddDocumentUndoUnit(this, docInfo, text)); break; default: throw ExceptionUtilities.UnexpectedValue(documentKind); } } } protected override void ApplyDocumentRemoved(DocumentId documentId) => RemoveDocumentCore(documentId, TextDocumentKind.Document); protected override void ApplyAdditionalDocumentRemoved(DocumentId documentId) => RemoveDocumentCore(documentId, TextDocumentKind.AdditionalDocument); protected override void ApplyAnalyzerConfigDocumentRemoved(DocumentId documentId) => RemoveDocumentCore(documentId, TextDocumentKind.AnalyzerConfigDocument); public override void OpenDocument(DocumentId documentId, bool activate = true) => OpenDocumentCore(documentId, activate); public override void OpenAdditionalDocument(DocumentId documentId, bool activate = true) => OpenDocumentCore(documentId, activate); public override void OpenAnalyzerConfigDocument(DocumentId documentId, bool activate = true) => OpenDocumentCore(documentId, activate); public override void CloseDocument(DocumentId documentId) => CloseDocumentCore(documentId); public override void CloseAdditionalDocument(DocumentId documentId) => CloseDocumentCore(documentId); public override void CloseAnalyzerConfigDocument(DocumentId documentId) => CloseDocumentCore(documentId); public void OpenDocumentCore(DocumentId documentId, bool activate = true) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } if (!_foregroundObject.IsForeground()) { throw new InvalidOperationException(ServicesVSResources.This_workspace_only_supports_opening_documents_on_the_UI_thread); } var document = this.CurrentSolution.GetTextDocument(documentId); if (document != null) { OpenDocumentFromPath(document.FilePath, document.Project.Id, activate); } } internal void OpenDocumentFromPath(string? filePath, ProjectId projectId, bool activate = true) { if (TryGetFrame(filePath, projectId, out var frame)) { if (activate) { frame.Show(); } else { frame.ShowNoActivate(); } } } /// <summary> /// Opens a file and retrieves the window frame. /// </summary> /// <param name="filePath">the file path of the file to open.</param> /// <param name="projectId">used to retrieve the IVsHierarchy to ensure the file is opened in a matching context.</param> /// <param name="frame">the window frame.</param> /// <returns></returns> private bool TryGetFrame(string? filePath, ProjectId projectId, [NotNullWhen(returnValue: true)] out IVsWindowFrame? frame) { frame = null; if (filePath == null) { return false; } var hierarchy = GetHierarchy(projectId); var itemId = hierarchy?.TryGetItemId(filePath) ?? (uint)VSConstants.VSITEMID.Nil; if (itemId == (uint)VSConstants.VSITEMID.Nil) { // If the ItemId is Nil, then IVsProject would not be able to open the // document using its ItemId. Thus, we must use OpenDocumentViaProject, which only // depends on the file path. var openDocumentService = IServiceProviderExtensions.GetService<SVsUIShellOpenDocument, IVsUIShellOpenDocument>(ServiceProvider.GlobalProvider); return ErrorHandler.Succeeded(openDocumentService.OpenDocumentViaProject( filePath, VSConstants.LOGVIEWID.TextView_guid, out _, out _, out _, out frame)); } else { // If the ItemId is not Nil, then we should not call IVsUIShellDocument // .OpenDocumentViaProject here because that simply takes a file path and opens the // file within the context of the first project it finds. That would cause problems // if the document we're trying to open is actually a linked file in another // project. So, we get the project's hierarchy and open the document using its item // ID. // It's conceivable that IVsHierarchy might not implement IVsProject. However, // OpenDocumentViaProject itself relies upon this QI working, so it should be OK to // use here. return hierarchy is IVsProject vsProject && ErrorHandler.Succeeded(vsProject.OpenItem(itemId, VSConstants.LOGVIEWID.TextView_guid, s_docDataExisting_Unknown, out frame)); } } public void CloseDocumentCore(DocumentId documentId) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } if (this.IsDocumentOpen(documentId)) { var filePath = this.GetFilePath(documentId); if (filePath != null) { var openDocumentService = IServiceProviderExtensions.GetService<SVsUIShellOpenDocument, IVsUIShellOpenDocument>(ServiceProvider.GlobalProvider); if (ErrorHandler.Succeeded(openDocumentService.IsDocumentOpen(null, 0, filePath, Guid.Empty, 0, out _, null, out var frame, out _))) { // TODO: do we need save argument for CloseDocument? frame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave); } } } } protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText newText) => ApplyTextDocumentChange(documentId, newText); protected override void ApplyAdditionalDocumentTextChanged(DocumentId documentId, SourceText newText) => ApplyTextDocumentChange(documentId, newText); protected override void ApplyAnalyzerConfigDocumentTextChanged(DocumentId documentId, SourceText newText) => ApplyTextDocumentChange(documentId, newText); private void ApplyTextDocumentChange(DocumentId documentId, SourceText newText) { EnsureEditableDocuments(documentId); var containedDocument = TryGetContainedDocument(documentId); if (containedDocument != null) { containedDocument.UpdateText(newText); } else { if (IsDocumentOpen(documentId)) { var textBuffer = this.CurrentSolution.GetTextDocument(documentId)!.GetTextSynchronously(CancellationToken.None).Container.TryGetTextBuffer(); if (textBuffer != null) { TextEditApplication.UpdateText(newText, textBuffer, EditOptions.DefaultMinimalChange); return; } } // The document wasn't open in a normal way, so invisible editor time using var invisibleEditor = OpenInvisibleEditor(documentId); TextEditApplication.UpdateText(newText, invisibleEditor.TextBuffer, EditOptions.None); } } protected override void ApplyDocumentInfoChanged(DocumentId documentId, DocumentInfo updatedInfo) { var document = CurrentSolution.GetRequiredDocument(documentId); FailIfDocumentInfoChangesNotSupported(document, updatedInfo); if (document.Name != updatedInfo.Name) { GetProjectData(updatedInfo.Id.ProjectId, out var _, out var dteProject); if (document.FilePath == null) { FatalError.ReportAndCatch(new Exception("Attempting to change the information of a document without a file path.")); return; } var projectItemForDocument = dteProject.FindItemByPath(document.FilePath, StringComparer.OrdinalIgnoreCase); if (projectItemForDocument == null) { // TODO(https://github.com/dotnet/roslyn/issues/34276): Debug.Fail("Attempting to change the name of a file in a Shared Project"); return; } // Must save the document first for things like Breakpoints to be preserved. // WORKAROUND: Check if the document needs to be saved before calling save. // Should remove the if below and just call save() once // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1163405 // is fixed if (!projectItemForDocument.Saved) { projectItemForDocument.Save(); } var uniqueName = projectItemForDocument.Collection .GetUniqueNameIgnoringProjectItem( projectItemForDocument, Path.GetFileNameWithoutExtension(updatedInfo.Name), Path.GetExtension(updatedInfo.Name)); // Get the current undoManager before any file renames/documentId changes happen var undoManager = TryGetUndoManager(); // By setting this property, Visual Studio will perform the file rename, which // will cause the workspace's current solution to update and will fire the // necessary workspace changed events. projectItemForDocument.Name = uniqueName; if (projectItemForDocument.TryGetFullPath(out var newPath)) { undoManager?.Add(new RenameDocumentUndoUnit(this, uniqueName, document.Name, newPath)); } } } /// <summary> /// The <see cref="VisualStudioWorkspace"/> currently supports only a subset of <see cref="DocumentInfo"/> /// changes. /// </summary> private void FailIfDocumentInfoChangesNotSupported(CodeAnalysis.Document document, DocumentInfo updatedInfo) { if (document.SourceCodeKind != updatedInfo.SourceCodeKind) { throw new InvalidOperationException( $"This Workspace does not support changing a document's {nameof(document.SourceCodeKind)}."); } if (document.FilePath != updatedInfo.FilePath) { throw new InvalidOperationException( $"This Workspace does not support changing a document's {nameof(document.FilePath)}."); } if (document.Id != updatedInfo.Id) { throw new InvalidOperationException( $"This Workspace does not support changing a document's {nameof(document.Id)}."); } if (document.Folders != updatedInfo.Folders && !document.Folders.SequenceEqual(updatedInfo.Folders)) { throw new InvalidOperationException( $"This Workspace does not support changing a document's {nameof(document.Folders)}."); } if (document.State.Attributes.IsGenerated != updatedInfo.IsGenerated) { throw new InvalidOperationException( $"This Workspace does not support changing a document's {nameof(document.State.Attributes.IsGenerated)} state."); } } private string GetPreferredExtension(DocumentId documentId) { // No extension was provided. Pick a good one based on the type of host project. return CurrentSolution.GetRequiredProject(documentId.ProjectId).Language switch { // TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325 //return sourceCodeKind == SourceCodeKind.Regular ? ".cs" : ".csx"; LanguageNames.CSharp => ".cs", // TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325 //return sourceCodeKind == SourceCodeKind.Regular ? ".vb" : ".vbx"; LanguageNames.VisualBasic => ".vb", _ => throw new InvalidOperationException(), }; } public override IVsHierarchy? GetHierarchy(ProjectId projectId) { // This doesn't take a lock since _projectToHierarchyMap is immutable return _projectToHierarchyMap.GetValueOrDefault(projectId, defaultValue: null); } internal override Guid GetProjectGuid(ProjectId projectId) { // This doesn't take a lock since _projectToGuidMap is immutable return _projectToGuidMap.GetValueOrDefault(projectId, defaultValue: Guid.Empty); } internal string? TryGetDependencyNodeTargetIdentifier(ProjectId projectId) { // This doesn't take a lock since _projectToDependencyNodeTargetIdentifier is immutable _projectToDependencyNodeTargetIdentifier.TryGetValue(projectId, out var identifier); return identifier; } internal override void SetDocumentContext(DocumentId documentId) { _foregroundObject.AssertIsForeground(); // Note: this method does not actually call into any workspace code here to change the workspace's context. The assumption is updating the running document table or // IVsHierarchies will raise the appropriate events which we are subscribed to. lock (_gate) { var hierarchy = GetHierarchy(documentId.ProjectId); if (hierarchy == null) { // If we don't have a hierarchy then there's nothing we can do return; } // The hierarchy might be supporting multitargeting; in that case, let's update the context. Unfortunately the IVsHierarchies that support this // don't necessarily let us read it first, so we have to fire-and-forget here. foreach (var (projectSystemName, projects) in _projectSystemNameToProjectsMap) { if (projects.Any(p => p.Id == documentId.ProjectId)) { hierarchy.SetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID8.VSHPROPID_ActiveIntellisenseProjectContext, projectSystemName); // We've updated that property, but we still need to continue the rest of this process to ensure the Running Document Table is updated // and any shared asset projects are also updated. break; } } var filePath = GetFilePath(documentId); if (filePath == null) { return; } var itemId = hierarchy.TryGetItemId(filePath); if (itemId != VSConstants.VSITEMID_NIL) { // Is this owned by a shared asset project? If so, we need to put the shared asset project into the running document table, and need to set the // current hierarchy as the active context of that shared hierarchy. This is kept as a loop that we do multiple times in the case that you // have multiple pointers. This used to be the case for multitargeting projects, but that was now handled by setting the active context property // above. Some project systems out there might still be supporting it, so we'll support it too. while (SharedProjectUtilities.TryGetItemInSharedAssetsProject(hierarchy, itemId, out var sharedHierarchy, out var sharedItemId) && hierarchy != sharedHierarchy) { // Ensure the shared context is set correctly if (sharedHierarchy.GetActiveProjectContext() != hierarchy) { ErrorHandler.ThrowOnFailure(sharedHierarchy.SetActiveProjectContext(hierarchy)); } // We now need to ensure the outer project is also set up hierarchy = sharedHierarchy; itemId = sharedItemId; } } // Update the ownership of the file in the Running Document Table var project = (IVsProject3)hierarchy; project.TransferItem(filePath, filePath, punkWindowFrame: null); } } internal bool TryGetHierarchy(ProjectId projectId, [NotNullWhen(returnValue: true)] out IVsHierarchy? hierarchy) { hierarchy = this.GetHierarchy(projectId); return hierarchy != null; } protected override void Dispose(bool finalize) { if (!finalize) { _textBufferFactoryService.TextBufferCreated -= AddTextBufferCloneServiceToBuffer; _projectionBufferFactoryService.ProjectionBufferCreated -= AddTextBufferCloneServiceToBuffer; FileWatchedReferenceFactory.ReferenceChanged -= RefreshMetadataReferencesForFile; if (_lazyExternalErrorDiagnosticUpdateSource.IsValueCreated) { _lazyExternalErrorDiagnosticUpdateSource.Value.Dispose(); } } base.Dispose(finalize); } public void EnsureEditableDocuments(IEnumerable<DocumentId> documents) { var queryEdit = (IVsQueryEditQuerySave2)ServiceProvider.GlobalProvider.GetService(typeof(SVsQueryEditQuerySave)); // make sure given document id actually exist in current solution and the file is marked as supporting modifications // and actually has non null file path var fileNames = documents.Select(GetFilePath).ToArray(); // TODO: meditate about the flags we can pass to this and decide what is most appropriate for Roslyn var result = queryEdit.QueryEditFiles( rgfQueryEdit: 0, cFiles: fileNames.Length, rgpszMkDocuments: fileNames, rgrgf: new uint[fileNames.Length], rgFileInfo: new VSQEQS_FILE_ATTRIBUTE_DATA[fileNames.Length], pfEditVerdict: out var editVerdict, prgfMoreInfo: out var editResultFlags); if (ErrorHandler.Failed(result) || editVerdict != (uint)tagVSQueryEditResult.QER_EditOK) { throw new Exception("Unable to check out the files from source control."); } if ((editResultFlags & (uint)(tagVSQueryEditResultFlags2.QER_Changed | tagVSQueryEditResultFlags2.QER_Reloaded)) != 0) { throw new Exception("A file was reloaded during the source control checkout."); } } public void EnsureEditableDocuments(params DocumentId[] documents) => this.EnsureEditableDocuments((IEnumerable<DocumentId>)documents); internal override bool CanAddProjectReference(ProjectId referencingProject, ProjectId referencedProject) { _foregroundObject.AssertIsForeground(); if (!TryGetHierarchy(referencingProject, out var referencingHierarchy) || !TryGetHierarchy(referencedProject, out var referencedHierarchy)) { // Couldn't even get a hierarchy for this project. So we have to assume // that adding a reference is disallowed. return false; } // First we have to see if either project disallows the reference being added. const int ContextFlags = (int)__VSQUERYFLAVORREFERENCESCONTEXT.VSQUERYFLAVORREFERENCESCONTEXT_RefreshReference; var canAddProjectReference = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN; var canBeReferenced = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN; if (referencingHierarchy is IVsProjectFlavorReferences3 referencingProjectFlavor3) { if (ErrorHandler.Failed(referencingProjectFlavor3.QueryAddProjectReferenceEx(referencedHierarchy, ContextFlags, out canAddProjectReference, out _))) { // Something went wrong even trying to see if the reference would be allowed. // Assume it won't be allowed. return false; } if (canAddProjectReference == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY) { // Adding this project reference is not allowed. return false; } } if (referencedHierarchy is IVsProjectFlavorReferences3 referencedProjectFlavor3) { if (ErrorHandler.Failed(referencedProjectFlavor3.QueryCanBeReferencedEx(referencingHierarchy, ContextFlags, out canBeReferenced, out _))) { // Something went wrong even trying to see if the reference would be allowed. // Assume it won't be allowed. return false; } if (canBeReferenced == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY) { // Adding this project reference is not allowed. return false; } } // Neither project denied the reference being added. At this point, if either project // allows the reference to be added, and the other doesn't block it, then we can add // the reference. if (canAddProjectReference == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW || canBeReferenced == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW) { return true; } // In both directions things are still unknown. Fallback to the reference manager // to make the determination here. var referenceManager = (IVsReferenceManager)ServiceProvider.GlobalProvider.GetService(typeof(SVsReferenceManager)); if (referenceManager == null) { // Couldn't get the reference manager. Have to assume it's not allowed. return false; } // As long as the reference manager does not deny things, then we allow the // reference to be added. var result = referenceManager.QueryCanReferenceProject(referencingHierarchy, referencedHierarchy); return result != (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY; } /// <summary> /// Applies a single operation to the workspace. <paramref name="action"/> should be a call to one of the protected Workspace.On* methods. /// </summary> public void ApplyChangeToWorkspace(Action<Workspace> action) { lock (_gate) { action(this); } } /// <summary> /// Applies a solution transformation to the workspace and triggers workspace changed event for specified <paramref name="projectId"/>. /// The transformation shall only update the project of the solution with the specified <paramref name="projectId"/>. /// </summary> public void ApplyChangeToWorkspace(ProjectId projectId, Func<CodeAnalysis.Solution, CodeAnalysis.Solution> solutionTransformation) { lock (_gate) { SetCurrentSolution(solutionTransformation, WorkspaceChangeKind.ProjectChanged, projectId); } } /// <summary> /// Applies a change to the workspace that can do any number of project changes. /// </summary> /// <remarks>This is needed to synchronize with <see cref="ApplyChangeToWorkspace(Action{Workspace})" /> to avoid any races. This /// method could be moved down to the core Workspace layer and then could use the synchronization lock there.</remarks> public void ApplyBatchChangeToWorkspace(Func<CodeAnalysis.Solution, SolutionChangeAccumulator> mutation) { lock (_gate) { var oldSolution = this.CurrentSolution; var solutionChangeAccumulator = mutation(oldSolution); if (!solutionChangeAccumulator.HasChange) { return; } foreach (var documentId in solutionChangeAccumulator.DocumentIdsRemoved) { this.ClearDocumentData(documentId); } SetCurrentSolution(solutionChangeAccumulator.Solution); RaiseWorkspaceChangedEventAsync( solutionChangeAccumulator.WorkspaceChangeKind, oldSolution, solutionChangeAccumulator.Solution, solutionChangeAccumulator.WorkspaceChangeProjectId, solutionChangeAccumulator.WorkspaceChangeDocumentId); } } private readonly Dictionary<ProjectId, ProjectReferenceInformation> _projectReferenceInfoMap = new(); private ProjectReferenceInformation GetReferenceInfo_NoLock(ProjectId projectId) { Debug.Assert(Monitor.IsEntered(_gate)); return _projectReferenceInfoMap.GetOrAdd(projectId, _ => new ProjectReferenceInformation()); } protected internal override void OnProjectRemoved(ProjectId projectId) { lock (_gate) { var languageName = CurrentSolution.GetRequiredProject(projectId).Language; if (_projectReferenceInfoMap.TryGetValue(projectId, out var projectReferenceInfo)) { // If we still had any output paths, we'll want to remove them to cause conversion back to metadata references. // The call below implicitly is modifying the collection we've fetched, so we'll make a copy. foreach (var outputPath in projectReferenceInfo.OutputPaths.ToList()) { RemoveProjectOutputPath(projectId, outputPath); } _projectReferenceInfoMap.Remove(projectId); } _projectToHierarchyMap = _projectToHierarchyMap.Remove(projectId); _projectToGuidMap = _projectToGuidMap.Remove(projectId); // _projectToMaxSupportedLangVersionMap needs to be updated with ImmutableInterlocked since it can be mutated outside the lock ImmutableInterlocked.TryRemove<ProjectId, string?>(ref _projectToMaxSupportedLangVersionMap, projectId, out _); // _projectToDependencyNodeTargetIdentifier needs to be updated with ImmutableInterlocked since it can be mutated outside the lock ImmutableInterlocked.TryRemove(ref _projectToDependencyNodeTargetIdentifier, projectId, out _); _projectToRuleSetFilePath.Remove(projectId); foreach (var (projectName, projects) in _projectSystemNameToProjectsMap) { if (projects.RemoveAll(p => p.Id == projectId) > 0) { if (projects.Count == 0) { _projectSystemNameToProjectsMap.Remove(projectName); } break; } } base.OnProjectRemoved(projectId); // Try to update the UI context info. But cancel that work if we're shutting down. _threadingContext.RunWithShutdownBlockAsync(async cancellationToken => { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); RefreshProjectExistsUIContextForLanguage(languageName); }); } } private sealed class ProjectReferenceInformation { public readonly List<string> OutputPaths = new(); public readonly List<(string path, ProjectReference projectReference)> ConvertedProjectReferences = new List<(string path, ProjectReference)>(); } /// <summary> /// A multimap from an output path to the project outputting to it. Ideally, this shouldn't ever /// actually be a true multimap, since we shouldn't have two projects outputting to the same path, but /// any bug by a project adding the wrong output path means we could end up with some duplication. /// In that case, we'll temporarily have two until (hopefully) somebody removes it. /// </summary> private readonly Dictionary<string, List<ProjectId>> _projectsByOutputPath = new(StringComparer.OrdinalIgnoreCase); public void AddProjectOutputPath(ProjectId projectId, string outputPath) { lock (_gate) { var projectReferenceInformation = GetReferenceInfo_NoLock(projectId); projectReferenceInformation.OutputPaths.Add(outputPath); _projectsByOutputPath.MultiAdd(outputPath, projectId); var projectsForOutputPath = _projectsByOutputPath[outputPath]; var distinctProjectsForOutputPath = projectsForOutputPath.Distinct().ToList(); // If we have exactly one, then we're definitely good to convert if (projectsForOutputPath.Count == 1) { ConvertMetadataReferencesToProjectReferences_NoLock(projectId, outputPath); } else if (distinctProjectsForOutputPath.Count == 1) { // The same project has multiple output paths that are the same. Any project would have already been converted // by the prior add, so nothing further to do } else { // We have more than one project outputting to the same path. This shouldn't happen but we'll convert back // because now we don't know which project to reference. foreach (var otherProjectId in projectsForOutputPath) { // We know that since we're adding a path to projectId and we're here that we couldn't have already // had a converted reference to us, instead we need to convert things that are pointing to the project // we're colliding with if (otherProjectId != projectId) { ConvertProjectReferencesToMetadataReferences_NoLock(otherProjectId, outputPath); } } } } } /// <summary> /// Attempts to convert all metadata references to <paramref name="outputPath"/> to a project reference to <paramref name="projectId"/>. /// </summary> /// <param name="projectId">The <see cref="ProjectId"/> of the project that could be referenced in place of the output path.</param> /// <param name="outputPath">The output path to replace.</param> [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/31306", Constraint = "Avoid calling " + nameof(CodeAnalysis.Solution.GetProject) + " to avoid realizing all projects.")] private void ConvertMetadataReferencesToProjectReferences_NoLock(ProjectId projectId, string outputPath) { Debug.Assert(Monitor.IsEntered(_gate)); var modifiedSolution = this.CurrentSolution; using var _ = PooledHashSet<ProjectId>.GetInstance(out var projectIdsChanged); foreach (var projectIdToRetarget in this.CurrentSolution.ProjectIds) { if (CanConvertMetadataReferenceToProjectReference_NoLock(projectIdToRetarget, referencedProjectId: projectId)) { // PERF: call GetProjectState instead of GetProject, otherwise creating a new project might force all // Project instances to get created. foreach (PortableExecutableReference reference in modifiedSolution.GetProjectState(projectIdToRetarget)!.MetadataReferences) { if (string.Equals(reference.FilePath, outputPath, StringComparison.OrdinalIgnoreCase)) { FileWatchedReferenceFactory.StopWatchingReference(reference); var projectReference = new ProjectReference(projectId, reference.Properties.Aliases, reference.Properties.EmbedInteropTypes); modifiedSolution = modifiedSolution.RemoveMetadataReference(projectIdToRetarget, reference) .AddProjectReference(projectIdToRetarget, projectReference); projectIdsChanged.Add(projectIdToRetarget); GetReferenceInfo_NoLock(projectIdToRetarget).ConvertedProjectReferences.Add( (reference.FilePath!, projectReference)); // We have converted one, but you could have more than one reference with different aliases // that we need to convert, so we'll keep going } } } } SetSolutionAndRaiseWorkspaceChanged_NoLock(modifiedSolution, projectIdsChanged); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/31306", Constraint = "Avoid calling " + nameof(CodeAnalysis.Solution.GetProject) + " to avoid realizing all projects.")] private bool CanConvertMetadataReferenceToProjectReference_NoLock(ProjectId projectIdWithMetadataReference, ProjectId referencedProjectId) { Debug.Assert(Monitor.IsEntered(_gate)); // We can never make a project reference ourselves. This isn't a meaningful scenario, but if somebody does this by accident // we do want to throw exceptions. if (projectIdWithMetadataReference == referencedProjectId) { return false; } // PERF: call GetProjectState instead of GetProject, otherwise creating a new project might force all // Project instances to get created. var projectWithMetadataReference = CurrentSolution.GetProjectState(projectIdWithMetadataReference); var referencedProject = CurrentSolution.GetProjectState(referencedProjectId); Contract.ThrowIfNull(projectWithMetadataReference); Contract.ThrowIfNull(referencedProject); // We don't want to convert a metadata reference to a project reference if the project being referenced isn't something // we can create a Compilation for. For example, if we have a C# project, and it's referencing a F# project via a metadata reference // everything would be fine if we left it a metadata reference. Converting it to a project reference means we couldn't create a Compilation // anymore in the IDE, since the C# compilation would need to reference an F# compilation. F# projects referencing other F# projects though // do expect this to work, and so we'll always allow references through of the same language. if (projectWithMetadataReference.Language != referencedProject.Language) { if (projectWithMetadataReference.LanguageServices.GetService<ICompilationFactoryService>() != null && referencedProject.LanguageServices.GetService<ICompilationFactoryService>() == null) { // We're referencing something that we can't create a compilation from something that can, so keep the metadata reference return false; } } // If this is going to cause a circular reference, also disallow it if (CurrentSolution.GetProjectDependencyGraph().GetProjectsThatThisProjectTransitivelyDependsOn(referencedProjectId).Contains(projectIdWithMetadataReference)) { return false; } return true; } /// <summary> /// Finds all projects that had a project reference to <paramref name="projectId"/> and convert it back to a metadata reference. /// </summary> /// <param name="projectId">The <see cref="ProjectId"/> of the project being referenced.</param> /// <param name="outputPath">The output path of the given project to remove the link to.</param> [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/37616", Constraint = "Update ConvertedProjectReferences in place to avoid duplicate list allocations.")] private void ConvertProjectReferencesToMetadataReferences_NoLock(ProjectId projectId, string outputPath) { Debug.Assert(Monitor.IsEntered(_gate)); var modifiedSolution = this.CurrentSolution; using var _ = PooledHashSet<ProjectId>.GetInstance(out var projectIdsChanged); foreach (var projectIdToRetarget in this.CurrentSolution.ProjectIds) { var referenceInfo = GetReferenceInfo_NoLock(projectIdToRetarget); // Update ConvertedProjectReferences in place to avoid duplicate list allocations for (var i = 0; i < referenceInfo.ConvertedProjectReferences.Count; i++) { var convertedReference = referenceInfo.ConvertedProjectReferences[i]; if (string.Equals(convertedReference.path, outputPath, StringComparison.OrdinalIgnoreCase) && convertedReference.projectReference.ProjectId == projectId) { var metadataReference = FileWatchedReferenceFactory.CreateReferenceAndStartWatchingFile( convertedReference.path, new MetadataReferenceProperties( aliases: convertedReference.projectReference.Aliases, embedInteropTypes: convertedReference.projectReference.EmbedInteropTypes)); modifiedSolution = modifiedSolution.RemoveProjectReference(projectIdToRetarget, convertedReference.projectReference) .AddMetadataReference(projectIdToRetarget, metadataReference); projectIdsChanged.Add(projectIdToRetarget); referenceInfo.ConvertedProjectReferences.RemoveAt(i); // We have converted one, but you could have more than one reference with different aliases // that we need to convert, so we'll keep going. Make sure to decrement the index so we don't // skip any items. i--; } } } SetSolutionAndRaiseWorkspaceChanged_NoLock(modifiedSolution, projectIdsChanged); } public ProjectReference? TryCreateConvertedProjectReference_NoLock(ProjectId referencingProject, string path, MetadataReferenceProperties properties) { // Any conversion to or from project references must be done under the global workspace lock, // since that needs to be coordinated with updating all projects simultaneously. Debug.Assert(Monitor.IsEntered(_gate)); if (_projectsByOutputPath.TryGetValue(path, out var ids) && ids.Distinct().Count() == 1) { var projectIdToReference = ids.First(); if (CanConvertMetadataReferenceToProjectReference_NoLock(referencingProject, projectIdToReference)) { var projectReference = new ProjectReference( projectIdToReference, aliases: properties.Aliases, embedInteropTypes: properties.EmbedInteropTypes); GetReferenceInfo_NoLock(referencingProject).ConvertedProjectReferences.Add((path, projectReference)); return projectReference; } else { return null; } } else { return null; } } public ProjectReference? TryRemoveConvertedProjectReference_NoLock(ProjectId referencingProject, string path, MetadataReferenceProperties properties) { // Any conversion to or from project references must be done under the global workspace lock, // since that needs to be coordinated with updating all projects simultaneously. Debug.Assert(Monitor.IsEntered(_gate)); var projectReferenceInformation = GetReferenceInfo_NoLock(referencingProject); foreach (var convertedProject in projectReferenceInformation.ConvertedProjectReferences) { if (convertedProject.path == path && convertedProject.projectReference.EmbedInteropTypes == properties.EmbedInteropTypes && convertedProject.projectReference.Aliases.SequenceEqual(properties.Aliases)) { projectReferenceInformation.ConvertedProjectReferences.Remove(convertedProject); return convertedProject.projectReference; } } return null; } private void SetSolutionAndRaiseWorkspaceChanged_NoLock(CodeAnalysis.Solution modifiedSolution, ICollection<ProjectId> projectIdsChanged) { if (projectIdsChanged.Count > 0) { Debug.Assert(modifiedSolution != CurrentSolution); var originalSolution = this.CurrentSolution; SetCurrentSolution(modifiedSolution); if (projectIdsChanged.Count == 1) { RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.ProjectChanged, originalSolution, this.CurrentSolution, projectIdsChanged.Single()); } else { RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.SolutionChanged, originalSolution, this.CurrentSolution); } } else { // If they said nothing changed, than definitely nothing should have changed! Debug.Assert(modifiedSolution == CurrentSolution); } } public void RemoveProjectOutputPath(ProjectId projectId, string outputPath) { lock (_gate) { var projectReferenceInformation = GetReferenceInfo_NoLock(projectId); if (!projectReferenceInformation.OutputPaths.Contains(outputPath)) { throw new ArgumentException($"Project does not contain output path '{outputPath}'", nameof(outputPath)); } projectReferenceInformation.OutputPaths.Remove(outputPath); _projectsByOutputPath.MultiRemove(outputPath, projectId); // When a project is closed, we may need to convert project references to metadata references (or vice // versa). Failure to convert the references could leave a project in the workspace with a project // reference to a project which is not open. // // For the specific case where the entire solution is closing, we do not need to update the state for // remaining projects as each project closes, because we know those projects will be closed without // further use. Avoiding reference conversion when the solution is closing improves performance for both // IDE close scenarios and solution reload scenarios that occur after complex branch switches. if (!_solutionClosing) { if (_projectsByOutputPath.TryGetValue(outputPath, out var remainingProjectsForOutputPath)) { var distinctRemainingProjects = remainingProjectsForOutputPath.Distinct(); if (distinctRemainingProjects.Count() == 1) { // We had more than one project outputting to the same path. Now we're back down to one // so we can reference that one again ConvertMetadataReferencesToProjectReferences_NoLock(distinctRemainingProjects.Single(), outputPath); } } else { // No projects left, we need to convert back to metadata references ConvertProjectReferencesToMetadataReferences_NoLock(projectId, outputPath); } } } } private void RefreshMetadataReferencesForFile(object sender, string fullFilePath) { lock (_gate) { var newSolution = CurrentSolution; using var _ = PooledHashSet<ProjectId>.GetInstance(out var changedProjectIds); foreach (var project in CurrentSolution.Projects) { // Loop to find each reference with the given path. It's possible that there might be multiple references of the same path; // the project system could concievably add the same reference multiple times but with different aliases. It's also possible // we might not find the path at all: when we receive the file changed event, we aren't checking if the file is still // in the workspace at that time; it's possible it might have already been removed. foreach (var portableExecutableReference in project.MetadataReferences.OfType<PortableExecutableReference>()) { if (portableExecutableReference.FilePath == fullFilePath) { FileWatchedReferenceFactory.StopWatchingReference(portableExecutableReference); var newPortableExecutableReference = FileWatchedReferenceFactory.CreateReferenceAndStartWatchingFile( portableExecutableReference.FilePath, portableExecutableReference.Properties); newSolution = newSolution.RemoveMetadataReference(project.Id, portableExecutableReference) .AddMetadataReference(project.Id, newPortableExecutableReference); changedProjectIds.Add(project.Id); } } } SetSolutionAndRaiseWorkspaceChanged_NoLock(newSolution, changedProjectIds); } } internal async Task EnsureDocumentOptionProvidersInitializedAsync(CancellationToken cancellationToken) { // HACK: switch to the UI thread, ensure we initialize our options provider which depends on a // UI-affinitized experimentation service await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); _foregroundObject.AssertIsForeground(); if (_documentOptionsProvidersInitialized) { return; } _documentOptionsProvidersInitialized = true; RegisterDocumentOptionProviders(_documentOptionsProviderFactories); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/54137", AllowLocks = false)] internal void SetMaxLanguageVersion(ProjectId projectId, string? maxLanguageVersion) { ImmutableInterlocked.Update( ref _projectToMaxSupportedLangVersionMap, static (map, arg) => map.SetItem(arg.projectId, arg.maxLanguageVersion), (projectId, maxLanguageVersion)); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/54135", AllowLocks = false)] internal void SetDependencyNodeTargetIdentifier(ProjectId projectId, string targetIdentifier) { ImmutableInterlocked.Update( ref _projectToDependencyNodeTargetIdentifier, static (map, arg) => map.SetItem(arg.projectId, arg.targetIdentifier), (projectId, targetIdentifier)); } internal void RefreshProjectExistsUIContextForLanguage(string language) { // We must assert the call is on the foreground as setting UIContext.IsActive would otherwise do a COM RPC. _foregroundObject.AssertIsForeground(); lock (_gate) { var uiContext = _languageToProjectExistsUIContext.GetOrAdd( language, l => Services.GetLanguageServices(l).GetService<IProjectExistsUIContextProviderLanguageService>()?.GetUIContext()); // UIContexts can be "zombied" if UIContexts aren't supported because we're in a command line build or in other scenarios. if (uiContext != null && !uiContext.IsZombie) { uiContext.IsActive = CurrentSolution.Projects.Any(p => p.Language == language); } } } } }
1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/PathMetadataUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.LanguageServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal static class PathMetadataUtilities { private static readonly char[] NamespaceSeparatorArray = new[] { '.' }; /// <summary> /// Given a set of folders from build the namespace that would match /// the folder structure. If a document is located in { "Bat" , "Bar", "Baz" } then the namespace could be /// "Bat.Bar.Baz". If a rootNamespace is provided, it is prepended to the generated namespace. /// /// Returns null if the folders contain parts that are invalid identifiers for a namespace. /// </summary> public static string? TryBuildNamespaceFromFolders(IEnumerable<string> folders, ISyntaxFacts syntaxFacts, string? rootNamespace = null) { var parts = folders.SelectMany(folder => folder.Split(NamespaceSeparatorArray)).SelectAsArray(syntaxFacts.EscapeIdentifier); var constructedNamespace = parts.All(syntaxFacts.IsValidIdentifier) ? string.Join(".", parts) : null; if (constructedNamespace is null) { return null; } if (string.IsNullOrEmpty(rootNamespace)) { return constructedNamespace; } return $"{rootNamespace}.{constructedNamespace}"; } public static ImmutableArray<string> BuildFoldersFromNamespace(string? @namespace, string? rootNamespace = null) { if (@namespace is null || @namespace == rootNamespace) { return ImmutableArray<string>.Empty; } if (rootNamespace is not null && @namespace.StartsWith(rootNamespace + ".", StringComparison.OrdinalIgnoreCase)) { // Add 1 to get rid of the starting "." as well @namespace = @namespace.Substring(rootNamespace.Length + 1); } var parts = @namespace.Split(NamespaceSeparatorArray, options: StringSplitOptions.RemoveEmptyEntries); return parts.ToImmutableArray(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.LanguageServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal static class PathMetadataUtilities { private static readonly char[] NamespaceSeparatorArray = new[] { '.' }; /// <summary> /// Given a set of folders from build the namespace that would match /// the folder structure. If a document is located in { "Bat" , "Bar", "Baz" } then the namespace could be /// "Bat.Bar.Baz". If a rootNamespace is provided, it is prepended to the generated namespace. /// /// Returns null if the folders contain parts that are invalid identifiers for a namespace. /// </summary> public static string? TryBuildNamespaceFromFolders(IEnumerable<string> folders, ISyntaxFacts syntaxFacts, string? rootNamespace = null) { var parts = folders.SelectMany(folder => folder.Split(NamespaceSeparatorArray)).SelectAsArray(syntaxFacts.EscapeIdentifier); if (parts.IsDefaultOrEmpty) { return rootNamespace; } var constructedNamespace = parts.All(syntaxFacts.IsValidIdentifier) ? string.Join(".", parts) : null; if (constructedNamespace is null) { return null; } if (string.IsNullOrEmpty(rootNamespace)) { return constructedNamespace; } return $"{rootNamespace}.{constructedNamespace}"; } public static ImmutableArray<string> BuildFoldersFromNamespace(string? @namespace, string? rootNamespace = null) { if (@namespace is null || @namespace == rootNamespace) { return ImmutableArray<string>.Empty; } if (rootNamespace is not null && @namespace.StartsWith(rootNamespace + ".", StringComparison.OrdinalIgnoreCase)) { // Add 1 to get rid of the starting "." as well @namespace = @namespace.Substring(rootNamespace.Length + 1); } var parts = @namespace.Split(NamespaceSeparatorArray, options: StringSplitOptions.RemoveEmptyEntries); return parts.ToImmutableArray(); } } }
1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpCompleteStatement.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpCompleteStatement : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpCompleteStatement(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpCompleteStatement)) { } [WpfFact] public void UndoRestoresCaretPosition1() { SetUpEditor(@" public class Test { private object f; public void Method() { f.ToString($$) } } "); VisualStudio.Editor.SendKeys(';'); VisualStudio.Editor.Verify.CurrentLineText("f.ToString();$$", assertCaretPosition: true); VisualStudio.Editor.Undo(); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true); } [WpfFact] [WorkItem(43400, "https://github.com/dotnet/roslyn/issues/43400")] public void UndoRestoresCaretPosition2() { SetUpEditor(@" public class Test { private object f; public void Method() { Method(condition ? whenTrue $$) } } "); VisualStudio.Editor.SendKeys(';'); VisualStudio.Editor.Verify.CurrentLineText("Method(condition ? whenTrue );$$", assertCaretPosition: true); VisualStudio.Editor.Undo(); VisualStudio.Editor.Verify.CurrentLineText("Method(condition ? whenTrue $$)", assertCaretPosition: true); } [WpfFact] public void UndoRestoresFormatBeforeRestoringCaretPosition() { SetUpEditor(@" public class Test { private object f; public void Method() { f.ToString($$ ) } } "); VisualStudio.Editor.SendKeys(';'); VisualStudio.Editor.Verify.CurrentLineText("f.ToString();$$", assertCaretPosition: true); VisualStudio.Editor.Undo(); VisualStudio.Editor.Verify.CurrentLineText("f.ToString( );$$", assertCaretPosition: true); VisualStudio.Editor.Undo(); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$ )", assertCaretPosition: 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 Microsoft.CodeAnalysis; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpCompleteStatement : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpCompleteStatement(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpCompleteStatement)) { } [WpfFact] public void UndoRestoresCaretPosition1() { SetUpEditor(@" public class Test { private object f; public void Method() { f.ToString($$) } } "); VisualStudio.Editor.SendKeys(';'); VisualStudio.Editor.Verify.CurrentLineText("f.ToString();$$", assertCaretPosition: true); VisualStudio.Editor.Undo(); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$)", assertCaretPosition: true); } [WpfFact] [WorkItem(43400, "https://github.com/dotnet/roslyn/issues/43400")] public void UndoRestoresCaretPosition2() { SetUpEditor(@" public class Test { private object f; public void Method() { Method(condition ? whenTrue $$) } } "); VisualStudio.Editor.SendKeys(';'); VisualStudio.Editor.Verify.CurrentLineText("Method(condition ? whenTrue );$$", assertCaretPosition: true); VisualStudio.Editor.Undo(); VisualStudio.Editor.Verify.CurrentLineText("Method(condition ? whenTrue $$)", assertCaretPosition: true); } [WpfFact] public void UndoRestoresFormatBeforeRestoringCaretPosition() { SetUpEditor(@" public class Test { private object f; public void Method() { f.ToString($$ ) } } "); VisualStudio.Editor.SendKeys(';'); VisualStudio.Editor.Verify.CurrentLineText("f.ToString();$$", assertCaretPosition: true); VisualStudio.Editor.Undo(); VisualStudio.Editor.Verify.CurrentLineText("f.ToString( );$$", assertCaretPosition: true); VisualStudio.Editor.Undo(); VisualStudio.Editor.Verify.CurrentLineText("f.ToString($$ )", assertCaretPosition: true); } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Compilers/CSharp/Test/WinRT/Metadata/WinMdMetadataTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { // Unit tests for programs that use the Windows.winmd file. // // Checks to see that types are forwarded correctly, that // metadata files are loaded as they should, etc. public class WinMdMetadataTests : CSharpTestBase { /// <summary> /// Make sure that the members of a function are forwarded to their appropriate types. /// We do this by checking that the first parameter of /// Windows.UI.Text.ITextRange.SetPoint(Point p...) gets forwarded to the /// System.Runtime.WindowsRuntime assembly. /// </summary> [Fact] public void FunctionSignatureForwarded() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); wns1 = wns1.GetMember<NamespaceSymbol>("UI"); wns1 = wns1.GetMember<NamespaceSymbol>("Text"); var itextrange = wns1.GetMember<PENamedTypeSymbol>("ITextRange"); var func = itextrange.GetMember<PEMethodSymbol>("SetPoint"); var pt = ((PEParameterSymbol)(func.Parameters[0])).Type as PENamedTypeSymbol; Assert.Equal("System.Runtime.WindowsRuntime", pt.ContainingAssembly.Name); } /// <summary> /// Make sure that a delegate defined in Windows.winmd has a public constructor /// (by default, all delegates in Windows.winmd have a private constructor). /// </summary> [Fact] public void DelegateConstructorMarkedPublic() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); wns1 = wns1.GetMember<NamespaceSymbol>("UI"); wns1 = wns1.GetMember<NamespaceSymbol>("Xaml"); var itextrange = wns1.GetMember<PENamedTypeSymbol>("SuspendingEventHandler"); var func = itextrange.GetMember<PEMethodSymbol>(".ctor"); Assert.Equal(Accessibility.Public, func.DeclaredAccessibility); } /// <summary> /// Verify that Windows.Foundation.Uri forwards successfully /// to System.Uri /// </summary> [Fact] public void TypeForwardingRenaming() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); wns1 = wns1.GetMember<NamespaceSymbol>("Foundation"); var iref = wns1.GetMember<PENamedTypeSymbol>("IUriRuntimeClass"); var func = iref.GetMember<PEMethodSymbol>("CombineUri"); var ret = func.ReturnTypeWithAnnotations; Assert.Equal("System.Uri", func.ReturnType.ToTestDisplayString()); } /// <summary> /// Verify that WinMd types are marked as private so that the /// C# developer cannot instantiate them. /// </summary> [Fact] public void WinMdTypesDefPrivate() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); var wns2 = wns1.GetMember<NamespaceSymbol>("Foundation"); var clas = wns2.GetMember<PENamedTypeSymbol>("Point"); Assert.Equal(Accessibility.Internal, clas.DeclaredAccessibility); } /// <summary> /// Verify that Windows.UI.Colors.Black is forwarded to the /// System.Runtime.WindowsRuntime.dll assembly. /// </summary> [Fact] public void WinMdColorType() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); var wns2 = wns1.GetMember<NamespaceSymbol>("UI"); var clas = wns2.GetMember<TypeSymbol>("Colors"); var blk = clas.GetMembers("Black").Single(); //The windows.winmd module points to a Windows.UI.Color which should be modified to belong //to System.Runtime.WindowsRuntime Assert.Equal("System.Runtime.WindowsRuntime.dll", ((PENamedTypeSymbol)((((PropertySymbol)(blk)).GetMethod).ReturnType)).ContainingModule.ToString()); } /// <summary> /// Ensure that a simple program that uses projected types can compile /// and run. /// </summary> [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void WinMdColorTest() { var text = @"using Windows.UI; using Windows.Foundation; public class A{ public static void Main(){ var a = Colors.Black; System.Console.WriteLine(a.ToString()); } };"; CompileAndVerify(text, WinRtRefs, targetFramework: TargetFramework.Empty, expectedOutput: "#FF000000"); } /// <summary> /// Test that the metadata adapter correctly projects IReference to INullable /// </summary> [Fact] public void IReferenceToINullableType() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); var wns2 = wns1.GetMember<NamespaceSymbol>("Globalization"); var wns3 = wns2.GetMember<NamespaceSymbol>("NumberFormatting"); var clas = wns3.GetMember<TypeSymbol>("DecimalFormatter"); var puint = clas.GetMembers("ParseUInt").Single(); // The return type of ParseUInt should be Nullable<ulong>, not IReference<ulong> Assert.Equal("ulong?", ((Microsoft.CodeAnalysis.CSharp.Symbols.ConstructedNamedTypeSymbol) (((Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)puint).ReturnType)).ToString()); } /// <summary> /// Test that a program projects IReference to INullable. /// </summary> [Fact] public void WinMdIReferenceINullableTest() { var source = @"using System; using Windows.Globalization.NumberFormatting; public class C { public static void Main(string[] args) { var format = new DecimalFormatter(); ulong result = format.ParseUInt(""10"") ?? 0; Console.WriteLine(result); result = format.ParseUInt(""-1"") ?? 0; Console.WriteLine(result); } }"; var verifier = this.CompileAndVerifyOnWin8Only(source, expectedOutput: "10\r\n0"); verifier.VerifyDiagnostics(); } [Fact, WorkItem(1169511, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1169511")] public void WinMdAssemblyQualifiedType() { var source = @"using System; [MyAttribute(typeof(C1))] public class C { public static void Main(string[] args) { } } public class MyAttribute : System.Attribute { public MyAttribute(System.Type type) { } } "; CompileAndVerify( source, WinRtRefs.Concat(new[] { AssemblyMetadata.CreateFromImage(TestResources.WinRt.W1).GetReference() }), targetFramework: TargetFramework.Empty, symbolValidator: m => { var module = (PEModuleSymbol)m; var c = (PENamedTypeSymbol)module.GlobalNamespace.GetTypeMember("C"); var attributeHandle = module.Module.MetadataReader.GetCustomAttributes(c.Handle).Single(); string value; module.Module.TryExtractStringValueFromAttribute(attributeHandle, out value); Assert.Equal("C1, W, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime", value); }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { // Unit tests for programs that use the Windows.winmd file. // // Checks to see that types are forwarded correctly, that // metadata files are loaded as they should, etc. public class WinMdMetadataTests : CSharpTestBase { /// <summary> /// Make sure that the members of a function are forwarded to their appropriate types. /// We do this by checking that the first parameter of /// Windows.UI.Text.ITextRange.SetPoint(Point p...) gets forwarded to the /// System.Runtime.WindowsRuntime assembly. /// </summary> [Fact] public void FunctionSignatureForwarded() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); wns1 = wns1.GetMember<NamespaceSymbol>("UI"); wns1 = wns1.GetMember<NamespaceSymbol>("Text"); var itextrange = wns1.GetMember<PENamedTypeSymbol>("ITextRange"); var func = itextrange.GetMember<PEMethodSymbol>("SetPoint"); var pt = ((PEParameterSymbol)(func.Parameters[0])).Type as PENamedTypeSymbol; Assert.Equal("System.Runtime.WindowsRuntime", pt.ContainingAssembly.Name); } /// <summary> /// Make sure that a delegate defined in Windows.winmd has a public constructor /// (by default, all delegates in Windows.winmd have a private constructor). /// </summary> [Fact] public void DelegateConstructorMarkedPublic() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); wns1 = wns1.GetMember<NamespaceSymbol>("UI"); wns1 = wns1.GetMember<NamespaceSymbol>("Xaml"); var itextrange = wns1.GetMember<PENamedTypeSymbol>("SuspendingEventHandler"); var func = itextrange.GetMember<PEMethodSymbol>(".ctor"); Assert.Equal(Accessibility.Public, func.DeclaredAccessibility); } /// <summary> /// Verify that Windows.Foundation.Uri forwards successfully /// to System.Uri /// </summary> [Fact] public void TypeForwardingRenaming() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); wns1 = wns1.GetMember<NamespaceSymbol>("Foundation"); var iref = wns1.GetMember<PENamedTypeSymbol>("IUriRuntimeClass"); var func = iref.GetMember<PEMethodSymbol>("CombineUri"); var ret = func.ReturnTypeWithAnnotations; Assert.Equal("System.Uri", func.ReturnType.ToTestDisplayString()); } /// <summary> /// Verify that WinMd types are marked as private so that the /// C# developer cannot instantiate them. /// </summary> [Fact] public void WinMdTypesDefPrivate() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); var wns2 = wns1.GetMember<NamespaceSymbol>("Foundation"); var clas = wns2.GetMember<PENamedTypeSymbol>("Point"); Assert.Equal(Accessibility.Internal, clas.DeclaredAccessibility); } /// <summary> /// Verify that Windows.UI.Colors.Black is forwarded to the /// System.Runtime.WindowsRuntime.dll assembly. /// </summary> [Fact] public void WinMdColorType() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); var wns2 = wns1.GetMember<NamespaceSymbol>("UI"); var clas = wns2.GetMember<TypeSymbol>("Colors"); var blk = clas.GetMembers("Black").Single(); //The windows.winmd module points to a Windows.UI.Color which should be modified to belong //to System.Runtime.WindowsRuntime Assert.Equal("System.Runtime.WindowsRuntime.dll", ((PENamedTypeSymbol)((((PropertySymbol)(blk)).GetMethod).ReturnType)).ContainingModule.ToString()); } /// <summary> /// Ensure that a simple program that uses projected types can compile /// and run. /// </summary> [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void WinMdColorTest() { var text = @"using Windows.UI; using Windows.Foundation; public class A{ public static void Main(){ var a = Colors.Black; System.Console.WriteLine(a.ToString()); } };"; CompileAndVerify(text, WinRtRefs, targetFramework: TargetFramework.Empty, expectedOutput: "#FF000000"); } /// <summary> /// Test that the metadata adapter correctly projects IReference to INullable /// </summary> [Fact] public void IReferenceToINullableType() { var text = "public class A{};"; var comp = CreateCompilationWithWinRT(text); var winmdlib = comp.ExternalReferences.Where(r => r.Display == "Windows").Single(); var winmdNS = comp.GetReferencedAssemblySymbol(winmdlib); var wns1 = winmdNS.GlobalNamespace.GetMember<NamespaceSymbol>("Windows"); var wns2 = wns1.GetMember<NamespaceSymbol>("Globalization"); var wns3 = wns2.GetMember<NamespaceSymbol>("NumberFormatting"); var clas = wns3.GetMember<TypeSymbol>("DecimalFormatter"); var puint = clas.GetMembers("ParseUInt").Single(); // The return type of ParseUInt should be Nullable<ulong>, not IReference<ulong> Assert.Equal("ulong?", ((Microsoft.CodeAnalysis.CSharp.Symbols.ConstructedNamedTypeSymbol) (((Microsoft.CodeAnalysis.CSharp.Symbols.MethodSymbol)puint).ReturnType)).ToString()); } /// <summary> /// Test that a program projects IReference to INullable. /// </summary> [Fact] public void WinMdIReferenceINullableTest() { var source = @"using System; using Windows.Globalization.NumberFormatting; public class C { public static void Main(string[] args) { var format = new DecimalFormatter(); ulong result = format.ParseUInt(""10"") ?? 0; Console.WriteLine(result); result = format.ParseUInt(""-1"") ?? 0; Console.WriteLine(result); } }"; var verifier = this.CompileAndVerifyOnWin8Only(source, expectedOutput: "10\r\n0"); verifier.VerifyDiagnostics(); } [Fact, WorkItem(1169511, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1169511")] public void WinMdAssemblyQualifiedType() { var source = @"using System; [MyAttribute(typeof(C1))] public class C { public static void Main(string[] args) { } } public class MyAttribute : System.Attribute { public MyAttribute(System.Type type) { } } "; CompileAndVerify( source, WinRtRefs.Concat(new[] { AssemblyMetadata.CreateFromImage(TestResources.WinRt.W1).GetReference() }), targetFramework: TargetFramework.Empty, symbolValidator: m => { var module = (PEModuleSymbol)m; var c = (PENamedTypeSymbol)module.GlobalNamespace.GetTypeMember("C"); var attributeHandle = module.Module.MetadataReader.GetCustomAttributes(c.Handle).Single(); string value; module.Module.TryExtractStringValueFromAttribute(attributeHandle, out value); Assert.Equal("C1, W, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime", value); }); } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Workspaces/Core/Portable/FindSymbols/SymbolFinder.FindReferencesServerCallback.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { public static partial class SymbolFinder { /// <summary> /// Callback object we pass to the OOP server to hear about the result /// of the FindReferencesEngine as it executes there. /// </summary> internal sealed class FindReferencesServerCallback { private readonly Solution _solution; private readonly IStreamingFindReferencesProgress _progress; private readonly object _gate = new(); private readonly Dictionary<SerializableSymbolGroup, SymbolGroup> _groupMap = new(); private readonly Dictionary<SerializableSymbolAndProjectId, ISymbol> _definitionMap = new(); public FindReferencesServerCallback( Solution solution, IStreamingFindReferencesProgress progress) { _solution = solution; _progress = progress; } public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) => _progress.ProgressTracker.AddItemsAsync(count, cancellationToken); public ValueTask ItemCompletedAsync(CancellationToken cancellationToken) => _progress.ProgressTracker.ItemCompletedAsync(cancellationToken); public ValueTask OnStartedAsync(CancellationToken cancellationToken) => _progress.OnStartedAsync(cancellationToken); public ValueTask OnCompletedAsync(CancellationToken cancellationToken) => _progress.OnCompletedAsync(cancellationToken); public ValueTask OnFindInDocumentStartedAsync(DocumentId documentId, CancellationToken cancellationToken) { var document = _solution.GetDocument(documentId); return _progress.OnFindInDocumentStartedAsync(document, cancellationToken); } public ValueTask OnFindInDocumentCompletedAsync(DocumentId documentId, CancellationToken cancellationToken) { var document = _solution.GetDocument(documentId); return _progress.OnFindInDocumentCompletedAsync(document, cancellationToken); } public async ValueTask OnDefinitionFoundAsync(SerializableSymbolGroup dehydrated, CancellationToken cancellationToken) { Contract.ThrowIfTrue(dehydrated.Symbols.Count == 0); using var _ = PooledDictionary<SerializableSymbolAndProjectId, ISymbol>.GetInstance(out var map); foreach (var symbolAndProjectId in dehydrated.Symbols) { var symbol = await symbolAndProjectId.TryRehydrateAsync(_solution, cancellationToken).ConfigureAwait(false); if (symbol == null) return; map[symbolAndProjectId] = symbol; } var symbolGroup = new SymbolGroup(map.Values.ToImmutableArray()); lock (_gate) { _groupMap[dehydrated] = symbolGroup; foreach (var pair in map) _definitionMap[pair.Key] = pair.Value; } await _progress.OnDefinitionFoundAsync(symbolGroup, cancellationToken).ConfigureAwait(false); } public async ValueTask OnReferenceFoundAsync( SerializableSymbolGroup serializableSymbolGroup, SerializableSymbolAndProjectId serializableSymbol, SerializableReferenceLocation reference, CancellationToken cancellationToken) { SymbolGroup symbolGroup; ISymbol symbol; lock (_gate) { // The definition may not be in the map if we failed to map it over using TryRehydrateAsync in OnDefinitionFoundAsync. // Just ignore this reference. Note: while this is a degraded experience: // // 1. TryRehydrateAsync logs an NFE so we can track down while we're failing to roundtrip the // definition so we can track down that issue. // 2. NFE'ing and failing to show a result, is much better than NFE'ing and then crashing // immediately afterwards. if (!_groupMap.TryGetValue(serializableSymbolGroup, out symbolGroup) || !_definitionMap.TryGetValue(serializableSymbol, out symbol)) { return; } } var referenceLocation = await reference.RehydrateAsync( _solution, cancellationToken).ConfigureAwait(false); await _progress.OnReferenceFoundAsync(symbolGroup, symbol, referenceLocation, cancellationToken).ConfigureAwait(false); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { public static partial class SymbolFinder { /// <summary> /// Callback object we pass to the OOP server to hear about the result /// of the FindReferencesEngine as it executes there. /// </summary> internal sealed class FindReferencesServerCallback { private readonly Solution _solution; private readonly IStreamingFindReferencesProgress _progress; private readonly object _gate = new(); private readonly Dictionary<SerializableSymbolGroup, SymbolGroup> _groupMap = new(); private readonly Dictionary<SerializableSymbolAndProjectId, ISymbol> _definitionMap = new(); public FindReferencesServerCallback( Solution solution, IStreamingFindReferencesProgress progress) { _solution = solution; _progress = progress; } public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) => _progress.ProgressTracker.AddItemsAsync(count, cancellationToken); public ValueTask ItemCompletedAsync(CancellationToken cancellationToken) => _progress.ProgressTracker.ItemCompletedAsync(cancellationToken); public ValueTask OnStartedAsync(CancellationToken cancellationToken) => _progress.OnStartedAsync(cancellationToken); public ValueTask OnCompletedAsync(CancellationToken cancellationToken) => _progress.OnCompletedAsync(cancellationToken); public ValueTask OnFindInDocumentStartedAsync(DocumentId documentId, CancellationToken cancellationToken) { var document = _solution.GetDocument(documentId); return _progress.OnFindInDocumentStartedAsync(document, cancellationToken); } public ValueTask OnFindInDocumentCompletedAsync(DocumentId documentId, CancellationToken cancellationToken) { var document = _solution.GetDocument(documentId); return _progress.OnFindInDocumentCompletedAsync(document, cancellationToken); } public async ValueTask OnDefinitionFoundAsync(SerializableSymbolGroup dehydrated, CancellationToken cancellationToken) { Contract.ThrowIfTrue(dehydrated.Symbols.Count == 0); using var _ = PooledDictionary<SerializableSymbolAndProjectId, ISymbol>.GetInstance(out var map); foreach (var symbolAndProjectId in dehydrated.Symbols) { var symbol = await symbolAndProjectId.TryRehydrateAsync(_solution, cancellationToken).ConfigureAwait(false); if (symbol == null) return; map[symbolAndProjectId] = symbol; } var symbolGroup = new SymbolGroup(map.Values.ToImmutableArray()); lock (_gate) { _groupMap[dehydrated] = symbolGroup; foreach (var pair in map) _definitionMap[pair.Key] = pair.Value; } await _progress.OnDefinitionFoundAsync(symbolGroup, cancellationToken).ConfigureAwait(false); } public async ValueTask OnReferenceFoundAsync( SerializableSymbolGroup serializableSymbolGroup, SerializableSymbolAndProjectId serializableSymbol, SerializableReferenceLocation reference, CancellationToken cancellationToken) { SymbolGroup symbolGroup; ISymbol symbol; lock (_gate) { // The definition may not be in the map if we failed to map it over using TryRehydrateAsync in OnDefinitionFoundAsync. // Just ignore this reference. Note: while this is a degraded experience: // // 1. TryRehydrateAsync logs an NFE so we can track down while we're failing to roundtrip the // definition so we can track down that issue. // 2. NFE'ing and failing to show a result, is much better than NFE'ing and then crashing // immediately afterwards. if (!_groupMap.TryGetValue(serializableSymbolGroup, out symbolGroup) || !_definitionMap.TryGetValue(serializableSymbol, out symbol)) { return; } } var referenceLocation = await reference.RehydrateAsync( _solution, cancellationToken).ConfigureAwait(false); await _progress.OnReferenceFoundAsync(symbolGroup, symbol, referenceLocation, cancellationToken).ConfigureAwait(false); } } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Features/Core/Portable/Navigation/ISymbolNavigationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Navigation { internal interface ISymbolNavigationService : IWorkspaceService { /// <summary> /// Navigate to the first source location of a given symbol. /// </summary> /// <param name="project">A project context with which to generate source for symbol /// if it has no source locations</param> /// <param name="symbol">The symbol to navigate to</param> /// <param name="options">A set of options. If these options are not supplied the /// current set of options from the project's workspace will be used.</param> /// <param name="cancellationToken">The token to check for cancellation</param> bool TryNavigateToSymbol(ISymbol symbol, Project project, OptionSet? options = null, CancellationToken cancellationToken = default); /// <returns>True if the navigation was handled, indicating that the caller should not /// perform the navigation.</returns> Task<bool> TrySymbolNavigationNotifyAsync(ISymbol symbol, Project project, CancellationToken cancellationToken); /// <returns>True if the navigation would be handled.</returns> bool WouldNavigateToSymbol( DefinitionItem definitionItem, Solution solution, CancellationToken cancellationToken, [NotNullWhen(true)] out string? filePath, out int lineNumber, out int charOffset); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Navigation { internal interface ISymbolNavigationService : IWorkspaceService { /// <summary> /// Navigate to the first source location of a given symbol. /// </summary> /// <param name="project">A project context with which to generate source for symbol /// if it has no source locations</param> /// <param name="symbol">The symbol to navigate to</param> /// <param name="options">A set of options. If these options are not supplied the /// current set of options from the project's workspace will be used.</param> /// <param name="cancellationToken">The token to check for cancellation</param> bool TryNavigateToSymbol(ISymbol symbol, Project project, OptionSet? options = null, CancellationToken cancellationToken = default); /// <returns>True if the navigation was handled, indicating that the caller should not /// perform the navigation.</returns> Task<bool> TrySymbolNavigationNotifyAsync(ISymbol symbol, Project project, CancellationToken cancellationToken); /// <returns>True if the navigation would be handled.</returns> bool WouldNavigateToSymbol( DefinitionItem definitionItem, Solution solution, CancellationToken cancellationToken, [NotNullWhen(true)] out string? filePath, out int lineNumber, out int charOffset); } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Compilers/CSharp/Portable/Syntax/BaseMethodDeclarationSyntax.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class BaseMethodDeclarationSyntax { public abstract override SyntaxList<AttributeListSyntax> AttributeLists { get; } public abstract override SyntaxTokenList Modifiers { 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. namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class BaseMethodDeclarationSyntax { public abstract override SyntaxList<AttributeListSyntax> AttributeLists { get; } public abstract override SyntaxTokenList Modifiers { get; } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/EditorFeatures/Core.Wpf/SignatureHelp/Controller_OnTextViewBufferPostChanged.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp { internal partial class Controller { internal override void OnTextViewBufferPostChanged(object sender, EventArgs args) => Retrigger(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp { internal partial class Controller { internal override void OnTextViewBufferPostChanged(object sender, EventArgs args) => Retrigger(); } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Compilers/CSharp/Portable/Symbols/Wrapped/WrappedParameterSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.CSharp.Emit; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a parameter that is based on another parameter. /// When inheriting from this class, one shouldn't assume that /// the default behavior it has is appropriate for every case. /// That behavior should be carefully reviewed and derived type /// should override behavior as appropriate. /// </summary> internal abstract class WrappedParameterSymbol : ParameterSymbol { protected readonly ParameterSymbol _underlyingParameter; protected WrappedParameterSymbol(ParameterSymbol underlyingParameter) { Debug.Assert((object)underlyingParameter != null); this._underlyingParameter = underlyingParameter; } public ParameterSymbol UnderlyingParameter => _underlyingParameter; public sealed override bool IsDiscard => _underlyingParameter.IsDiscard; #region Forwarded public override TypeWithAnnotations TypeWithAnnotations { get { return _underlyingParameter.TypeWithAnnotations; } } public sealed override RefKind RefKind { get { return _underlyingParameter.RefKind; } } internal sealed override bool IsMetadataIn { get { return _underlyingParameter.IsMetadataIn; } } internal sealed override bool IsMetadataOut { get { return _underlyingParameter.IsMetadataOut; } } public sealed override ImmutableArray<Location> Locations { get { return _underlyingParameter.Locations; } } public sealed override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return _underlyingParameter.DeclaringSyntaxReferences; } } public override ImmutableArray<CSharpAttributeData> GetAttributes() { return _underlyingParameter.GetAttributes(); } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { _underlyingParameter.AddSynthesizedAttributes(moduleBuilder, ref attributes); } internal sealed override ConstantValue ExplicitDefaultConstantValue { get { return _underlyingParameter.ExplicitDefaultConstantValue; } } public override int Ordinal { get { return _underlyingParameter.Ordinal; } } public override bool IsParams { get { return _underlyingParameter.IsParams; } } internal override bool IsMetadataOptional { get { return _underlyingParameter.IsMetadataOptional; } } public override bool IsImplicitlyDeclared { get { return _underlyingParameter.IsImplicitlyDeclared; } } public sealed override string Name { get { return _underlyingParameter.Name; } } public sealed override string MetadataName { get { return _underlyingParameter.MetadataName; } } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return _underlyingParameter.RefCustomModifiers; } } internal override MarshalPseudoCustomAttributeData MarshallingInformation { get { return _underlyingParameter.MarshallingInformation; } } internal override UnmanagedType MarshallingType { get { return _underlyingParameter.MarshallingType; } } internal override bool IsIDispatchConstant { get { return _underlyingParameter.IsIDispatchConstant; } } internal override bool IsIUnknownConstant { get { return _underlyingParameter.IsIUnknownConstant; } } internal override FlowAnalysisAnnotations FlowAnalysisAnnotations { // https://github.com/dotnet/roslyn/issues/30073: Consider moving to leaf types get { return _underlyingParameter.FlowAnalysisAnnotations; } } internal override ImmutableHashSet<string> NotNullIfParameterNotNull { get { return _underlyingParameter.NotNullIfParameterNotNull; } } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default) { return _underlyingParameter.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); } #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.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.CSharp.Emit; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a parameter that is based on another parameter. /// When inheriting from this class, one shouldn't assume that /// the default behavior it has is appropriate for every case. /// That behavior should be carefully reviewed and derived type /// should override behavior as appropriate. /// </summary> internal abstract class WrappedParameterSymbol : ParameterSymbol { protected readonly ParameterSymbol _underlyingParameter; protected WrappedParameterSymbol(ParameterSymbol underlyingParameter) { Debug.Assert((object)underlyingParameter != null); this._underlyingParameter = underlyingParameter; } public ParameterSymbol UnderlyingParameter => _underlyingParameter; public sealed override bool IsDiscard => _underlyingParameter.IsDiscard; #region Forwarded public override TypeWithAnnotations TypeWithAnnotations { get { return _underlyingParameter.TypeWithAnnotations; } } public sealed override RefKind RefKind { get { return _underlyingParameter.RefKind; } } internal sealed override bool IsMetadataIn { get { return _underlyingParameter.IsMetadataIn; } } internal sealed override bool IsMetadataOut { get { return _underlyingParameter.IsMetadataOut; } } public sealed override ImmutableArray<Location> Locations { get { return _underlyingParameter.Locations; } } public sealed override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return _underlyingParameter.DeclaringSyntaxReferences; } } public override ImmutableArray<CSharpAttributeData> GetAttributes() { return _underlyingParameter.GetAttributes(); } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { _underlyingParameter.AddSynthesizedAttributes(moduleBuilder, ref attributes); } internal sealed override ConstantValue ExplicitDefaultConstantValue { get { return _underlyingParameter.ExplicitDefaultConstantValue; } } public override int Ordinal { get { return _underlyingParameter.Ordinal; } } public override bool IsParams { get { return _underlyingParameter.IsParams; } } internal override bool IsMetadataOptional { get { return _underlyingParameter.IsMetadataOptional; } } public override bool IsImplicitlyDeclared { get { return _underlyingParameter.IsImplicitlyDeclared; } } public sealed override string Name { get { return _underlyingParameter.Name; } } public sealed override string MetadataName { get { return _underlyingParameter.MetadataName; } } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return _underlyingParameter.RefCustomModifiers; } } internal override MarshalPseudoCustomAttributeData MarshallingInformation { get { return _underlyingParameter.MarshallingInformation; } } internal override UnmanagedType MarshallingType { get { return _underlyingParameter.MarshallingType; } } internal override bool IsIDispatchConstant { get { return _underlyingParameter.IsIDispatchConstant; } } internal override bool IsIUnknownConstant { get { return _underlyingParameter.IsIUnknownConstant; } } internal override FlowAnalysisAnnotations FlowAnalysisAnnotations { // https://github.com/dotnet/roslyn/issues/30073: Consider moving to leaf types get { return _underlyingParameter.FlowAnalysisAnnotations; } } internal override ImmutableHashSet<string> NotNullIfParameterNotNull { get { return _underlyingParameter.NotNullIfParameterNotNull; } } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default) { return _underlyingParameter.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); } #endregion } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Features/Core/Portable/Completion/Providers/AbstractMemberInsertingCompletionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract partial class AbstractMemberInsertingCompletionProvider : LSPCompletionProvider { private readonly SyntaxAnnotation _annotation = new(); private readonly SyntaxAnnotation _otherAnnotation = new(); protected abstract SyntaxToken GetToken(CompletionItem completionItem, SyntaxTree tree, CancellationToken cancellationToken); protected abstract Task<ISymbol> GenerateMemberAsync(ISymbol member, INamedTypeSymbol containingType, Document document, CompletionItem item, CancellationToken cancellationToken); protected abstract int GetTargetCaretPosition(SyntaxNode caretTarget); protected abstract SyntaxNode GetSyntax(SyntaxToken commonSyntaxToken); public AbstractMemberInsertingCompletionProvider() { } public override async Task<CompletionChange> GetChangeAsync(Document document, CompletionItem item, char? commitKey = null, CancellationToken cancellationToken = default) { var newDocument = await DetermineNewDocumentAsync(document, item, cancellationToken).ConfigureAwait(false); var newText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); var newRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); int? newPosition = null; // Attempt to find the inserted node and move the caret appropriately if (newRoot != null) { var caretTarget = newRoot.GetAnnotatedNodesAndTokens(_annotation).FirstOrNull(); if (caretTarget != null) { var targetPosition = GetTargetCaretPosition(caretTarget.Value.AsNode()); // Something weird happened and we failed to get a valid position. // Bail on moving the caret. if (targetPosition > 0 && targetPosition <= newText.Length) { newPosition = targetPosition; } } } var changes = await newDocument.GetTextChangesAsync(document, cancellationToken).ConfigureAwait(false); var changesArray = changes.ToImmutableArray(); var change = Utilities.Collapse(newText, changesArray); return CompletionChange.Create(change, changesArray, newPosition, includesCommitCharacter: true); } private async Task<Document> DetermineNewDocumentAsync(Document document, CompletionItem completionItem, CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); // The span we're going to replace var line = text.Lines[MemberInsertionCompletionItem.GetLine(completionItem)]; // Annotate the line we care about so we can find it after adding usings var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = GetToken(completionItem, tree, cancellationToken); var annotatedRoot = tree.GetRoot(cancellationToken).ReplaceToken(token, token.WithAdditionalAnnotations(_otherAnnotation)); document = document.WithSyntaxRoot(annotatedRoot); var memberContainingDocument = await GenerateMemberAndUsingsAsync(document, completionItem, line, cancellationToken).ConfigureAwait(false); if (memberContainingDocument == null) { // Generating the new document failed because we somehow couldn't resolve // the underlying symbol's SymbolKey. At this point, we won't be able to // make any changes, so just return the document we started with. return document; } var insertionRoot = await GetTreeWithAddedSyntaxNodeRemovedAsync(memberContainingDocument, cancellationToken).ConfigureAwait(false); var insertionText = await GenerateInsertionTextAsync(memberContainingDocument, cancellationToken).ConfigureAwait(false); var destinationSpan = ComputeDestinationSpan(insertionRoot); var finalText = insertionRoot.GetText(text.Encoding) .Replace(destinationSpan, insertionText.Trim()); document = document.WithText(finalText); var newRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var declaration = GetSyntax(newRoot.FindToken(destinationSpan.End)); document = document.WithSyntaxRoot(newRoot.ReplaceNode(declaration, declaration.WithAdditionalAnnotations(_annotation))); return await Formatter.FormatAsync(document, _annotation, cancellationToken: cancellationToken).ConfigureAwait(false); } private async Task<Document> GenerateMemberAndUsingsAsync( Document document, CompletionItem completionItem, TextLine line, CancellationToken cancellationToken) { var codeGenService = document.GetLanguageService<ICodeGenerationService>(); // Resolve member and type in our new, forked, solution var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var containingType = semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(line.Start, cancellationToken); var symbols = await SymbolCompletionItem.GetSymbolsAsync(completionItem, document, cancellationToken).ConfigureAwait(false); var overriddenMember = symbols.FirstOrDefault(); if (overriddenMember == null) { // Unfortunately, SymbolKey resolution failed. Bail. return null; } // CodeGenerationOptions containing before and after var options = new CodeGenerationOptions( contextLocation: semanticModel.SyntaxTree.GetLocation(TextSpan.FromBounds(line.Start, line.Start)), options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)); var generatedMember = await GenerateMemberAsync(overriddenMember, containingType, document, completionItem, cancellationToken).ConfigureAwait(false); generatedMember = _annotation.AddAnnotationToSymbol(generatedMember); Document memberContainingDocument = null; if (generatedMember.Kind == SymbolKind.Method) { memberContainingDocument = await codeGenService.AddMethodAsync(document.Project.Solution, containingType, (IMethodSymbol)generatedMember, options, cancellationToken).ConfigureAwait(false); } else if (generatedMember.Kind == SymbolKind.Property) { memberContainingDocument = await codeGenService.AddPropertyAsync(document.Project.Solution, containingType, (IPropertySymbol)generatedMember, options, cancellationToken).ConfigureAwait(false); } else if (generatedMember.Kind == SymbolKind.Event) { memberContainingDocument = await codeGenService.AddEventAsync(document.Project.Solution, containingType, (IEventSymbol)generatedMember, options, cancellationToken).ConfigureAwait(false); } return memberContainingDocument; } private TextSpan ComputeDestinationSpan(SyntaxNode insertionRoot) { var targetToken = insertionRoot.GetAnnotatedTokens(_otherAnnotation).FirstOrNull(); var text = insertionRoot.GetText(); var line = text.Lines.GetLineFromPosition(targetToken.Value.Span.End); // DevDiv 958235: // // void goo() // { // } // override $$ // // If our text edit includes the trailing trivia of the close brace of goo(), // that token will be reconstructed. The ensuing tree diff will then count // the { } as replaced even though we didn't want it to. If the user // has collapsed the outline for goo, that means we'll edit the outlined // region and weird stuff will happen. Therefore, we'll start with the first // token on the line in order to leave the token and its trivia alone. var firstToken = insertionRoot.FindToken(line.GetFirstNonWhitespacePosition().Value); return TextSpan.FromBounds(firstToken.SpanStart, line.End); } private async Task<string> GenerateInsertionTextAsync( Document memberContainingDocument, CancellationToken cancellationToken) { memberContainingDocument = await Simplifier.ReduceAsync(memberContainingDocument, Simplifier.Annotation, optionSet: null, cancellationToken).ConfigureAwait(false); memberContainingDocument = await Formatter.FormatAsync(memberContainingDocument, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); var root = await memberContainingDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); return root.GetAnnotatedNodesAndTokens(_annotation).Single().AsNode().ToString().Trim(); } private async Task<SyntaxNode> GetTreeWithAddedSyntaxNodeRemovedAsync( Document document, CancellationToken cancellationToken) { // Added imports are annotated for simplification too. Therefore, we simplify the document // before removing added member node to preserve those imports in the document. document = await Simplifier.ReduceAsync(document, Simplifier.Annotation, optionSet: null, cancellationToken).ConfigureAwait(false); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var members = root.GetAnnotatedNodesAndTokens(_annotation) .AsImmutable() .Select(m => m.AsNode()); root = root.RemoveNodes(members, SyntaxRemoveOptions.KeepUnbalancedDirectives); var dismemberedDocument = document.WithSyntaxRoot(root); dismemberedDocument = await Formatter.FormatAsync(dismemberedDocument, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); return await dismemberedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); } private static readonly ImmutableArray<CharacterSetModificationRule> s_commitRules = ImmutableArray.Create( CharacterSetModificationRule.Create(CharacterSetModificationKind.Replace, '(')); private static readonly ImmutableArray<CharacterSetModificationRule> s_filterRules = ImmutableArray.Create( CharacterSetModificationRule.Create(CharacterSetModificationKind.Remove, '(')); private static readonly CompletionItemRules s_defaultRules = CompletionItemRules.Create( commitCharacterRules: s_commitRules, filterCharacterRules: s_filterRules, enterKeyRule: EnterKeyRule.Never); protected static CompletionItemRules GetRules() => s_defaultRules; protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => MemberInsertionCompletionItem.GetDescriptionAsync(item, document, cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract partial class AbstractMemberInsertingCompletionProvider : LSPCompletionProvider { private readonly SyntaxAnnotation _annotation = new(); private readonly SyntaxAnnotation _otherAnnotation = new(); protected abstract SyntaxToken GetToken(CompletionItem completionItem, SyntaxTree tree, CancellationToken cancellationToken); protected abstract Task<ISymbol> GenerateMemberAsync(ISymbol member, INamedTypeSymbol containingType, Document document, CompletionItem item, CancellationToken cancellationToken); protected abstract int GetTargetCaretPosition(SyntaxNode caretTarget); protected abstract SyntaxNode GetSyntax(SyntaxToken commonSyntaxToken); public AbstractMemberInsertingCompletionProvider() { } public override async Task<CompletionChange> GetChangeAsync(Document document, CompletionItem item, char? commitKey = null, CancellationToken cancellationToken = default) { var newDocument = await DetermineNewDocumentAsync(document, item, cancellationToken).ConfigureAwait(false); var newText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); var newRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); int? newPosition = null; // Attempt to find the inserted node and move the caret appropriately if (newRoot != null) { var caretTarget = newRoot.GetAnnotatedNodesAndTokens(_annotation).FirstOrNull(); if (caretTarget != null) { var targetPosition = GetTargetCaretPosition(caretTarget.Value.AsNode()); // Something weird happened and we failed to get a valid position. // Bail on moving the caret. if (targetPosition > 0 && targetPosition <= newText.Length) { newPosition = targetPosition; } } } var changes = await newDocument.GetTextChangesAsync(document, cancellationToken).ConfigureAwait(false); var changesArray = changes.ToImmutableArray(); var change = Utilities.Collapse(newText, changesArray); return CompletionChange.Create(change, changesArray, newPosition, includesCommitCharacter: true); } private async Task<Document> DetermineNewDocumentAsync(Document document, CompletionItem completionItem, CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); // The span we're going to replace var line = text.Lines[MemberInsertionCompletionItem.GetLine(completionItem)]; // Annotate the line we care about so we can find it after adding usings var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = GetToken(completionItem, tree, cancellationToken); var annotatedRoot = tree.GetRoot(cancellationToken).ReplaceToken(token, token.WithAdditionalAnnotations(_otherAnnotation)); document = document.WithSyntaxRoot(annotatedRoot); var memberContainingDocument = await GenerateMemberAndUsingsAsync(document, completionItem, line, cancellationToken).ConfigureAwait(false); if (memberContainingDocument == null) { // Generating the new document failed because we somehow couldn't resolve // the underlying symbol's SymbolKey. At this point, we won't be able to // make any changes, so just return the document we started with. return document; } var insertionRoot = await GetTreeWithAddedSyntaxNodeRemovedAsync(memberContainingDocument, cancellationToken).ConfigureAwait(false); var insertionText = await GenerateInsertionTextAsync(memberContainingDocument, cancellationToken).ConfigureAwait(false); var destinationSpan = ComputeDestinationSpan(insertionRoot); var finalText = insertionRoot.GetText(text.Encoding) .Replace(destinationSpan, insertionText.Trim()); document = document.WithText(finalText); var newRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var declaration = GetSyntax(newRoot.FindToken(destinationSpan.End)); document = document.WithSyntaxRoot(newRoot.ReplaceNode(declaration, declaration.WithAdditionalAnnotations(_annotation))); return await Formatter.FormatAsync(document, _annotation, cancellationToken: cancellationToken).ConfigureAwait(false); } private async Task<Document> GenerateMemberAndUsingsAsync( Document document, CompletionItem completionItem, TextLine line, CancellationToken cancellationToken) { var codeGenService = document.GetLanguageService<ICodeGenerationService>(); // Resolve member and type in our new, forked, solution var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var containingType = semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(line.Start, cancellationToken); var symbols = await SymbolCompletionItem.GetSymbolsAsync(completionItem, document, cancellationToken).ConfigureAwait(false); var overriddenMember = symbols.FirstOrDefault(); if (overriddenMember == null) { // Unfortunately, SymbolKey resolution failed. Bail. return null; } // CodeGenerationOptions containing before and after var options = new CodeGenerationOptions( contextLocation: semanticModel.SyntaxTree.GetLocation(TextSpan.FromBounds(line.Start, line.Start)), options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)); var generatedMember = await GenerateMemberAsync(overriddenMember, containingType, document, completionItem, cancellationToken).ConfigureAwait(false); generatedMember = _annotation.AddAnnotationToSymbol(generatedMember); Document memberContainingDocument = null; if (generatedMember.Kind == SymbolKind.Method) { memberContainingDocument = await codeGenService.AddMethodAsync(document.Project.Solution, containingType, (IMethodSymbol)generatedMember, options, cancellationToken).ConfigureAwait(false); } else if (generatedMember.Kind == SymbolKind.Property) { memberContainingDocument = await codeGenService.AddPropertyAsync(document.Project.Solution, containingType, (IPropertySymbol)generatedMember, options, cancellationToken).ConfigureAwait(false); } else if (generatedMember.Kind == SymbolKind.Event) { memberContainingDocument = await codeGenService.AddEventAsync(document.Project.Solution, containingType, (IEventSymbol)generatedMember, options, cancellationToken).ConfigureAwait(false); } return memberContainingDocument; } private TextSpan ComputeDestinationSpan(SyntaxNode insertionRoot) { var targetToken = insertionRoot.GetAnnotatedTokens(_otherAnnotation).FirstOrNull(); var text = insertionRoot.GetText(); var line = text.Lines.GetLineFromPosition(targetToken.Value.Span.End); // DevDiv 958235: // // void goo() // { // } // override $$ // // If our text edit includes the trailing trivia of the close brace of goo(), // that token will be reconstructed. The ensuing tree diff will then count // the { } as replaced even though we didn't want it to. If the user // has collapsed the outline for goo, that means we'll edit the outlined // region and weird stuff will happen. Therefore, we'll start with the first // token on the line in order to leave the token and its trivia alone. var firstToken = insertionRoot.FindToken(line.GetFirstNonWhitespacePosition().Value); return TextSpan.FromBounds(firstToken.SpanStart, line.End); } private async Task<string> GenerateInsertionTextAsync( Document memberContainingDocument, CancellationToken cancellationToken) { memberContainingDocument = await Simplifier.ReduceAsync(memberContainingDocument, Simplifier.Annotation, optionSet: null, cancellationToken).ConfigureAwait(false); memberContainingDocument = await Formatter.FormatAsync(memberContainingDocument, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); var root = await memberContainingDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); return root.GetAnnotatedNodesAndTokens(_annotation).Single().AsNode().ToString().Trim(); } private async Task<SyntaxNode> GetTreeWithAddedSyntaxNodeRemovedAsync( Document document, CancellationToken cancellationToken) { // Added imports are annotated for simplification too. Therefore, we simplify the document // before removing added member node to preserve those imports in the document. document = await Simplifier.ReduceAsync(document, Simplifier.Annotation, optionSet: null, cancellationToken).ConfigureAwait(false); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var members = root.GetAnnotatedNodesAndTokens(_annotation) .AsImmutable() .Select(m => m.AsNode()); root = root.RemoveNodes(members, SyntaxRemoveOptions.KeepUnbalancedDirectives); var dismemberedDocument = document.WithSyntaxRoot(root); dismemberedDocument = await Formatter.FormatAsync(dismemberedDocument, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); return await dismemberedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); } private static readonly ImmutableArray<CharacterSetModificationRule> s_commitRules = ImmutableArray.Create( CharacterSetModificationRule.Create(CharacterSetModificationKind.Replace, '(')); private static readonly ImmutableArray<CharacterSetModificationRule> s_filterRules = ImmutableArray.Create( CharacterSetModificationRule.Create(CharacterSetModificationKind.Remove, '(')); private static readonly CompletionItemRules s_defaultRules = CompletionItemRules.Create( commitCharacterRules: s_commitRules, filterCharacterRules: s_filterRules, enterKeyRule: EnterKeyRule.Never); protected static CompletionItemRules GetRules() => s_defaultRules; protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => MemberInsertionCompletionItem.GetDescriptionAsync(item, document, cancellationToken); } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/EditorFeatures/CSharpTest2/Recommendations/ShortKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ShortKeywordRecommenderTests : 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 TestAfterStackAlloc() { await VerifyKeywordAsync( @"class C { int* goo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFixedStatement() { await VerifyKeywordAsync( @"fixed ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDelegateReturnType() { await VerifyKeywordAsync( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType2() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); } [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 $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestEnumBaseTypes() { await VerifyKeywordAsync( @"enum E : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType1() { await VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType2() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType3() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int[],$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType4() { await VerifyKeywordAsync(AddInsideMethod( @"IList<IGoo<int?,byte*>,$$")); } [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<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); } [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 $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInLocalVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForeachVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUsingVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFromVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInJoinVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from a in b join $$")); } [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, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"new $$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTypeOf() { await VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDefault() { await VerifyKeywordAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInSizeOf() { await VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [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 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(short 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")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTupleWithinMember() { await VerifyKeywordAsync(@" class Program { void Method() { ($$ } }"); } [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*$$"); } [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunction))] public async Task TestAfterKeywordIndicatingLocalFunction(string keyword) { await VerifyKeywordAsync(AddInsideMethod($@" {keyword} $$")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ShortKeywordRecommenderTests : 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 TestAfterStackAlloc() { await VerifyKeywordAsync( @"class C { int* goo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFixedStatement() { await VerifyKeywordAsync( @"fixed ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDelegateReturnType() { await VerifyKeywordAsync( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType2() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); } [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 $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestEnumBaseTypes() { await VerifyKeywordAsync( @"enum E : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType1() { await VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType2() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType3() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int[],$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType4() { await VerifyKeywordAsync(AddInsideMethod( @"IList<IGoo<int?,byte*>,$$")); } [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<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); } [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 $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInLocalVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForeachVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUsingVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFromVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInJoinVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from a in b join $$")); } [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, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"new $$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTypeOf() { await VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDefault() { await VerifyKeywordAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInSizeOf() { await VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [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 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(short 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")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTupleWithinMember() { await VerifyKeywordAsync(@" class Program { void Method() { ($$ } }"); } [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*$$"); } [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunction))] public async Task TestAfterKeywordIndicatingLocalFunction(string keyword) { await VerifyKeywordAsync(AddInsideMethod($@" {keyword} $$")); } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/VisualStudio/CSharp/Impl/ProjectSystemShim/EntryPointFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim { internal class EntryPointFinder : AbstractEntryPointFinder { protected override bool MatchesMainMethodName(string name) => name == "Main"; public static IEnumerable<INamedTypeSymbol> FindEntryPoints(INamespaceSymbol symbol) { var visitor = new EntryPointFinder(); visitor.Visit(symbol); return visitor.EntryPoints; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim { internal class EntryPointFinder : AbstractEntryPointFinder { protected override bool MatchesMainMethodName(string name) => name == "Main"; public static IEnumerable<INamedTypeSymbol> FindEntryPoints(INamespaceSymbol symbol) { var visitor = new EntryPointFinder(); visitor.Visit(symbol); return visitor.EntryPoints; } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/CodeStyle/CSharp/Tests/FormattingAnalyzerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.IO; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Testing; using Microsoft.CodeAnalysis.Testing.Verifiers; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CodeStyle { using Verify = CSharpCodeFixVerifier<CSharpFormattingAnalyzer, CSharpFormattingCodeFixProvider, XUnitVerifier>; public class FormattingAnalyzerTests { [Fact] public async Task TestAlreadyFormatted() { var testCode = @" class MyClass { void MyMethod() { } } "; await Verify.VerifyAnalyzerAsync(testCode); } [Fact] public async Task TestNeedsIndentation() { var testCode = @" class MyClass { $$void MyMethod() $${ $$} } "; var fixedCode = @" class MyClass { void MyMethod() { } } "; await Verify.VerifyCodeFixAsync(testCode, fixedCode); } [Fact] public async Task TestNeedsIndentationButSuppressed() { var testCode = @" class MyClass { $$void MyMethod1() $${ $$} #pragma warning disable format void MyMethod2() { } #pragma warning restore format void MyMethod3() $${ $$} } "; var fixedCode = @" class MyClass { void MyMethod1() { } #pragma warning disable format void MyMethod2() { } #pragma warning restore format void MyMethod3() { } } "; await Verify.VerifyCodeFixAsync(testCode, fixedCode); } [Fact] public async Task TestWhitespaceBetweenMethods1() { var testCode = @" class MyClass { void MyMethod1() { } [| |] void MyMethod2() { } } "; var fixedCode = @" class MyClass { void MyMethod1() { } void MyMethod2() { } } "; await Verify.VerifyCodeFixAsync(testCode, fixedCode); } [Fact] public async Task TestWhitespaceBetweenMethods2() { var testCode = @" class MyClass { void MyMethod1() { }[| |] void MyMethod2() { } } "; var fixedCode = @" class MyClass { void MyMethod1() { } void MyMethod2() { } } "; await Verify.VerifyCodeFixAsync(testCode, fixedCode); } [Fact] public async Task TestWhitespaceBetweenMethods3() { // This example has trailing whitespace on both lines preceding MyMethod2 var testCode = @" class MyClass { void MyMethod1() { }[| |]void MyMethod2() { } } "; var fixedCode = @" class MyClass { void MyMethod1() { } void MyMethod2() { } } "; await Verify.VerifyCodeFixAsync(testCode, fixedCode); } [Fact] public async Task TestOverIndentation() { var testCode = @" class MyClass { [| |]void MyMethod() [| |]{ [| |]} } "; var fixedCode = @" class MyClass { void MyMethod() { } } "; await Verify.VerifyCodeFixAsync(testCode, fixedCode); } [Fact] public async Task TestIncrementalFixesFullLine() { var testCode = @" class MyClass { int Property1$${$$get;$$set;$$} int Property2$${$$get;$$} } "; var fixedCode = @" class MyClass { int Property1 { get; set; } int Property2 { get; } } "; await new CSharpCodeFixTest<CSharpFormattingAnalyzer, CSharpFormattingCodeFixProvider, XUnitVerifier> { TestCode = testCode, FixedCode = fixedCode, // Each application of a single code fix covers all diagnostics on the same line. In total, two lines // require changes so the number of incremental iterations is exactly 2. NumberOfIncrementalIterations = 2, }.RunAsync(); } [Fact] public async Task TestEditorConfigUsed() { var testCode = @" class MyClass { void MyMethod()[| |]{ } } "; var fixedCode = @" class MyClass { void MyMethod() { } } "; var editorConfig = @" root = true [*.cs] csharp_new_line_before_open_brace = methods "; await new CSharpCodeFixTest<CSharpFormattingAnalyzer, CSharpFormattingCodeFixProvider, XUnitVerifier> { TestState = { Sources = { testCode }, AnalyzerConfigFiles = { ("/.editorconfig", editorConfig), }, }, FixedState = { Sources = { fixedCode } }, }.RunAsync(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.IO; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Testing; using Microsoft.CodeAnalysis.Testing.Verifiers; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CodeStyle { using Verify = CSharpCodeFixVerifier<CSharpFormattingAnalyzer, CSharpFormattingCodeFixProvider, XUnitVerifier>; public class FormattingAnalyzerTests { [Fact] public async Task TestAlreadyFormatted() { var testCode = @" class MyClass { void MyMethod() { } } "; await Verify.VerifyAnalyzerAsync(testCode); } [Fact] public async Task TestNeedsIndentation() { var testCode = @" class MyClass { $$void MyMethod() $${ $$} } "; var fixedCode = @" class MyClass { void MyMethod() { } } "; await Verify.VerifyCodeFixAsync(testCode, fixedCode); } [Fact] public async Task TestNeedsIndentationButSuppressed() { var testCode = @" class MyClass { $$void MyMethod1() $${ $$} #pragma warning disable format void MyMethod2() { } #pragma warning restore format void MyMethod3() $${ $$} } "; var fixedCode = @" class MyClass { void MyMethod1() { } #pragma warning disable format void MyMethod2() { } #pragma warning restore format void MyMethod3() { } } "; await Verify.VerifyCodeFixAsync(testCode, fixedCode); } [Fact] public async Task TestWhitespaceBetweenMethods1() { var testCode = @" class MyClass { void MyMethod1() { } [| |] void MyMethod2() { } } "; var fixedCode = @" class MyClass { void MyMethod1() { } void MyMethod2() { } } "; await Verify.VerifyCodeFixAsync(testCode, fixedCode); } [Fact] public async Task TestWhitespaceBetweenMethods2() { var testCode = @" class MyClass { void MyMethod1() { }[| |] void MyMethod2() { } } "; var fixedCode = @" class MyClass { void MyMethod1() { } void MyMethod2() { } } "; await Verify.VerifyCodeFixAsync(testCode, fixedCode); } [Fact] public async Task TestWhitespaceBetweenMethods3() { // This example has trailing whitespace on both lines preceding MyMethod2 var testCode = @" class MyClass { void MyMethod1() { }[| |]void MyMethod2() { } } "; var fixedCode = @" class MyClass { void MyMethod1() { } void MyMethod2() { } } "; await Verify.VerifyCodeFixAsync(testCode, fixedCode); } [Fact] public async Task TestOverIndentation() { var testCode = @" class MyClass { [| |]void MyMethod() [| |]{ [| |]} } "; var fixedCode = @" class MyClass { void MyMethod() { } } "; await Verify.VerifyCodeFixAsync(testCode, fixedCode); } [Fact] public async Task TestIncrementalFixesFullLine() { var testCode = @" class MyClass { int Property1$${$$get;$$set;$$} int Property2$${$$get;$$} } "; var fixedCode = @" class MyClass { int Property1 { get; set; } int Property2 { get; } } "; await new CSharpCodeFixTest<CSharpFormattingAnalyzer, CSharpFormattingCodeFixProvider, XUnitVerifier> { TestCode = testCode, FixedCode = fixedCode, // Each application of a single code fix covers all diagnostics on the same line. In total, two lines // require changes so the number of incremental iterations is exactly 2. NumberOfIncrementalIterations = 2, }.RunAsync(); } [Fact] public async Task TestEditorConfigUsed() { var testCode = @" class MyClass { void MyMethod()[| |]{ } } "; var fixedCode = @" class MyClass { void MyMethod() { } } "; var editorConfig = @" root = true [*.cs] csharp_new_line_before_open_brace = methods "; await new CSharpCodeFixTest<CSharpFormattingAnalyzer, CSharpFormattingCodeFixProvider, XUnitVerifier> { TestState = { Sources = { testCode }, AnalyzerConfigFiles = { ("/.editorconfig", editorConfig), }, }, FixedState = { Sources = { fixedCode } }, }.RunAsync(); } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/VisualStudio/Core/Impl/CodeModel/GlobalNodeKey.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal struct GlobalNodeKey { public readonly SyntaxNodeKey NodeKey; public readonly SyntaxPath Path; public GlobalNodeKey(SyntaxNodeKey nodeKey, SyntaxPath path) { this.NodeKey = nodeKey; this.Path = path; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal struct GlobalNodeKey { public readonly SyntaxNodeKey NodeKey; public readonly SyntaxPath Path; public GlobalNodeKey(SyntaxNodeKey nodeKey, SyntaxPath path) { this.NodeKey = nodeKey; this.Path = path; } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Compilers/Core/Portable/CommandLine/SarifVersion.cs
// Licensed to the .NET Foundation under one or more 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 { /// <summary> /// Specifies the version of the SARIF log file to produce. /// </summary> public enum SarifVersion { /// <summary> /// The original, non-standardized version of the SARIF format. /// </summary> Sarif1 = 1, /// <summary> /// The first standardized version of the SARIF format. /// </summary> Sarif2 = 2, /// <summary> /// The default SARIF version, which is v1.0.0 for compatibility with /// previous versions of the compiler. /// </summary> Default = Sarif1, /// <summary> /// The latest supported SARIF version. /// </summary> Latest = int.MaxValue } public static class SarifVersionFacts { /// <summary> /// Try to parse the SARIF log file version from a string. /// </summary> public static bool TryParse(string version, out SarifVersion result) { if (version == null) { result = SarifVersion.Default; return true; } switch (CaseInsensitiveComparison.ToLower(version)) { case "default": result = SarifVersion.Default; return true; case "latest": result = SarifVersion.Latest; return true; case "1": case "1.0": result = SarifVersion.Sarif1; return true; case "2": case "2.1": result = SarifVersion.Sarif2; return true; default: result = SarifVersion.Default; return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis { /// <summary> /// Specifies the version of the SARIF log file to produce. /// </summary> public enum SarifVersion { /// <summary> /// The original, non-standardized version of the SARIF format. /// </summary> Sarif1 = 1, /// <summary> /// The first standardized version of the SARIF format. /// </summary> Sarif2 = 2, /// <summary> /// The default SARIF version, which is v1.0.0 for compatibility with /// previous versions of the compiler. /// </summary> Default = Sarif1, /// <summary> /// The latest supported SARIF version. /// </summary> Latest = int.MaxValue } public static class SarifVersionFacts { /// <summary> /// Try to parse the SARIF log file version from a string. /// </summary> public static bool TryParse(string version, out SarifVersion result) { if (version == null) { result = SarifVersion.Default; return true; } switch (CaseInsensitiveComparison.ToLower(version)) { case "default": result = SarifVersion.Default; return true; case "latest": result = SarifVersion.Latest; return true; case "1": case "1.0": result = SarifVersion.Sarif1; return true; case "2": case "2.1": result = SarifVersion.Sarif2; return true; default: result = SarifVersion.Default; return false; } } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Workspaces/Core/Portable/Utilities/WeakSet`1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; namespace Roslyn.Utilities { /// <summary> /// A simple collection of values held as weak references. Objects in the set are compared by reference equality. /// </summary> /// <typeparam name="T">The type of object stored in the set.</typeparam> internal sealed class WeakSet<T> where T : class? { private readonly HashSet<ReferenceHolder<T>> _values = new(); public WeakSet() { } public bool Add(T value) { if (Contains(value)) return false; return _values.Add(ReferenceHolder<T>.Weak(value)); } public bool Contains(T value) { return _values.Contains(ReferenceHolder<T>.Strong(value)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; namespace Roslyn.Utilities { /// <summary> /// A simple collection of values held as weak references. Objects in the set are compared by reference equality. /// </summary> /// <typeparam name="T">The type of object stored in the set.</typeparam> internal sealed class WeakSet<T> where T : class? { private readonly HashSet<ReferenceHolder<T>> _values = new(); public WeakSet() { } public bool Add(T value) { if (Contains(value)) return false; return _values.Add(ReferenceHolder<T>.Weak(value)); } public bool Contains(T value) { return _values.Contains(ReferenceHolder<T>.Strong(value)); } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Workspaces/CSharp/Portable/Classification/Worker_Preprocesser.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Classification; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Classification { internal partial class Worker { private void ClassifyPreprocessorDirective(DirectiveTriviaSyntax node) { if (!_textSpan.OverlapsWith(node.Span)) { return; } switch (node.Kind()) { case SyntaxKind.IfDirectiveTrivia: ClassifyIfDirective((IfDirectiveTriviaSyntax)node); break; case SyntaxKind.ElifDirectiveTrivia: ClassifyElifDirective((ElifDirectiveTriviaSyntax)node); break; case SyntaxKind.ElseDirectiveTrivia: ClassifyElseDirective((ElseDirectiveTriviaSyntax)node); break; case SyntaxKind.EndIfDirectiveTrivia: ClassifyEndIfDirective((EndIfDirectiveTriviaSyntax)node); break; case SyntaxKind.RegionDirectiveTrivia: ClassifyRegionDirective((RegionDirectiveTriviaSyntax)node); break; case SyntaxKind.EndRegionDirectiveTrivia: ClassifyEndRegionDirective((EndRegionDirectiveTriviaSyntax)node); break; case SyntaxKind.ErrorDirectiveTrivia: ClassifyErrorDirective((ErrorDirectiveTriviaSyntax)node); break; case SyntaxKind.WarningDirectiveTrivia: ClassifyWarningDirective((WarningDirectiveTriviaSyntax)node); break; case SyntaxKind.BadDirectiveTrivia: ClassifyBadDirective((BadDirectiveTriviaSyntax)node); break; case SyntaxKind.DefineDirectiveTrivia: ClassifyDefineDirective((DefineDirectiveTriviaSyntax)node); break; case SyntaxKind.UndefDirectiveTrivia: ClassifyUndefDirective((UndefDirectiveTriviaSyntax)node); break; case SyntaxKind.LineDirectiveTrivia: ClassifyLineDirective((LineDirectiveTriviaSyntax)node); break; case SyntaxKind.LineSpanDirectiveTrivia: ClassifyLineSpanDirective((LineSpanDirectiveTriviaSyntax)node); break; case SyntaxKind.PragmaChecksumDirectiveTrivia: ClassifyPragmaChecksumDirective((PragmaChecksumDirectiveTriviaSyntax)node); break; case SyntaxKind.PragmaWarningDirectiveTrivia: ClassifyPragmaWarningDirective((PragmaWarningDirectiveTriviaSyntax)node); break; case SyntaxKind.ReferenceDirectiveTrivia: ClassifyReferenceDirective((ReferenceDirectiveTriviaSyntax)node); break; case SyntaxKind.LoadDirectiveTrivia: ClassifyLoadDirective((LoadDirectiveTriviaSyntax)node); break; case SyntaxKind.NullableDirectiveTrivia: ClassifyNullableDirective((NullableDirectiveTriviaSyntax)node); break; } } private void ClassifyDirectiveTrivia(DirectiveTriviaSyntax node, bool allowComments = true) { var lastToken = node.EndOfDirectiveToken.GetPreviousToken(includeSkipped: false); foreach (var trivia in lastToken.TrailingTrivia) { // skip initial whitespace if (trivia.Kind() == SyntaxKind.WhitespaceTrivia) { continue; } ClassifyPreprocessorTrivia(trivia, allowComments); } foreach (var trivia in node.EndOfDirectiveToken.LeadingTrivia) { ClassifyPreprocessorTrivia(trivia, allowComments); } } private void ClassifyPreprocessorTrivia(SyntaxTrivia trivia, bool allowComments) { if (allowComments && trivia.Kind() == SyntaxKind.SingleLineCommentTrivia) { AddClassification(trivia, ClassificationTypeNames.Comment); } else { AddClassification(trivia, ClassificationTypeNames.PreprocessorText); } } private void ClassifyPreprocessorExpression(ExpressionSyntax? node) { if (node == null) { return; } if (node is LiteralExpressionSyntax literal) { // true or false AddClassification(literal.Token, ClassificationTypeNames.Keyword); } else if (node is IdentifierNameSyntax identifier) { // DEBUG AddClassification(identifier.Identifier, ClassificationTypeNames.Identifier); } else if (node is ParenthesizedExpressionSyntax parenExpression) { // (true) AddClassification(parenExpression.OpenParenToken, ClassificationTypeNames.Punctuation); ClassifyPreprocessorExpression(parenExpression.Expression); AddClassification(parenExpression.CloseParenToken, ClassificationTypeNames.Punctuation); } else if (node is PrefixUnaryExpressionSyntax prefixExpression) { // ! AddClassification(prefixExpression.OperatorToken, ClassificationTypeNames.Operator); ClassifyPreprocessorExpression(prefixExpression.Operand); } else if (node is BinaryExpressionSyntax binaryExpression) { // &&, ||, ==, != ClassifyPreprocessorExpression(binaryExpression.Left); AddClassification(binaryExpression.OperatorToken, ClassificationTypeNames.Operator); ClassifyPreprocessorExpression(binaryExpression.Right); } } private void ClassifyIfDirective(IfDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.IfKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyPreprocessorExpression(node.Condition); ClassifyDirectiveTrivia(node); } private void ClassifyElifDirective(ElifDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.ElifKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyPreprocessorExpression(node.Condition); ClassifyDirectiveTrivia(node); } private void ClassifyElseDirective(ElseDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.ElseKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node); } private void ClassifyEndIfDirective(EndIfDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.EndIfKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node); } private void ClassifyErrorDirective(ErrorDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.ErrorKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node, allowComments: false); } private void ClassifyWarningDirective(WarningDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.WarningKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node, allowComments: false); } private void ClassifyRegionDirective(RegionDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.RegionKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node, allowComments: false); } private void ClassifyEndRegionDirective(EndRegionDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.EndRegionKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node); } private void ClassifyDefineDirective(DefineDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.DefineKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.Name, ClassificationTypeNames.Identifier); ClassifyDirectiveTrivia(node); } private void ClassifyUndefDirective(UndefDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.UndefKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.Name, ClassificationTypeNames.Identifier); ClassifyDirectiveTrivia(node); } private void ClassifyBadDirective(BadDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.Identifier, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node); } private void ClassifyLineDirective(LineDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.LineKeyword, ClassificationTypeNames.PreprocessorKeyword); switch (node.Line.Kind()) { case SyntaxKind.HiddenKeyword: case SyntaxKind.DefaultKeyword: AddClassification(node.Line, ClassificationTypeNames.PreprocessorKeyword); break; case SyntaxKind.NumericLiteralToken: AddClassification(node.Line, ClassificationTypeNames.NumericLiteral); break; } AddOptionalClassification(node.File, ClassificationTypeNames.StringLiteral); ClassifyDirectiveTrivia(node); } private void ClassifyLineSpanDirective(LineSpanDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.LineKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyLineDirectivePosition(node.Start); AddClassification(node.MinusToken, ClassificationTypeNames.Operator); ClassifyLineDirectivePosition(node.End); AddOptionalClassification(node.CharacterOffset, ClassificationTypeNames.NumericLiteral); AddOptionalClassification(node.File, ClassificationTypeNames.StringLiteral); ClassifyDirectiveTrivia(node); } private void AddOptionalClassification(SyntaxToken token, string classification) { if (token.Kind() != SyntaxKind.None) { AddClassification(token, classification); } } private void ClassifyLineDirectivePosition(LineDirectivePositionSyntax node) { AddClassification(node.OpenParenToken, ClassificationTypeNames.Punctuation); AddClassification(node.Line, ClassificationTypeNames.NumericLiteral); AddClassification(node.CommaToken, ClassificationTypeNames.Punctuation); AddClassification(node.Character, ClassificationTypeNames.NumericLiteral); AddClassification(node.CloseParenToken, ClassificationTypeNames.Punctuation); } private void ClassifyPragmaChecksumDirective(PragmaChecksumDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.PragmaKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.ChecksumKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.File, ClassificationTypeNames.StringLiteral); AddClassification(node.Guid, ClassificationTypeNames.StringLiteral); AddClassification(node.Bytes, ClassificationTypeNames.StringLiteral); ClassifyDirectiveTrivia(node); } private void ClassifyPragmaWarningDirective(PragmaWarningDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.PragmaKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.WarningKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.DisableOrRestoreKeyword, ClassificationTypeNames.PreprocessorKeyword); foreach (var nodeOrToken in node.ErrorCodes.GetWithSeparators()) { ClassifyNodeOrToken(nodeOrToken); } if (node.ErrorCodes.Count == 0) { // When there are no error codes, we need to classify the directive's trivia. // (When there are error codes, ClassifyNodeOrToken above takes care of that.) ClassifyDirectiveTrivia(node); } } private void ClassifyReferenceDirective(ReferenceDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.ReferenceKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.File, ClassificationTypeNames.StringLiteral); ClassifyDirectiveTrivia(node); } private void ClassifyLoadDirective(LoadDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.LoadKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.File, ClassificationTypeNames.StringLiteral); ClassifyDirectiveTrivia(node); } private void ClassifyNullableDirective(NullableDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.NullableKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.SettingToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.TargetToken, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Classification { internal partial class Worker { private void ClassifyPreprocessorDirective(DirectiveTriviaSyntax node) { if (!_textSpan.OverlapsWith(node.Span)) { return; } switch (node.Kind()) { case SyntaxKind.IfDirectiveTrivia: ClassifyIfDirective((IfDirectiveTriviaSyntax)node); break; case SyntaxKind.ElifDirectiveTrivia: ClassifyElifDirective((ElifDirectiveTriviaSyntax)node); break; case SyntaxKind.ElseDirectiveTrivia: ClassifyElseDirective((ElseDirectiveTriviaSyntax)node); break; case SyntaxKind.EndIfDirectiveTrivia: ClassifyEndIfDirective((EndIfDirectiveTriviaSyntax)node); break; case SyntaxKind.RegionDirectiveTrivia: ClassifyRegionDirective((RegionDirectiveTriviaSyntax)node); break; case SyntaxKind.EndRegionDirectiveTrivia: ClassifyEndRegionDirective((EndRegionDirectiveTriviaSyntax)node); break; case SyntaxKind.ErrorDirectiveTrivia: ClassifyErrorDirective((ErrorDirectiveTriviaSyntax)node); break; case SyntaxKind.WarningDirectiveTrivia: ClassifyWarningDirective((WarningDirectiveTriviaSyntax)node); break; case SyntaxKind.BadDirectiveTrivia: ClassifyBadDirective((BadDirectiveTriviaSyntax)node); break; case SyntaxKind.DefineDirectiveTrivia: ClassifyDefineDirective((DefineDirectiveTriviaSyntax)node); break; case SyntaxKind.UndefDirectiveTrivia: ClassifyUndefDirective((UndefDirectiveTriviaSyntax)node); break; case SyntaxKind.LineDirectiveTrivia: ClassifyLineDirective((LineDirectiveTriviaSyntax)node); break; case SyntaxKind.LineSpanDirectiveTrivia: ClassifyLineSpanDirective((LineSpanDirectiveTriviaSyntax)node); break; case SyntaxKind.PragmaChecksumDirectiveTrivia: ClassifyPragmaChecksumDirective((PragmaChecksumDirectiveTriviaSyntax)node); break; case SyntaxKind.PragmaWarningDirectiveTrivia: ClassifyPragmaWarningDirective((PragmaWarningDirectiveTriviaSyntax)node); break; case SyntaxKind.ReferenceDirectiveTrivia: ClassifyReferenceDirective((ReferenceDirectiveTriviaSyntax)node); break; case SyntaxKind.LoadDirectiveTrivia: ClassifyLoadDirective((LoadDirectiveTriviaSyntax)node); break; case SyntaxKind.NullableDirectiveTrivia: ClassifyNullableDirective((NullableDirectiveTriviaSyntax)node); break; } } private void ClassifyDirectiveTrivia(DirectiveTriviaSyntax node, bool allowComments = true) { var lastToken = node.EndOfDirectiveToken.GetPreviousToken(includeSkipped: false); foreach (var trivia in lastToken.TrailingTrivia) { // skip initial whitespace if (trivia.Kind() == SyntaxKind.WhitespaceTrivia) { continue; } ClassifyPreprocessorTrivia(trivia, allowComments); } foreach (var trivia in node.EndOfDirectiveToken.LeadingTrivia) { ClassifyPreprocessorTrivia(trivia, allowComments); } } private void ClassifyPreprocessorTrivia(SyntaxTrivia trivia, bool allowComments) { if (allowComments && trivia.Kind() == SyntaxKind.SingleLineCommentTrivia) { AddClassification(trivia, ClassificationTypeNames.Comment); } else { AddClassification(trivia, ClassificationTypeNames.PreprocessorText); } } private void ClassifyPreprocessorExpression(ExpressionSyntax? node) { if (node == null) { return; } if (node is LiteralExpressionSyntax literal) { // true or false AddClassification(literal.Token, ClassificationTypeNames.Keyword); } else if (node is IdentifierNameSyntax identifier) { // DEBUG AddClassification(identifier.Identifier, ClassificationTypeNames.Identifier); } else if (node is ParenthesizedExpressionSyntax parenExpression) { // (true) AddClassification(parenExpression.OpenParenToken, ClassificationTypeNames.Punctuation); ClassifyPreprocessorExpression(parenExpression.Expression); AddClassification(parenExpression.CloseParenToken, ClassificationTypeNames.Punctuation); } else if (node is PrefixUnaryExpressionSyntax prefixExpression) { // ! AddClassification(prefixExpression.OperatorToken, ClassificationTypeNames.Operator); ClassifyPreprocessorExpression(prefixExpression.Operand); } else if (node is BinaryExpressionSyntax binaryExpression) { // &&, ||, ==, != ClassifyPreprocessorExpression(binaryExpression.Left); AddClassification(binaryExpression.OperatorToken, ClassificationTypeNames.Operator); ClassifyPreprocessorExpression(binaryExpression.Right); } } private void ClassifyIfDirective(IfDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.IfKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyPreprocessorExpression(node.Condition); ClassifyDirectiveTrivia(node); } private void ClassifyElifDirective(ElifDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.ElifKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyPreprocessorExpression(node.Condition); ClassifyDirectiveTrivia(node); } private void ClassifyElseDirective(ElseDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.ElseKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node); } private void ClassifyEndIfDirective(EndIfDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.EndIfKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node); } private void ClassifyErrorDirective(ErrorDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.ErrorKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node, allowComments: false); } private void ClassifyWarningDirective(WarningDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.WarningKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node, allowComments: false); } private void ClassifyRegionDirective(RegionDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.RegionKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node, allowComments: false); } private void ClassifyEndRegionDirective(EndRegionDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.EndRegionKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node); } private void ClassifyDefineDirective(DefineDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.DefineKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.Name, ClassificationTypeNames.Identifier); ClassifyDirectiveTrivia(node); } private void ClassifyUndefDirective(UndefDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.UndefKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.Name, ClassificationTypeNames.Identifier); ClassifyDirectiveTrivia(node); } private void ClassifyBadDirective(BadDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.Identifier, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node); } private void ClassifyLineDirective(LineDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.LineKeyword, ClassificationTypeNames.PreprocessorKeyword); switch (node.Line.Kind()) { case SyntaxKind.HiddenKeyword: case SyntaxKind.DefaultKeyword: AddClassification(node.Line, ClassificationTypeNames.PreprocessorKeyword); break; case SyntaxKind.NumericLiteralToken: AddClassification(node.Line, ClassificationTypeNames.NumericLiteral); break; } AddOptionalClassification(node.File, ClassificationTypeNames.StringLiteral); ClassifyDirectiveTrivia(node); } private void ClassifyLineSpanDirective(LineSpanDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.LineKeyword, ClassificationTypeNames.PreprocessorKeyword); ClassifyLineDirectivePosition(node.Start); AddClassification(node.MinusToken, ClassificationTypeNames.Operator); ClassifyLineDirectivePosition(node.End); AddOptionalClassification(node.CharacterOffset, ClassificationTypeNames.NumericLiteral); AddOptionalClassification(node.File, ClassificationTypeNames.StringLiteral); ClassifyDirectiveTrivia(node); } private void AddOptionalClassification(SyntaxToken token, string classification) { if (token.Kind() != SyntaxKind.None) { AddClassification(token, classification); } } private void ClassifyLineDirectivePosition(LineDirectivePositionSyntax node) { AddClassification(node.OpenParenToken, ClassificationTypeNames.Punctuation); AddClassification(node.Line, ClassificationTypeNames.NumericLiteral); AddClassification(node.CommaToken, ClassificationTypeNames.Punctuation); AddClassification(node.Character, ClassificationTypeNames.NumericLiteral); AddClassification(node.CloseParenToken, ClassificationTypeNames.Punctuation); } private void ClassifyPragmaChecksumDirective(PragmaChecksumDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.PragmaKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.ChecksumKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.File, ClassificationTypeNames.StringLiteral); AddClassification(node.Guid, ClassificationTypeNames.StringLiteral); AddClassification(node.Bytes, ClassificationTypeNames.StringLiteral); ClassifyDirectiveTrivia(node); } private void ClassifyPragmaWarningDirective(PragmaWarningDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.PragmaKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.WarningKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.DisableOrRestoreKeyword, ClassificationTypeNames.PreprocessorKeyword); foreach (var nodeOrToken in node.ErrorCodes.GetWithSeparators()) { ClassifyNodeOrToken(nodeOrToken); } if (node.ErrorCodes.Count == 0) { // When there are no error codes, we need to classify the directive's trivia. // (When there are error codes, ClassifyNodeOrToken above takes care of that.) ClassifyDirectiveTrivia(node); } } private void ClassifyReferenceDirective(ReferenceDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.ReferenceKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.File, ClassificationTypeNames.StringLiteral); ClassifyDirectiveTrivia(node); } private void ClassifyLoadDirective(LoadDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.LoadKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.File, ClassificationTypeNames.StringLiteral); ClassifyDirectiveTrivia(node); } private void ClassifyNullableDirective(NullableDirectiveTriviaSyntax node) { AddClassification(node.HashToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.NullableKeyword, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.SettingToken, ClassificationTypeNames.PreprocessorKeyword); AddClassification(node.TargetToken, ClassificationTypeNames.PreprocessorKeyword); ClassifyDirectiveTrivia(node); } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./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(53585, "https://github.com/dotnet/roslyn/issues/53585")] public async Task AfterStaticLocalFunction_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { static $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData("extern")] [InlineData("static extern")] [InlineData("extern static")] [InlineData("async")] [InlineData("static async")] [InlineData("async static")] [InlineData("unsafe")] [InlineData("static unsafe")] [InlineData("unsafe static")] [InlineData("async unsafe")] [InlineData("unsafe async")] [InlineData("unsafe extern")] [InlineData("extern unsafe")] [InlineData("extern unsafe async static")] public async Task AfterLocalFunction_TypeOnly(string keyword) { var markup = $@" using System; class C {{ void M(String parameter) {{ {keyword} $$ }} }} "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] public async Task NotAfterAsyncLocalFunctionWithTwoAsyncs() { var markup = @" using System; class C { void M(String parameter) { async async $$ } } "; await VerifyItemIsAbsentAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData("void")] [InlineData("string")] [InlineData("String")] [InlineData("(int, int)")] [InlineData("async void")] [InlineData("async System.Threading.Tasks.Task")] [InlineData("int Function")] public async Task NotAfterReturnTypeInLocalFunction(string returnType) { var markup = @$" using System; class C {{ void M(String parameter) {{ static {returnType} $$ }} }} "; await VerifyItemIsAbsentAsync(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(53585, "https://github.com/dotnet/roslyn/issues/53585")] public async Task AfterStaticLocalFunction_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { static $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData("extern")] [InlineData("static extern")] [InlineData("extern static")] [InlineData("async")] [InlineData("static async")] [InlineData("async static")] [InlineData("unsafe")] [InlineData("static unsafe")] [InlineData("unsafe static")] [InlineData("async unsafe")] [InlineData("unsafe async")] [InlineData("unsafe extern")] [InlineData("extern unsafe")] [InlineData("extern unsafe async static")] public async Task AfterLocalFunction_TypeOnly(string keyword) { var markup = $@" using System; class C {{ void M(String parameter) {{ {keyword} $$ }} }} "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] public async Task NotAfterAsyncLocalFunctionWithTwoAsyncs() { var markup = @" using System; class C { void M(String parameter) { async async $$ } } "; await VerifyItemIsAbsentAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData("void")] [InlineData("string")] [InlineData("String")] [InlineData("(int, int)")] [InlineData("async void")] [InlineData("async System.Threading.Tasks.Task")] [InlineData("int Function")] public async Task NotAfterReturnTypeInLocalFunction(string returnType) { var markup = @$" using System; class C {{ void M(String parameter) {{ static {returnType} $$ }} }} "; await VerifyItemIsAbsentAsync(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
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IPatternSwitchCase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IPatternSwitchCase : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_VarPatternDeclaration() { string source = @" using System; class X { void M() { int? x = 12; switch (x) { /*<bind>*/case var y:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case var y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var y') (InputType: System.Int32?, NarrowedType: System.Int32?, DeclaredSymbol: System.Int32? y, MatchesNull: True) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_PrimitiveTypePatternDeclaration() { string source = @" using System; class X { void M() { int? x = 12; switch (x) { /*<bind>*/case int y:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case int y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int y') (InputType: System.Int32?, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 y, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_ReferenceTypePatternDeclaration() { string source = @" using System; class X { void M(object x) { switch (x) { /*<bind>*/case X y:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case X y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'X y') (InputType: System.Object, NarrowedType: X, DeclaredSymbol: X y, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_TypeParameterTypePatternDeclaration() { string source = @" using System; class X { void M<T>(object x) where T : class { switch (x) { /*<bind>*/case T y:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case T y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'T y') (InputType: System.Object, NarrowedType: T, DeclaredSymbol: T y, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_DynamicTypePatternDeclaration() { string source = @" using System; class X { void M<T>(object x) where T : class { switch (x) { /*<bind>*/case dynamic y:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null, IsInvalid) (Syntax: 'case dynamic y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'dynamic y') (InputType: System.Object, NarrowedType: dynamic, DeclaredSymbol: dynamic y, MatchesNull: False) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS8208: It is not legal to use the type 'dynamic' in a pattern. // /*<bind>*/case dynamic y:/*</bind>*/ Diagnostic(ErrorCode.ERR_PatternDynamicType, "dynamic").WithLocation(9, 28) }; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_MixedDeclarationPatternAndConstantPatternClauses() { string source = @" using System; class X { void M(object x) { switch (x) { case null: break; /*<bind>*/case X y:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case X y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'X y') (InputType: System.Object, NarrowedType: X, DeclaredSymbol: X y, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_MixedDeclarationPatternAndConstantPatternClausesInSameSwitchSection() { string source = @" using System; class X { void M(object x) { switch (x) { case null: /*<bind>*/case X y:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case X y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'X y') (InputType: System.Object, NarrowedType: X, DeclaredSymbol: X y, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_MixedDeclarationPatternAndConstantPatternWithDefaultLabel() { string source = @" using System; class X { void M(object x) { switch (x) { case null: /*<bind>*/case X y:/*</bind>*/ default: break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case X y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'X y') (InputType: System.Object, NarrowedType: X, DeclaredSymbol: X y, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_GuardExpressionInPattern() { string source = @" using System; class X { void M(object x) { switch (x) { /*<bind>*/case X y when x != null:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case X y when x != null:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'X y') (InputType: System.Object, NarrowedType: X, DeclaredSymbol: X y, MatchesNull: False) Guard: IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x != null') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_PatternInGuardExpressionInPattern() { string source = @" using System; class X { void M(object x) { switch (x) { /*<bind>*/case X y when x is X z :/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case X y when x is X z :') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'X y') (InputType: System.Object, NarrowedType: X, DeclaredSymbol: X y, MatchesNull: False) Guard: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is X z') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'X z') (InputType: System.Object, NarrowedType: X, DeclaredSymbol: X z, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_SyntaxErrorInGuardExpressionInPattern() { string source = @" using System; class X { void M(object x) { switch (x) { /*<bind>*/case X y when :/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null, IsInvalid) (Syntax: 'case X y when :') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'X y') (InputType: System.Object, NarrowedType: X, DeclaredSymbol: X y, MatchesNull: False) Guard: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ':' // /*<bind>*/case X y when :/*</bind>*/ Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":").WithLocation(9, 37) }; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_SemanticErrorInGuardExpressionInPattern() { string source = @" using System; class X { void M(object x) { switch (x) { /*<bind>*/case X y when x:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null, IsInvalid) (Syntax: 'case X y when x:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'X y') (InputType: System.Object, NarrowedType: X, DeclaredSymbol: X y, MatchesNull: False) Guard: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object, IsInvalid) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0266: Cannot implicitly convert type 'object' to 'bool'. An explicit conversion exists (are you missing a cast?) // /*<bind>*/case X y when x:/*</bind>*/ Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "bool").WithLocation(9, 37) }; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_ConstantPattern() { string source = @" using System; class X { void M(bool x) { switch (x) { case /*<bind>*/x is true/*</bind>*/: break; } } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'x is true') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'x') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: 'true') (InputType: System.Boolean, NarrowedType: System.Boolean) Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsInvalid) (Syntax: 'true') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0150: A constant value is expected // case /*<bind>*/x is true/*</bind>*/: Diagnostic(ErrorCode.ERR_ConstantExpected, "x is true").WithLocation(9, 28) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_DefaultLabel() { string source = @" using System; class X { void M(object x) { switch (x) { case X y: /*<bind>*/default:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IDefaultCaseClauseOperation (Label Id: 0) (CaseKind.Default) (OperationKind.CaseClause, Type: null) (Syntax: 'default:') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<DefaultSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_InvalidTypeSwitch() { string source = @" using System; class X { void M(object x) { switch (x.GetType()) { /*<bind>*/case typeof(X):/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null, IsInvalid) (Syntax: 'case typeof(X):') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'typeof(X)') (InputType: System.Type, NarrowedType: System.Type) Value: ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'typeof(X)') TypeOperand: X "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0150: A constant value is expected // /*<bind>*/case typeof(X):/*</bind>*/ Diagnostic(ErrorCode.ERR_ConstantExpected, "typeof(X)").WithLocation(9, 28) }; VerifyOperationTreeAndDiagnosticsForTest<CaseSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_UndefinedTypeInPatternDeclaration() { string source = @" using System; class X { void M(object x) { switch (x) { /*<bind>*/case UndefinedType y:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null, IsInvalid) (Syntax: 'case UndefinedType y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'UndefinedType y') (InputType: System.Object, NarrowedType: UndefinedType, DeclaredSymbol: UndefinedType y, MatchesNull: False) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0246: The type or namespace name 'UndefinedType' could not be found (are you missing a using directive or an assembly reference?) // /*<bind>*/case UndefinedType y:/*</bind>*/ Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UndefinedType").WithArguments("UndefinedType").WithLocation(9, 28) }; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_InvalidTypeInPatternDeclaration() { string source = @" using System; class X { void M(int? x) { switch (x) { /*<bind>*/case X y:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null, IsInvalid) (Syntax: 'case X y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'X y') (InputType: System.Int32?, NarrowedType: X, DeclaredSymbol: X y, MatchesNull: False) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(9,28): error CS8121: An expression of type 'int?' cannot be handled by a pattern of type 'X'. // /*<bind>*/case X y:/*</bind>*/ Diagnostic(ErrorCode.ERR_PatternWrongType, "X").WithArguments("int?", "X").WithLocation(9, 28) }; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_DuplicateLocalInPatternDeclaration() { string source = @" using System; class X { void M(int? x) { int? y = 0; switch (x) { /*<bind>*/case int y:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null, IsInvalid) (Syntax: 'case int y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int y') (InputType: System.Int32?, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 y, MatchesNull: False) "; var expectedDiagnostics = new DiagnosticDescription[] { // 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 // /*<bind>*/case int y:/*</bind>*/ Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y").WithArguments("y").WithLocation(10, 32), // CS0219: The variable 'y' is assigned but its value is never used // int? y = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(7, 14) }; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_InvalidConstDeclarationInPatternDeclaration() { string source = @" using System; class X { void M(int? x) { switch (x) { /*<bind>*/case /*</bind>*/const int y: break; } } } "; string expectedOperationTree = @" ISingleValueCaseClauseOperation (Label Id: 0) (CaseKind.SingleValue) (OperationKind.CaseClause, Type: null, IsInvalid) (Syntax: 'case /*</bind>*/') Value: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term 'const' // /*<bind>*/case /*</bind>*/const int y: Diagnostic(ErrorCode.ERR_InvalidExprTerm, "const").WithArguments("const").WithLocation(9, 39), // CS1003: Syntax error, ':' expected // /*<bind>*/case /*</bind>*/const int y: Diagnostic(ErrorCode.ERR_SyntaxError, "const").WithArguments(":", "const").WithLocation(9, 39), // CS0145: A const field requires a value to be provided // /*<bind>*/case /*</bind>*/const int y: Diagnostic(ErrorCode.ERR_ConstValueRequired, "y").WithLocation(9, 49), // CS1002: ; expected // /*<bind>*/case /*</bind>*/const int y: Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(9, 50), // CS1513: } expected // /*<bind>*/case /*</bind>*/const int y: Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(9, 50), // CS0168: The variable 'y' is declared but never used // /*<bind>*/case /*</bind>*/const int y: Diagnostic(ErrorCode.WRN_UnreferencedVar, "y").WithArguments("y").WithLocation(9, 49) }; VerifyOperationTreeAndDiagnosticsForTest<CaseSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_RedundantPatternDeclarationClauses() { string source = @" using System; class X { void M(object p) { /*<bind>*/switch (p) { case int x: break; case int y: break; case X z: break; }/*</bind>*/ } } "; string expectedOperationTree = @" ISwitchOperation (3 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null, IsInvalid) (Syntax: 'switch (p) ... }') Switch expression: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p') Sections: ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case int x: ... break;') Locals: Local_1: System.Int32 x Clauses: IPatternCaseClauseOperation (Label Id: 1) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case int x:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int x') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False) Body: IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;') ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null, IsInvalid) (Syntax: 'case int y: ... break;') Locals: Local_1: System.Int32 y Clauses: IPatternCaseClauseOperation (Label Id: 2) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null, IsInvalid) (Syntax: 'case int y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int y') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 y, MatchesNull: False) Body: IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;') ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case X z: ... break;') Locals: Local_1: X z Clauses: IPatternCaseClauseOperation (Label Id: 3) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case X z:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'X z') (InputType: System.Object, NarrowedType: X, DeclaredSymbol: X z, MatchesNull: False) Body: IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(11,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case int y: Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "int y").WithLocation(11, 18) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestPatternCaseClause_PatternCombinatorsAndRelationalPatterns_01() { string source = @" class X { void M(char c) { switch (c) { /*<bind>*/case (>= 'A' and <= 'Z') or (>= 'a' and <= 'z'):/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case (>= 'A ... nd <= 'z'):') Pattern: IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: '(>= 'A' and ... and <= 'z')') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IBinaryPatternOperation (BinaryOperatorKind.And) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= 'A' and <= 'Z'') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IRelationalPatternOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '>= 'A'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: A) (Syntax: ''A'') RightPattern: IRelationalPatternOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '<= 'Z'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: Z) (Syntax: ''Z'') RightPattern: IBinaryPatternOperation (BinaryOperatorKind.And) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= 'a' and <= 'z'') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IRelationalPatternOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '>= 'a'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: a) (Syntax: ''a'') RightPattern: IRelationalPatternOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '<= 'z'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: z) (Syntax: ''z'') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestPatternCaseClause_TypePatterns_01() { string source = @" class X { void M(object o) { switch (o) { /*<bind>*/case int or long or bool:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case int or ... ng or bool:') Pattern: IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: 'int or long or bool') (InputType: System.Object, NarrowedType: System.Object) LeftPattern: IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: 'int or long') (InputType: System.Object, NarrowedType: System.Object) LeftPattern: ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'int') (InputType: System.Object, NarrowedType: System.Int32, MatchedType: System.Int32) RightPattern: ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'long') (InputType: System.Object, NarrowedType: System.Int64, MatchedType: System.Int64) RightPattern: ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'bool') (InputType: System.Object, NarrowedType: System.Boolean, MatchedType: System.Boolean) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IPatternSwitchCase : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_VarPatternDeclaration() { string source = @" using System; class X { void M() { int? x = 12; switch (x) { /*<bind>*/case var y:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case var y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'var y') (InputType: System.Int32?, NarrowedType: System.Int32?, DeclaredSymbol: System.Int32? y, MatchesNull: True) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_PrimitiveTypePatternDeclaration() { string source = @" using System; class X { void M() { int? x = 12; switch (x) { /*<bind>*/case int y:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case int y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int y') (InputType: System.Int32?, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 y, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_ReferenceTypePatternDeclaration() { string source = @" using System; class X { void M(object x) { switch (x) { /*<bind>*/case X y:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case X y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'X y') (InputType: System.Object, NarrowedType: X, DeclaredSymbol: X y, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_TypeParameterTypePatternDeclaration() { string source = @" using System; class X { void M<T>(object x) where T : class { switch (x) { /*<bind>*/case T y:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case T y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'T y') (InputType: System.Object, NarrowedType: T, DeclaredSymbol: T y, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_DynamicTypePatternDeclaration() { string source = @" using System; class X { void M<T>(object x) where T : class { switch (x) { /*<bind>*/case dynamic y:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null, IsInvalid) (Syntax: 'case dynamic y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'dynamic y') (InputType: System.Object, NarrowedType: dynamic, DeclaredSymbol: dynamic y, MatchesNull: False) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS8208: It is not legal to use the type 'dynamic' in a pattern. // /*<bind>*/case dynamic y:/*</bind>*/ Diagnostic(ErrorCode.ERR_PatternDynamicType, "dynamic").WithLocation(9, 28) }; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_MixedDeclarationPatternAndConstantPatternClauses() { string source = @" using System; class X { void M(object x) { switch (x) { case null: break; /*<bind>*/case X y:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case X y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'X y') (InputType: System.Object, NarrowedType: X, DeclaredSymbol: X y, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_MixedDeclarationPatternAndConstantPatternClausesInSameSwitchSection() { string source = @" using System; class X { void M(object x) { switch (x) { case null: /*<bind>*/case X y:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case X y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'X y') (InputType: System.Object, NarrowedType: X, DeclaredSymbol: X y, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_MixedDeclarationPatternAndConstantPatternWithDefaultLabel() { string source = @" using System; class X { void M(object x) { switch (x) { case null: /*<bind>*/case X y:/*</bind>*/ default: break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case X y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'X y') (InputType: System.Object, NarrowedType: X, DeclaredSymbol: X y, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_GuardExpressionInPattern() { string source = @" using System; class X { void M(object x) { switch (x) { /*<bind>*/case X y when x != null:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case X y when x != null:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'X y') (InputType: System.Object, NarrowedType: X, DeclaredSymbol: X y, MatchesNull: False) Guard: IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x != null') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_PatternInGuardExpressionInPattern() { string source = @" using System; class X { void M(object x) { switch (x) { /*<bind>*/case X y when x is X z :/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case X y when x is X z :') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'X y') (InputType: System.Object, NarrowedType: X, DeclaredSymbol: X y, MatchesNull: False) Guard: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'x is X z') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'X z') (InputType: System.Object, NarrowedType: X, DeclaredSymbol: X z, MatchesNull: False) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_SyntaxErrorInGuardExpressionInPattern() { string source = @" using System; class X { void M(object x) { switch (x) { /*<bind>*/case X y when :/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null, IsInvalid) (Syntax: 'case X y when :') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'X y') (InputType: System.Object, NarrowedType: X, DeclaredSymbol: X y, MatchesNull: False) Guard: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term ':' // /*<bind>*/case X y when :/*</bind>*/ Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":").WithLocation(9, 37) }; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_SemanticErrorInGuardExpressionInPattern() { string source = @" using System; class X { void M(object x) { switch (x) { /*<bind>*/case X y when x:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null, IsInvalid) (Syntax: 'case X y when x:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'X y') (InputType: System.Object, NarrowedType: X, DeclaredSymbol: X y, MatchesNull: False) Guard: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object, IsInvalid) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0266: Cannot implicitly convert type 'object' to 'bool'. An explicit conversion exists (are you missing a cast?) // /*<bind>*/case X y when x:/*</bind>*/ Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "bool").WithLocation(9, 37) }; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_ConstantPattern() { string source = @" using System; class X { void M(bool x) { switch (x) { case /*<bind>*/x is true/*</bind>*/: break; } } } "; string expectedOperationTree = @" IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'x is true') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'x') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: 'true') (InputType: System.Boolean, NarrowedType: System.Boolean) Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True, IsInvalid) (Syntax: 'true') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0150: A constant value is expected // case /*<bind>*/x is true/*</bind>*/: Diagnostic(ErrorCode.ERR_ConstantExpected, "x is true").WithLocation(9, 28) }; VerifyOperationTreeAndDiagnosticsForTest<IsPatternExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_DefaultLabel() { string source = @" using System; class X { void M(object x) { switch (x) { case X y: /*<bind>*/default:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IDefaultCaseClauseOperation (Label Id: 0) (CaseKind.Default) (OperationKind.CaseClause, Type: null) (Syntax: 'default:') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<DefaultSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_InvalidTypeSwitch() { string source = @" using System; class X { void M(object x) { switch (x.GetType()) { /*<bind>*/case typeof(X):/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null, IsInvalid) (Syntax: 'case typeof(X):') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'typeof(X)') (InputType: System.Type, NarrowedType: System.Type) Value: ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'typeof(X)') TypeOperand: X "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0150: A constant value is expected // /*<bind>*/case typeof(X):/*</bind>*/ Diagnostic(ErrorCode.ERR_ConstantExpected, "typeof(X)").WithLocation(9, 28) }; VerifyOperationTreeAndDiagnosticsForTest<CaseSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_UndefinedTypeInPatternDeclaration() { string source = @" using System; class X { void M(object x) { switch (x) { /*<bind>*/case UndefinedType y:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null, IsInvalid) (Syntax: 'case UndefinedType y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'UndefinedType y') (InputType: System.Object, NarrowedType: UndefinedType, DeclaredSymbol: UndefinedType y, MatchesNull: False) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0246: The type or namespace name 'UndefinedType' could not be found (are you missing a using directive or an assembly reference?) // /*<bind>*/case UndefinedType y:/*</bind>*/ Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UndefinedType").WithArguments("UndefinedType").WithLocation(9, 28) }; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_InvalidTypeInPatternDeclaration() { string source = @" using System; class X { void M(int? x) { switch (x) { /*<bind>*/case X y:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null, IsInvalid) (Syntax: 'case X y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'X y') (InputType: System.Int32?, NarrowedType: X, DeclaredSymbol: X y, MatchesNull: False) "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(9,28): error CS8121: An expression of type 'int?' cannot be handled by a pattern of type 'X'. // /*<bind>*/case X y:/*</bind>*/ Diagnostic(ErrorCode.ERR_PatternWrongType, "X").WithArguments("int?", "X").WithLocation(9, 28) }; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_DuplicateLocalInPatternDeclaration() { string source = @" using System; class X { void M(int? x) { int? y = 0; switch (x) { /*<bind>*/case int y:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null, IsInvalid) (Syntax: 'case int y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int y') (InputType: System.Int32?, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 y, MatchesNull: False) "; var expectedDiagnostics = new DiagnosticDescription[] { // 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 // /*<bind>*/case int y:/*</bind>*/ Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y").WithArguments("y").WithLocation(10, 32), // CS0219: The variable 'y' is assigned but its value is never used // int? y = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(7, 14) }; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_InvalidConstDeclarationInPatternDeclaration() { string source = @" using System; class X { void M(int? x) { switch (x) { /*<bind>*/case /*</bind>*/const int y: break; } } } "; string expectedOperationTree = @" ISingleValueCaseClauseOperation (Label Id: 0) (CaseKind.SingleValue) (OperationKind.CaseClause, Type: null, IsInvalid) (Syntax: 'case /*</bind>*/') Value: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1525: Invalid expression term 'const' // /*<bind>*/case /*</bind>*/const int y: Diagnostic(ErrorCode.ERR_InvalidExprTerm, "const").WithArguments("const").WithLocation(9, 39), // CS1003: Syntax error, ':' expected // /*<bind>*/case /*</bind>*/const int y: Diagnostic(ErrorCode.ERR_SyntaxError, "const").WithArguments(":", "const").WithLocation(9, 39), // CS0145: A const field requires a value to be provided // /*<bind>*/case /*</bind>*/const int y: Diagnostic(ErrorCode.ERR_ConstValueRequired, "y").WithLocation(9, 49), // CS1002: ; expected // /*<bind>*/case /*</bind>*/const int y: Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(9, 50), // CS1513: } expected // /*<bind>*/case /*</bind>*/const int y: Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(9, 50), // CS0168: The variable 'y' is declared but never used // /*<bind>*/case /*</bind>*/const int y: Diagnostic(ErrorCode.WRN_UnreferencedVar, "y").WithArguments("y").WithLocation(9, 49) }; VerifyOperationTreeAndDiagnosticsForTest<CaseSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(19927, "https://github.com/dotnet/roslyn/issues/19927")] public void TestPatternCaseClause_RedundantPatternDeclarationClauses() { string source = @" using System; class X { void M(object p) { /*<bind>*/switch (p) { case int x: break; case int y: break; case X z: break; }/*</bind>*/ } } "; string expectedOperationTree = @" ISwitchOperation (3 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null, IsInvalid) (Syntax: 'switch (p) ... }') Switch expression: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'p') Sections: ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case int x: ... break;') Locals: Local_1: System.Int32 x Clauses: IPatternCaseClauseOperation (Label Id: 1) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case int x:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int x') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False) Body: IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;') ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null, IsInvalid) (Syntax: 'case int y: ... break;') Locals: Local_1: System.Int32 y Clauses: IPatternCaseClauseOperation (Label Id: 2) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null, IsInvalid) (Syntax: 'case int y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int y') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 y, MatchesNull: False) Body: IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;') ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case X z: ... break;') Locals: Local_1: X z Clauses: IPatternCaseClauseOperation (Label Id: 3) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case X z:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'X z') (InputType: System.Object, NarrowedType: X, DeclaredSymbol: X z, MatchesNull: False) Body: IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(11,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case int y: Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "int y").WithLocation(11, 18) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestPatternCaseClause_PatternCombinatorsAndRelationalPatterns_01() { string source = @" class X { void M(char c) { switch (c) { /*<bind>*/case (>= 'A' and <= 'Z') or (>= 'a' and <= 'z'):/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case (>= 'A ... nd <= 'z'):') Pattern: IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: '(>= 'A' and ... and <= 'z')') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IBinaryPatternOperation (BinaryOperatorKind.And) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= 'A' and <= 'Z'') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IRelationalPatternOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '>= 'A'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: A) (Syntax: ''A'') RightPattern: IRelationalPatternOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '<= 'Z'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: Z) (Syntax: ''Z'') RightPattern: IBinaryPatternOperation (BinaryOperatorKind.And) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= 'a' and <= 'z'') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IRelationalPatternOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '>= 'a'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: a) (Syntax: ''a'') RightPattern: IRelationalPatternOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '<= 'z'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: z) (Syntax: ''z'') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestPatternCaseClause_TypePatterns_01() { string source = @" class X { void M(object o) { switch (o) { /*<bind>*/case int or long or bool:/*</bind>*/ break; } } } "; string expectedOperationTree = @" IPatternCaseClauseOperation (Label Id: 0) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case int or ... ng or bool:') Pattern: IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: 'int or long or bool') (InputType: System.Object, NarrowedType: System.Object) LeftPattern: IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: 'int or long') (InputType: System.Object, NarrowedType: System.Object) LeftPattern: ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'int') (InputType: System.Object, NarrowedType: System.Int32, MatchedType: System.Int32) RightPattern: ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'long') (InputType: System.Object, NarrowedType: System.Int64, MatchedType: System.Int64) RightPattern: ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'bool') (InputType: System.Object, NarrowedType: System.Boolean, MatchedType: System.Boolean) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<CasePatternSwitchLabelSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators); } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Workspaces/Core/Portable/ExternalAccess/VSTypeScript/Api/VSTypeScriptDocumentationCommentWrapper.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Shared.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal readonly struct VSTypeScriptDocumentationCommentWrapper { private readonly DocumentationComment _underlyingObject; public VSTypeScriptDocumentationCommentWrapper(DocumentationComment underlyingObject) => _underlyingObject = underlyingObject; public static VSTypeScriptDocumentationCommentWrapper FromXmlFragment(string xml) => new(DocumentationComment.FromXmlFragment(xml)); public bool IsDefault => _underlyingObject == null; public string? SummaryTextOpt => _underlyingObject?.SummaryText; public string? GetParameterTextOpt(string parameterName) => _underlyingObject?.GetParameterText(parameterName); } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Shared.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal readonly struct VSTypeScriptDocumentationCommentWrapper { private readonly DocumentationComment _underlyingObject; public VSTypeScriptDocumentationCommentWrapper(DocumentationComment underlyingObject) => _underlyingObject = underlyingObject; public static VSTypeScriptDocumentationCommentWrapper FromXmlFragment(string xml) => new(DocumentationComment.FromXmlFragment(xml)); public bool IsDefault => _underlyingObject == null; public string? SummaryTextOpt => _underlyingObject?.SummaryText; public string? GetParameterTextOpt(string parameterName) => _underlyingObject?.GetParameterText(parameterName); } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Compilers/Core/Portable/ReferenceManager/ModuleReferences.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Symbols; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// A record of the assemblies referenced by a module (their identities, symbols, and unification). /// </summary> internal sealed class ModuleReferences<TAssemblySymbol> where TAssemblySymbol : class, IAssemblySymbolInternal { /// <summary> /// Identities of referenced assemblies (those that are or will be emitted to metadata). /// </summary> /// <remarks> /// Names[i] is the identity of assembly Symbols[i]. /// </remarks> public readonly ImmutableArray<AssemblyIdentity> Identities; /// <summary> /// Assembly symbols that the identities are resolved against. /// </summary> /// <remarks> /// Names[i] is the identity of assembly Symbols[i]. /// Unresolved references are represented as MissingAssemblySymbols. /// </remarks> public readonly ImmutableArray<TAssemblySymbol> Symbols; /// <summary> /// A subset of <see cref="Symbols"/> that correspond to references with non-matching (unified) /// version along with unification details. /// </summary> public readonly ImmutableArray<UnifiedAssembly<TAssemblySymbol>> UnifiedAssemblies; public ModuleReferences( ImmutableArray<AssemblyIdentity> identities, ImmutableArray<TAssemblySymbol> symbols, ImmutableArray<UnifiedAssembly<TAssemblySymbol>> unifiedAssemblies) { Debug.Assert(!identities.IsDefault); Debug.Assert(!symbols.IsDefault); Debug.Assert(identities.Length == symbols.Length); Debug.Assert(!unifiedAssemblies.IsDefault); this.Identities = identities; this.Symbols = symbols; this.UnifiedAssemblies = unifiedAssemblies; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Symbols; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// A record of the assemblies referenced by a module (their identities, symbols, and unification). /// </summary> internal sealed class ModuleReferences<TAssemblySymbol> where TAssemblySymbol : class, IAssemblySymbolInternal { /// <summary> /// Identities of referenced assemblies (those that are or will be emitted to metadata). /// </summary> /// <remarks> /// Names[i] is the identity of assembly Symbols[i]. /// </remarks> public readonly ImmutableArray<AssemblyIdentity> Identities; /// <summary> /// Assembly symbols that the identities are resolved against. /// </summary> /// <remarks> /// Names[i] is the identity of assembly Symbols[i]. /// Unresolved references are represented as MissingAssemblySymbols. /// </remarks> public readonly ImmutableArray<TAssemblySymbol> Symbols; /// <summary> /// A subset of <see cref="Symbols"/> that correspond to references with non-matching (unified) /// version along with unification details. /// </summary> public readonly ImmutableArray<UnifiedAssembly<TAssemblySymbol>> UnifiedAssemblies; public ModuleReferences( ImmutableArray<AssemblyIdentity> identities, ImmutableArray<TAssemblySymbol> symbols, ImmutableArray<UnifiedAssembly<TAssemblySymbol>> unifiedAssemblies) { Debug.Assert(!identities.IsDefault); Debug.Assert(!symbols.IsDefault); Debug.Assert(identities.Length == symbols.Length); Debug.Assert(!unifiedAssemblies.IsDefault); this.Identities = identities; this.Symbols = symbols; this.UnifiedAssemblies = unifiedAssemblies; } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Tools/ExternalAccess/FSharp/Internal/Completion/FSharpInternalCommonCompletionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Completion; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Completion; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Completion { internal sealed class FSharpInternalCommonCompletionProvider : CommonCompletionProvider { private readonly IFSharpCommonCompletionProvider _provider; public FSharpInternalCommonCompletionProvider(IFSharpCommonCompletionProvider provider) { _provider = provider; } public override Task ProvideCompletionsAsync(CompletionContext context) { return _provider.ProvideCompletionsAsync(context); } protected override Task<TextChange?> GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) { return _provider.GetTextChangeAsync(base.GetTextChangeAsync, selectedItem, ch, cancellationToken); } public override bool IsInsertionTrigger(SourceText text, int insertedCharacterPosition, OptionSet options) { return _provider.IsInsertionTrigger(text, insertedCharacterPosition, options); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Completion; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Completion { internal sealed class FSharpInternalCommonCompletionProvider : CommonCompletionProvider { private readonly IFSharpCommonCompletionProvider _provider; public FSharpInternalCommonCompletionProvider(IFSharpCommonCompletionProvider provider) { _provider = provider; } public override Task ProvideCompletionsAsync(CompletionContext context) { return _provider.ProvideCompletionsAsync(context); } protected override Task<TextChange?> GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) { return _provider.GetTextChangeAsync(base.GetTextChangeAsync, selectedItem, ch, cancellationToken); } public override bool IsInsertionTrigger(SourceText text, int insertedCharacterPosition, OptionSet options) { return _provider.IsInsertionTrigger(text, insertedCharacterPosition, options); } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Analyzers/Core/CodeFixes/UseObjectInitializer/AbstractUseObjectInitializerCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseObjectInitializer { internal abstract class AbstractUseObjectInitializerCodeFixProvider< TSyntaxKind, TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TAssignmentStatementSyntax, TVariableDeclaratorSyntax> : SyntaxEditorBasedCodeFixProvider where TSyntaxKind : struct where TExpressionSyntax : SyntaxNode where TStatementSyntax : SyntaxNode where TObjectCreationExpressionSyntax : TExpressionSyntax where TMemberAccessExpressionSyntax : TExpressionSyntax where TAssignmentStatementSyntax : TStatementSyntax where TVariableDeclaratorSyntax : SyntaxNode { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseObjectInitializerDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.Descriptor.CustomTags.Contains(WellKnownDiagnosticTags.Unnecessary); public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { // Fix-All for this feature is somewhat complicated. As Object-Initializers // could be arbitrarily nested, we have to make sure that any edits we make // to one Object-Initializer are seen by any higher ones. In order to do this // we actually process each object-creation-node, one at a time, rewriting // the tree for each node. In order to do this effectively, we use the '.TrackNodes' // feature to keep track of all the object creation nodes as we make edits to // the tree. If we didn't do this, then we wouldn't be able to find the // second object-creation-node after we make the edit for the first one. var workspace = document.Project.Solution.Workspace; var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var originalRoot = editor.OriginalRoot; var originalObjectCreationNodes = new Stack<TObjectCreationExpressionSyntax>(); foreach (var diagnostic in diagnostics) { var objectCreation = (TObjectCreationExpressionSyntax)originalRoot.FindNode( diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true); originalObjectCreationNodes.Push(objectCreation); } // We're going to be continually editing this tree. Track all the nodes we // care about so we can find them across each edit. document = document.WithSyntaxRoot(originalRoot.TrackNodes(originalObjectCreationNodes)); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var currentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); while (originalObjectCreationNodes.Count > 0) { var originalObjectCreation = originalObjectCreationNodes.Pop(); var objectCreation = currentRoot.GetCurrentNodes(originalObjectCreation).Single(); var matches = ObjectCreationExpressionAnalyzer<TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TAssignmentStatementSyntax, TVariableDeclaratorSyntax>.Analyze( semanticModel, syntaxFacts, objectCreation, cancellationToken); if (matches == null || matches.Value.Length == 0) { continue; } var statement = objectCreation.FirstAncestorOrSelf<TStatementSyntax>(); var newStatement = GetNewStatement(statement, objectCreation, matches.Value) .WithAdditionalAnnotations(Formatter.Annotation); var subEditor = new SyntaxEditor(currentRoot, workspace); subEditor.ReplaceNode(statement, newStatement); foreach (var match in matches) { subEditor.RemoveNode(match.Statement, SyntaxRemoveOptions.KeepUnbalancedDirectives); } document = document.WithSyntaxRoot(subEditor.GetChangedRoot()); semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); currentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); } editor.ReplaceNode(editor.OriginalRoot, currentRoot); } protected abstract TStatementSyntax GetNewStatement( TStatementSyntax statement, TObjectCreationExpressionSyntax objectCreation, ImmutableArray<Match<TExpressionSyntax, TStatementSyntax, TMemberAccessExpressionSyntax, TAssignmentStatementSyntax>> matches); private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Object_initialization_can_be_simplified, createChangedDocument, nameof(AnalyzersResources.Object_initialization_can_be_simplified)) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseObjectInitializer { internal abstract class AbstractUseObjectInitializerCodeFixProvider< TSyntaxKind, TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TAssignmentStatementSyntax, TVariableDeclaratorSyntax> : SyntaxEditorBasedCodeFixProvider where TSyntaxKind : struct where TExpressionSyntax : SyntaxNode where TStatementSyntax : SyntaxNode where TObjectCreationExpressionSyntax : TExpressionSyntax where TMemberAccessExpressionSyntax : TExpressionSyntax where TAssignmentStatementSyntax : TStatementSyntax where TVariableDeclaratorSyntax : SyntaxNode { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseObjectInitializerDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected override bool IncludeDiagnosticDuringFixAll(Diagnostic diagnostic) => !diagnostic.Descriptor.CustomTags.Contains(WellKnownDiagnosticTags.Unnecessary); public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { // Fix-All for this feature is somewhat complicated. As Object-Initializers // could be arbitrarily nested, we have to make sure that any edits we make // to one Object-Initializer are seen by any higher ones. In order to do this // we actually process each object-creation-node, one at a time, rewriting // the tree for each node. In order to do this effectively, we use the '.TrackNodes' // feature to keep track of all the object creation nodes as we make edits to // the tree. If we didn't do this, then we wouldn't be able to find the // second object-creation-node after we make the edit for the first one. var workspace = document.Project.Solution.Workspace; var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var originalRoot = editor.OriginalRoot; var originalObjectCreationNodes = new Stack<TObjectCreationExpressionSyntax>(); foreach (var diagnostic in diagnostics) { var objectCreation = (TObjectCreationExpressionSyntax)originalRoot.FindNode( diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true); originalObjectCreationNodes.Push(objectCreation); } // We're going to be continually editing this tree. Track all the nodes we // care about so we can find them across each edit. document = document.WithSyntaxRoot(originalRoot.TrackNodes(originalObjectCreationNodes)); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var currentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); while (originalObjectCreationNodes.Count > 0) { var originalObjectCreation = originalObjectCreationNodes.Pop(); var objectCreation = currentRoot.GetCurrentNodes(originalObjectCreation).Single(); var matches = ObjectCreationExpressionAnalyzer<TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TAssignmentStatementSyntax, TVariableDeclaratorSyntax>.Analyze( semanticModel, syntaxFacts, objectCreation, cancellationToken); if (matches == null || matches.Value.Length == 0) { continue; } var statement = objectCreation.FirstAncestorOrSelf<TStatementSyntax>(); var newStatement = GetNewStatement(statement, objectCreation, matches.Value) .WithAdditionalAnnotations(Formatter.Annotation); var subEditor = new SyntaxEditor(currentRoot, workspace); subEditor.ReplaceNode(statement, newStatement); foreach (var match in matches) { subEditor.RemoveNode(match.Statement, SyntaxRemoveOptions.KeepUnbalancedDirectives); } document = document.WithSyntaxRoot(subEditor.GetChangedRoot()); semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); currentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); } editor.ReplaceNode(editor.OriginalRoot, currentRoot); } protected abstract TStatementSyntax GetNewStatement( TStatementSyntax statement, TObjectCreationExpressionSyntax objectCreation, ImmutableArray<Match<TExpressionSyntax, TStatementSyntax, TMemberAccessExpressionSyntax, TAssignmentStatementSyntax>> matches); private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Object_initialization_can_be_simplified, createChangedDocument, nameof(AnalyzersResources.Object_initialization_can_be_simplified)) { } } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Compilers/CSharp/Portable/Binder/Binder_WithExpression.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts a <see cref="WithExpressionSyntax"/> into a <see cref="BoundExpression"/>. /// </summary> internal partial class Binder { private BoundExpression BindWithExpression(WithExpressionSyntax syntax, BindingDiagnosticBag diagnostics) { var receiver = BindRValueWithoutTargetType(syntax.Expression, diagnostics); var receiverType = receiver.Type; var lookupResult = LookupResult.GetInstance(); bool hasErrors = false; if (receiverType is null || receiverType.IsVoidType()) { diagnostics.Add(ErrorCode.ERR_InvalidWithReceiverType, syntax.Expression.Location); receiverType = CreateErrorType(); } MethodSymbol? cloneMethod = null; if (receiverType.IsValueType && !receiverType.IsPointerOrFunctionPointer()) { CheckFeatureAvailability(syntax, MessageID.IDS_FeatureWithOnStructs, diagnostics); } else if (receiverType.IsAnonymousType) { CheckFeatureAvailability(syntax, MessageID.IDS_FeatureWithOnAnonymousTypes, diagnostics); } else if (!receiverType.IsErrorType()) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); cloneMethod = SynthesizedRecordClone.FindValidCloneMethod(receiverType is TypeParameterSymbol typeParameter ? typeParameter.EffectiveBaseClass(ref useSiteInfo) : receiverType, ref useSiteInfo); if (cloneMethod is null) { hasErrors = true; diagnostics.Add(ErrorCode.ERR_CannotClone, syntax.Expression.Location, receiverType); } else { cloneMethod.AddUseSiteInfo(ref useSiteInfo); } diagnostics.Add(syntax.Expression, useSiteInfo); } var initializer = BindInitializerExpression( syntax.Initializer, receiverType, syntax.Expression, isForNewInstance: true, diagnostics); // N.B. Since we don't parse nested initializers in syntax there should be no extra // errors we need to check for here. return new BoundWithExpression( syntax, receiver, cloneMethod, initializer, receiverType, hasErrors: hasErrors); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts a <see cref="WithExpressionSyntax"/> into a <see cref="BoundExpression"/>. /// </summary> internal partial class Binder { private BoundExpression BindWithExpression(WithExpressionSyntax syntax, BindingDiagnosticBag diagnostics) { var receiver = BindRValueWithoutTargetType(syntax.Expression, diagnostics); var receiverType = receiver.Type; var lookupResult = LookupResult.GetInstance(); bool hasErrors = false; if (receiverType is null || receiverType.IsVoidType()) { diagnostics.Add(ErrorCode.ERR_InvalidWithReceiverType, syntax.Expression.Location); receiverType = CreateErrorType(); } MethodSymbol? cloneMethod = null; if (receiverType.IsValueType && !receiverType.IsPointerOrFunctionPointer()) { CheckFeatureAvailability(syntax, MessageID.IDS_FeatureWithOnStructs, diagnostics); } else if (receiverType.IsAnonymousType) { CheckFeatureAvailability(syntax, MessageID.IDS_FeatureWithOnAnonymousTypes, diagnostics); } else if (!receiverType.IsErrorType()) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); cloneMethod = SynthesizedRecordClone.FindValidCloneMethod(receiverType is TypeParameterSymbol typeParameter ? typeParameter.EffectiveBaseClass(ref useSiteInfo) : receiverType, ref useSiteInfo); if (cloneMethod is null) { hasErrors = true; diagnostics.Add(ErrorCode.ERR_CannotClone, syntax.Expression.Location, receiverType); } else { cloneMethod.AddUseSiteInfo(ref useSiteInfo); } diagnostics.Add(syntax.Expression, useSiteInfo); } var initializer = BindInitializerExpression( syntax.Initializer, receiverType, syntax.Expression, isForNewInstance: true, diagnostics); // N.B. Since we don't parse nested initializers in syntax there should be no extra // errors we need to check for here. return new BoundWithExpression( syntax, receiver, cloneMethod, initializer, receiverType, hasErrors: hasErrors); } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/ParenthesizedExpressionSyntaxExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class ParenthesizedExpressionSyntaxExtensions { public static bool CanRemoveParentheses( this ParenthesizedExpressionSyntax node, SemanticModel semanticModel, CancellationToken cancellationToken) { if (node.OpenParenToken.IsMissing || node.CloseParenToken.IsMissing) { // int x = (3; return false; } var expression = node.Expression; // The 'direct' expression that contains this parenthesized node. Note: in the case // of code like: ```x is (y)``` there is an intermediary 'no-syntax' 'ConstantPattern' // node between the 'is-pattern' node and the parenthesized expression. So we manually // jump past that as, for all intents and purposes, we want to consider the 'is' expression // as the parent expression of the (y) expression. var parentExpression = node.IsParentKind(SyntaxKind.ConstantPattern) ? node.Parent.Parent as ExpressionSyntax : node.Parent as ExpressionSyntax; // Have to be careful if we would remove parens and cause a + and a + to become a ++. // (same with - as well). var tokenBeforeParen = node.GetFirstToken().GetPreviousToken(); var tokenAfterParen = node.Expression.GetFirstToken(); var previousChar = tokenBeforeParen.Text.LastOrDefault(); var nextChar = tokenAfterParen.Text.FirstOrDefault(); if ((previousChar == '+' && nextChar == '+') || (previousChar == '-' && nextChar == '-')) { return false; } // Simplest cases: // ((x)) -> (x) if (expression.IsKind(SyntaxKind.ParenthesizedExpression) || parentExpression.IsKind(SyntaxKind.ParenthesizedExpression)) { return true; } if (expression is StackAllocArrayCreationExpressionSyntax || expression is ImplicitStackAllocArrayCreationExpressionSyntax) { // var span = (stackalloc byte[8]); // https://github.com/dotnet/roslyn/issues/44629 // The code semantics changes if the parenthesis removed. // With parenthesis: variable span is of type `Span<byte>`. // Without parenthesis: variable span is of type `byte*` which can only be used in unsafe context. return false; } // (throw ...) -> throw ... if (expression.IsKind(SyntaxKind.ThrowExpression)) return true; // (x); -> x; if (node.IsParentKind(SyntaxKind.ExpressionStatement)) { return true; } // => (x) -> => x if (node.IsParentKind(SyntaxKind.ArrowExpressionClause)) { return true; } // checked((x)) -> checked(x) if (node.IsParentKind(SyntaxKind.CheckedExpression) || node.IsParentKind(SyntaxKind.UncheckedExpression)) { return true; } // ((x, y)) -> (x, y) if (expression.IsKind(SyntaxKind.TupleExpression)) { return true; } // int Prop => (x); -> int Prop => x; if (node.Parent is ArrowExpressionClauseSyntax arrowExpressionClause && arrowExpressionClause.Expression == node) { return true; } // Easy statement-level cases: // var y = (x); -> var y = x; // var (y, z) = (x); -> var (y, z) = x; // if ((x)) -> if (x) // return (x); -> return x; // yield return (x); -> yield return x; // throw (x); -> throw x; // switch ((x)) -> switch (x) // while ((x)) -> while (x) // do { } while ((x)) -> do { } while (x) // for(;(x);) -> for(;x;) // foreach (var y in (x)) -> foreach (var y in x) // lock ((x)) -> lock (x) // using ((x)) -> using (x) // catch when ((x)) -> catch when (x) if ((node.IsParentKind(SyntaxKind.EqualsValueClause, out EqualsValueClauseSyntax equalsValue) && equalsValue.Value == node) || (node.IsParentKind(SyntaxKind.IfStatement, out IfStatementSyntax ifStatement) && ifStatement.Condition == node) || (node.IsParentKind(SyntaxKind.ReturnStatement, out ReturnStatementSyntax returnStatement) && returnStatement.Expression == node) || (node.IsParentKind(SyntaxKind.YieldReturnStatement, out YieldStatementSyntax yieldStatement) && yieldStatement.Expression == node) || (node.IsParentKind(SyntaxKind.ThrowStatement, out ThrowStatementSyntax throwStatement) && throwStatement.Expression == node) || (node.IsParentKind(SyntaxKind.SwitchStatement, out SwitchStatementSyntax switchStatement) && switchStatement.Expression == node) || (node.IsParentKind(SyntaxKind.WhileStatement, out WhileStatementSyntax whileStatement) && whileStatement.Condition == node) || (node.IsParentKind(SyntaxKind.DoStatement, out DoStatementSyntax doStatement) && doStatement.Condition == node) || (node.IsParentKind(SyntaxKind.ForStatement, out ForStatementSyntax forStatement) && forStatement.Condition == node) || (node.IsParentKind(SyntaxKind.ForEachStatement, SyntaxKind.ForEachVariableStatement) && ((CommonForEachStatementSyntax)node.Parent).Expression == node) || (node.IsParentKind(SyntaxKind.LockStatement, out LockStatementSyntax lockStatement) && lockStatement.Expression == node) || (node.IsParentKind(SyntaxKind.UsingStatement, out UsingStatementSyntax usingStatement) && usingStatement.Expression == node) || (node.IsParentKind(SyntaxKind.CatchFilterClause, out CatchFilterClauseSyntax catchFilter) && catchFilter.FilterExpression == node)) { return true; } // Handle expression-level ambiguities if (RemovalMayIntroduceCastAmbiguity(node) || RemovalMayIntroduceCommaListAmbiguity(node) || RemovalMayIntroduceInterpolationAmbiguity(node) || RemovalWouldChangeConstantReferenceToTypeReference(node, expression, semanticModel, cancellationToken)) { return false; } // Cases: // (C)(this) -> (C)this if (node.IsParentKind(SyntaxKind.CastExpression) && expression.IsKind(SyntaxKind.ThisExpression)) { return true; } // Cases: // y((x)) -> y(x) if (node.IsParentKind(SyntaxKind.Argument, out ArgumentSyntax argument) && argument.Expression == node) { return true; } // Cases: // $"{(x)}" -> $"{x}" if (node.IsParentKind(SyntaxKind.Interpolation)) { return true; } // Cases: // ($"{x}") -> $"{x}" if (expression.IsKind(SyntaxKind.InterpolatedStringExpression)) { return true; } // Cases: // {(x)} -> {x} if (node.Parent is InitializerExpressionSyntax) { // Assignment expressions are not allowed in initializers if (expression.IsAnyAssignExpression()) { return false; } return true; } // Cases: // new {(x)} -> {x} // new { a = (x)} -> { a = x } // new { a = (x = c)} -> { a = x = c } if (node.Parent is AnonymousObjectMemberDeclaratorSyntax anonymousDeclarator) { // Assignment expressions are not allowed unless member is named if (anonymousDeclarator.NameEquals == null && expression.IsAnyAssignExpression()) { return false; } return true; } // Cases: // where (x + 1 > 14) -> where x + 1 > 14 if (node.Parent is QueryClauseSyntax) { return true; } // Cases: // (x) -> x // (x.y) -> x.y if (IsSimpleOrDottedName(expression)) { return true; } // Cases: // ('') -> '' // ("") -> "" // (false) -> false // (true) -> true // (null) -> null // (default) -> default; // (1) -> 1 if (expression.IsAnyLiteralExpression()) { return true; } // (this) -> this if (expression.IsKind(SyntaxKind.ThisExpression)) { return true; } // x ?? (throw ...) -> x ?? throw ... if (expression.IsKind(SyntaxKind.ThrowExpression) && node.IsParentKind(SyntaxKind.CoalesceExpression, out BinaryExpressionSyntax binary) && binary.Right == node) { return true; } // case (x): -> case x: if (node.IsParentKind(SyntaxKind.CaseSwitchLabel)) { return true; } // case (x) when y: -> case x when y: if (node.IsParentKind(SyntaxKind.ConstantPattern) && node.Parent.IsParentKind(SyntaxKind.CasePatternSwitchLabel)) { return true; } // case x when (y): -> case x when y: if (node.IsParentKind(SyntaxKind.WhenClause)) { return true; } // #if (x) -> #if x if (node.Parent is DirectiveTriviaSyntax) { return true; } // Switch expression arm // x => (y) if (node.Parent is SwitchExpressionArmSyntax arm && arm.Expression == node) { return true; } // If we have: (X)(++x) or (X)(--x), we don't want to remove the parens. doing so can // make the ++/-- now associate with the previous part of the cast expression. if (parentExpression.IsKind(SyntaxKind.CastExpression)) { if (expression.IsKind(SyntaxKind.PreIncrementExpression) || expression.IsKind(SyntaxKind.PreDecrementExpression)) { return false; } } // (condition ? ref a : ref b ) = SomeValue, parenthesis can't be removed for when conditional expression appears at left // This syntax is only allowed since C# 7.2 if (expression.IsKind(SyntaxKind.ConditionalExpression) && node.IsLeftSideOfAnyAssignExpression()) { return false; } // Don't change (x?.Count)... to x?.Count... // // It very much changes the semantics to have code that always executed (outside the // parenthesized expression) now only conditionally run depending on if 'x' is null or // not. if (expression.IsKind(SyntaxKind.ConditionalAccessExpression)) { return false; } // Operator precedence cases: // - If the parent is not an expression, do not remove parentheses // - Otherwise, parentheses may be removed if doing so does not change operator associations. return parentExpression != null && !RemovalChangesAssociation(node, parentExpression, semanticModel); } private static bool RemovalWouldChangeConstantReferenceToTypeReference( ParenthesizedExpressionSyntax node, ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { // With cases like: `if (x is (Y))` then we cannot remove the parens if it would make Y now bind to a type // instead of a constant. if (node.Parent is not ConstantPatternSyntax { Parent: IsPatternExpressionSyntax }) return false; var exprSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).Symbol; if (exprSymbol is not IFieldSymbol { IsConst: true } field) return false; // See if interpreting the same expression as a type in this location binds. var potentialType = semanticModel.GetSpeculativeTypeInfo(expression.SpanStart, expression, SpeculativeBindingOption.BindAsTypeOrNamespace).Type; return potentialType is not (null or IErrorTypeSymbol); } private static readonly ObjectPool<Stack<SyntaxNode>> s_nodeStackPool = SharedPools.Default<Stack<SyntaxNode>>(); private static bool RemovalMayIntroduceInterpolationAmbiguity(ParenthesizedExpressionSyntax node) { // First, find the parenting interpolation. If we find a parenthesize expression first, // we can bail out early. InterpolationSyntax interpolation = null; foreach (var ancestor in node.Parent.AncestorsAndSelf()) { if (ancestor.IsKind(SyntaxKind.ParenthesizedExpression)) { return false; } if (ancestor.IsKind(SyntaxKind.Interpolation, out interpolation)) { break; } } if (interpolation == null) { return false; } // In order determine whether removing this parenthesized expression will introduce a // parsing ambiguity, we must dig into the child tokens and nodes to determine whether // they include any : or :: tokens. If they do, we can't remove the parentheses because // the parser would assume that the first : would begin the format clause of the interpolation. var stack = s_nodeStackPool.AllocateAndClear(); try { stack.Push(node.Expression); while (stack.Count > 0) { var expression = stack.Pop(); foreach (var nodeOrToken in expression.ChildNodesAndTokens()) { // Note: There's no need drill into other parenthesized expressions, since any colons in them would be unambiguous. if (nodeOrToken.IsNode && !nodeOrToken.IsKind(SyntaxKind.ParenthesizedExpression)) { stack.Push(nodeOrToken.AsNode()); } else if (nodeOrToken.IsToken) { if (nodeOrToken.IsKind(SyntaxKind.ColonToken) || nodeOrToken.IsKind(SyntaxKind.ColonColonToken)) { return true; } } } } } finally { s_nodeStackPool.ClearAndFree(stack); } return false; } private static bool RemovalChangesAssociation( ParenthesizedExpressionSyntax node, ExpressionSyntax parentExpression, SemanticModel semanticModel) { var expression = node.Expression; var precedence = expression.GetOperatorPrecedence(); var parentPrecedence = parentExpression.GetOperatorPrecedence(); if (precedence == OperatorPrecedence.None || parentPrecedence == OperatorPrecedence.None) { // Be conservative if the expression or its parent has no precedence. return true; } if (precedence > parentPrecedence) { // Association never changes if the expression's precedence is higher than its parent. return false; } else if (precedence < parentPrecedence) { // Association always changes if the expression's precedence is lower that its parent. return true; } else if (precedence == parentPrecedence) { // If the expression's precedence is the same as its parent, and both are binary expressions, // check for associativity and commutability. if (!(expression is BinaryExpressionSyntax || expression is AssignmentExpressionSyntax)) { // If the expression is not a binary expression, association never changes. return false; } if (parentExpression is BinaryExpressionSyntax parentBinaryExpression) { // If both the expression and its parent are binary expressions and their kinds // are the same, and the parenthesized expression is on hte right and the // operation is associative, it can sometimes be safe to remove these parens. // // i.e. if you have "a && (b && c)" it can be converted to "a && b && c" // as that new interpretation "(a && b) && c" operates the exact same way at // runtime. // // Specifically: // 1) the operands are still executed in the same order: a, b, then c. // So even if they have side effects, it will not matter. // 2) the same shortcircuiting happens. // 3) for logical operators the result will always be the same (there are // additional conditions that are checked for non-logical operators). if (IsAssociative(parentBinaryExpression.Kind()) && node.Expression.Kind() == parentBinaryExpression.Kind() && parentBinaryExpression.Right == node) { return !node.IsSafeToChangeAssociativity( node.Expression, parentBinaryExpression.Left, parentBinaryExpression.Right, semanticModel); } // Null-coalescing is right associative; removing parens from the LHS changes the association. if (parentExpression.IsKind(SyntaxKind.CoalesceExpression)) { return parentBinaryExpression.Left == node; } // All other binary operators are left associative; removing parens from the RHS changes the association. return parentBinaryExpression.Right == node; } if (parentExpression is AssignmentExpressionSyntax parentAssignmentExpression) { // Assignment expressions are right associative; removing parens from the LHS changes the association. return parentAssignmentExpression.Left == node; } // If the parent is not a binary expression, association never changes. return false; } throw ExceptionUtilities.Unreachable; } private static bool IsAssociative(SyntaxKind kind) { switch (kind) { case SyntaxKind.AddExpression: case SyntaxKind.MultiplyExpression: case SyntaxKind.BitwiseOrExpression: case SyntaxKind.ExclusiveOrExpression: case SyntaxKind.LogicalOrExpression: case SyntaxKind.BitwiseAndExpression: case SyntaxKind.LogicalAndExpression: return true; } return false; } private static bool RemovalMayIntroduceCastAmbiguity(ParenthesizedExpressionSyntax node) { // Be careful not to break the special case around (x)(-y) // as defined in section 7.7.6 of the C# language specification. // // cases we can't remove the parens for are: // // (x)(+y) // (x)(-y) // (x)(&y) // unsafe code // (x)(*y) // unsafe code // // Note: we can remove the parens if the (x) part is unambiguously a type. // i.e. if it something like: // // (int)(...) // (x[])(...) // (X*)(...) // (X?)(...) // (global::X)(...) if (node.IsParentKind(SyntaxKind.CastExpression, out CastExpressionSyntax castExpression)) { if (castExpression.Type.IsKind( SyntaxKind.PredefinedType, SyntaxKind.ArrayType, SyntaxKind.PointerType, SyntaxKind.NullableType)) { return false; } if (castExpression.Type is NameSyntax name && StartsWithAlias(name)) { return false; } var expression = node.Expression; if (expression.IsKind( SyntaxKind.UnaryMinusExpression, SyntaxKind.UnaryPlusExpression, SyntaxKind.PointerIndirectionExpression, SyntaxKind.AddressOfExpression)) { return true; } } return false; } private static bool StartsWithAlias(NameSyntax name) { if (name.IsKind(SyntaxKind.AliasQualifiedName)) { return true; } if (name is QualifiedNameSyntax qualifiedName) { return StartsWithAlias(qualifiedName.Left); } return false; } private static bool RemovalMayIntroduceCommaListAmbiguity(ParenthesizedExpressionSyntax node) { if (IsSimpleOrDottedName(node.Expression)) { // We can't remove parentheses from an identifier name in the following cases: // F((x) < x, x > (1 + 2)) // F(x < (x), x > (1 + 2)) // F(x < x, (x) > (1 + 2)) // {(x) < x, x > (1 + 2)} // {x < (x), x > (1 + 2)} // {x < x, (x) > (1 + 2)} if (node.Parent is BinaryExpressionSyntax binaryExpression && binaryExpression.IsKind(SyntaxKind.LessThanExpression, SyntaxKind.GreaterThanExpression) && (binaryExpression.IsParentKind(SyntaxKind.Argument) || binaryExpression.Parent is InitializerExpressionSyntax)) { if (binaryExpression.IsKind(SyntaxKind.LessThanExpression)) { if ((binaryExpression.Left == node && IsSimpleOrDottedName(binaryExpression.Right)) || (binaryExpression.Right == node && IsSimpleOrDottedName(binaryExpression.Left))) { if (IsNextExpressionPotentiallyAmbiguous(binaryExpression)) { return true; } } return false; } else if (binaryExpression.IsKind(SyntaxKind.GreaterThanExpression)) { if (binaryExpression.Left == node && binaryExpression.Right.IsKind(SyntaxKind.ParenthesizedExpression, SyntaxKind.CastExpression)) { if (IsPreviousExpressionPotentiallyAmbiguous(binaryExpression)) { return true; } } return false; } } } else if (node.Expression.IsKind(SyntaxKind.LessThanExpression)) { // We can't remove parentheses from a less-than expression in the following cases: // F((x < x), x > (1 + 2)) // {(x < x), x > (1 + 2)} return IsNextExpressionPotentiallyAmbiguous(node); } else if (node.Expression.IsKind(SyntaxKind.GreaterThanExpression)) { // We can't remove parentheses from a greater-than expression in the following cases: // F(x < x, (x > (1 + 2))) // {x < x, (x > (1 + 2))} return IsPreviousExpressionPotentiallyAmbiguous(node); } return false; } private static bool IsPreviousExpressionPotentiallyAmbiguous(ExpressionSyntax node) { ExpressionSyntax previousExpression = null; if (node.IsParentKind(SyntaxKind.Argument, out ArgumentSyntax argument)) { if (argument.Parent is ArgumentListSyntax argumentList) { var argumentIndex = argumentList.Arguments.IndexOf(argument); if (argumentIndex > 0) { previousExpression = argumentList.Arguments[argumentIndex - 1].Expression; } } } else if (node.Parent is InitializerExpressionSyntax initializer) { var expressionIndex = initializer.Expressions.IndexOf(node); if (expressionIndex > 0) { previousExpression = initializer.Expressions[expressionIndex - 1]; } } if (previousExpression == null || !previousExpression.IsKind(SyntaxKind.LessThanExpression, out BinaryExpressionSyntax lessThanExpression)) { return false; } return (IsSimpleOrDottedName(lessThanExpression.Left) || lessThanExpression.Left.IsKind(SyntaxKind.CastExpression)) && IsSimpleOrDottedName(lessThanExpression.Right); } private static bool IsNextExpressionPotentiallyAmbiguous(ExpressionSyntax node) { ExpressionSyntax nextExpression = null; if (node.IsParentKind(SyntaxKind.Argument, out ArgumentSyntax argument)) { if (argument.Parent is ArgumentListSyntax argumentList) { var argumentIndex = argumentList.Arguments.IndexOf(argument); if (argumentIndex >= 0 && argumentIndex < argumentList.Arguments.Count - 1) { nextExpression = argumentList.Arguments[argumentIndex + 1].Expression; } } } else if (node.Parent is InitializerExpressionSyntax initializer) { var expressionIndex = initializer.Expressions.IndexOf(node); if (expressionIndex >= 0 && expressionIndex < initializer.Expressions.Count - 1) { nextExpression = initializer.Expressions[expressionIndex + 1]; } } if (nextExpression == null || !nextExpression.IsKind(SyntaxKind.GreaterThanExpression, out BinaryExpressionSyntax greaterThanExpression)) { return false; } return IsSimpleOrDottedName(greaterThanExpression.Left) && (greaterThanExpression.Right.IsKind(SyntaxKind.ParenthesizedExpression) || greaterThanExpression.Right.IsKind(SyntaxKind.CastExpression)); } private static bool IsSimpleOrDottedName(ExpressionSyntax expression) => expression.Kind() is SyntaxKind.IdentifierName or SyntaxKind.QualifiedName or SyntaxKind.SimpleMemberAccessExpression; public static bool CanRemoveParentheses(this ParenthesizedPatternSyntax node) { if (node.OpenParenToken.IsMissing || node.CloseParenToken.IsMissing) { // int x = (3; return false; } var pattern = node.Pattern; // We wrap a parenthesized pattern and we're parenthesized. We can remove our parens. if (pattern is ParenthesizedPatternSyntax) return true; // We're parenthesized discard pattern. We cannot remove parens. // x is (_) if (pattern is DiscardPatternSyntax && node.Parent is IsPatternExpressionSyntax) return false; // (not ...) -> not ... // // this is safe because unary patterns have the highest precedence, so even if you had: // (not ...) or (not ...) // // you can safely convert to `not ... or not ...` var patternPrecedence = pattern.GetOperatorPrecedence(); if (patternPrecedence == OperatorPrecedence.Primary || patternPrecedence == OperatorPrecedence.Unary) return true; // We're parenthesized and are inside a parenthesized pattern. We can remove our parens. // ((x)) -> (x) if (node.Parent is ParenthesizedPatternSyntax) return true; // x is (...) -> x is ... if (node.Parent is IsPatternExpressionSyntax) return true; // (x or y) => ... -> x or y => ... if (node.Parent is SwitchExpressionArmSyntax) return true; // X: (y or z) -> X: y or z if (node.Parent is SubpatternSyntax) return true; // case (x or y): -> case x or y: if (node.Parent is CasePatternSwitchLabelSyntax) return true; // Operator precedence cases: // - If the parent is not an expression, do not remove parentheses // - Otherwise, parentheses may be removed if doing so does not change operator associations. return node.Parent is PatternSyntax patternParent && !RemovalChangesAssociation(node, patternParent); } private static bool RemovalChangesAssociation( ParenthesizedPatternSyntax node, PatternSyntax parentPattern) { var pattern = node.Pattern; var precedence = pattern.GetOperatorPrecedence(); var parentPrecedence = parentPattern.GetOperatorPrecedence(); if (precedence == OperatorPrecedence.None || parentPrecedence == OperatorPrecedence.None) { // Be conservative if the expression or its parent has no precedence. return true; } // Association always changes if the expression's precedence is lower that its parent. return precedence < parentPrecedence; } public static OperatorPrecedence GetOperatorPrecedence(this PatternSyntax pattern) { switch (pattern) { case ConstantPatternSyntax _: case DiscardPatternSyntax _: case DeclarationPatternSyntax _: case RecursivePatternSyntax _: case TypePatternSyntax _: case VarPatternSyntax _: return OperatorPrecedence.Primary; case UnaryPatternSyntax _: case RelationalPatternSyntax _: return OperatorPrecedence.Unary; case BinaryPatternSyntax binaryPattern: if (binaryPattern.IsKind(SyntaxKind.AndPattern)) return OperatorPrecedence.ConditionalAnd; if (binaryPattern.IsKind(SyntaxKind.OrPattern)) return OperatorPrecedence.ConditionalOr; break; } Debug.Fail("Unhandled pattern type"); return OperatorPrecedence.None; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class ParenthesizedExpressionSyntaxExtensions { public static bool CanRemoveParentheses( this ParenthesizedExpressionSyntax node, SemanticModel semanticModel, CancellationToken cancellationToken) { if (node.OpenParenToken.IsMissing || node.CloseParenToken.IsMissing) { // int x = (3; return false; } var expression = node.Expression; // The 'direct' expression that contains this parenthesized node. Note: in the case // of code like: ```x is (y)``` there is an intermediary 'no-syntax' 'ConstantPattern' // node between the 'is-pattern' node and the parenthesized expression. So we manually // jump past that as, for all intents and purposes, we want to consider the 'is' expression // as the parent expression of the (y) expression. var parentExpression = node.IsParentKind(SyntaxKind.ConstantPattern) ? node.Parent.Parent as ExpressionSyntax : node.Parent as ExpressionSyntax; // Have to be careful if we would remove parens and cause a + and a + to become a ++. // (same with - as well). var tokenBeforeParen = node.GetFirstToken().GetPreviousToken(); var tokenAfterParen = node.Expression.GetFirstToken(); var previousChar = tokenBeforeParen.Text.LastOrDefault(); var nextChar = tokenAfterParen.Text.FirstOrDefault(); if ((previousChar == '+' && nextChar == '+') || (previousChar == '-' && nextChar == '-')) { return false; } // Simplest cases: // ((x)) -> (x) if (expression.IsKind(SyntaxKind.ParenthesizedExpression) || parentExpression.IsKind(SyntaxKind.ParenthesizedExpression)) { return true; } if (expression is StackAllocArrayCreationExpressionSyntax || expression is ImplicitStackAllocArrayCreationExpressionSyntax) { // var span = (stackalloc byte[8]); // https://github.com/dotnet/roslyn/issues/44629 // The code semantics changes if the parenthesis removed. // With parenthesis: variable span is of type `Span<byte>`. // Without parenthesis: variable span is of type `byte*` which can only be used in unsafe context. return false; } // (throw ...) -> throw ... if (expression.IsKind(SyntaxKind.ThrowExpression)) return true; // (x); -> x; if (node.IsParentKind(SyntaxKind.ExpressionStatement)) { return true; } // => (x) -> => x if (node.IsParentKind(SyntaxKind.ArrowExpressionClause)) { return true; } // checked((x)) -> checked(x) if (node.IsParentKind(SyntaxKind.CheckedExpression) || node.IsParentKind(SyntaxKind.UncheckedExpression)) { return true; } // ((x, y)) -> (x, y) if (expression.IsKind(SyntaxKind.TupleExpression)) { return true; } // int Prop => (x); -> int Prop => x; if (node.Parent is ArrowExpressionClauseSyntax arrowExpressionClause && arrowExpressionClause.Expression == node) { return true; } // Easy statement-level cases: // var y = (x); -> var y = x; // var (y, z) = (x); -> var (y, z) = x; // if ((x)) -> if (x) // return (x); -> return x; // yield return (x); -> yield return x; // throw (x); -> throw x; // switch ((x)) -> switch (x) // while ((x)) -> while (x) // do { } while ((x)) -> do { } while (x) // for(;(x);) -> for(;x;) // foreach (var y in (x)) -> foreach (var y in x) // lock ((x)) -> lock (x) // using ((x)) -> using (x) // catch when ((x)) -> catch when (x) if ((node.IsParentKind(SyntaxKind.EqualsValueClause, out EqualsValueClauseSyntax equalsValue) && equalsValue.Value == node) || (node.IsParentKind(SyntaxKind.IfStatement, out IfStatementSyntax ifStatement) && ifStatement.Condition == node) || (node.IsParentKind(SyntaxKind.ReturnStatement, out ReturnStatementSyntax returnStatement) && returnStatement.Expression == node) || (node.IsParentKind(SyntaxKind.YieldReturnStatement, out YieldStatementSyntax yieldStatement) && yieldStatement.Expression == node) || (node.IsParentKind(SyntaxKind.ThrowStatement, out ThrowStatementSyntax throwStatement) && throwStatement.Expression == node) || (node.IsParentKind(SyntaxKind.SwitchStatement, out SwitchStatementSyntax switchStatement) && switchStatement.Expression == node) || (node.IsParentKind(SyntaxKind.WhileStatement, out WhileStatementSyntax whileStatement) && whileStatement.Condition == node) || (node.IsParentKind(SyntaxKind.DoStatement, out DoStatementSyntax doStatement) && doStatement.Condition == node) || (node.IsParentKind(SyntaxKind.ForStatement, out ForStatementSyntax forStatement) && forStatement.Condition == node) || (node.IsParentKind(SyntaxKind.ForEachStatement, SyntaxKind.ForEachVariableStatement) && ((CommonForEachStatementSyntax)node.Parent).Expression == node) || (node.IsParentKind(SyntaxKind.LockStatement, out LockStatementSyntax lockStatement) && lockStatement.Expression == node) || (node.IsParentKind(SyntaxKind.UsingStatement, out UsingStatementSyntax usingStatement) && usingStatement.Expression == node) || (node.IsParentKind(SyntaxKind.CatchFilterClause, out CatchFilterClauseSyntax catchFilter) && catchFilter.FilterExpression == node)) { return true; } // Handle expression-level ambiguities if (RemovalMayIntroduceCastAmbiguity(node) || RemovalMayIntroduceCommaListAmbiguity(node) || RemovalMayIntroduceInterpolationAmbiguity(node) || RemovalWouldChangeConstantReferenceToTypeReference(node, expression, semanticModel, cancellationToken)) { return false; } // Cases: // (C)(this) -> (C)this if (node.IsParentKind(SyntaxKind.CastExpression) && expression.IsKind(SyntaxKind.ThisExpression)) { return true; } // Cases: // y((x)) -> y(x) if (node.IsParentKind(SyntaxKind.Argument, out ArgumentSyntax argument) && argument.Expression == node) { return true; } // Cases: // $"{(x)}" -> $"{x}" if (node.IsParentKind(SyntaxKind.Interpolation)) { return true; } // Cases: // ($"{x}") -> $"{x}" if (expression.IsKind(SyntaxKind.InterpolatedStringExpression)) { return true; } // Cases: // {(x)} -> {x} if (node.Parent is InitializerExpressionSyntax) { // Assignment expressions are not allowed in initializers if (expression.IsAnyAssignExpression()) { return false; } return true; } // Cases: // new {(x)} -> {x} // new { a = (x)} -> { a = x } // new { a = (x = c)} -> { a = x = c } if (node.Parent is AnonymousObjectMemberDeclaratorSyntax anonymousDeclarator) { // Assignment expressions are not allowed unless member is named if (anonymousDeclarator.NameEquals == null && expression.IsAnyAssignExpression()) { return false; } return true; } // Cases: // where (x + 1 > 14) -> where x + 1 > 14 if (node.Parent is QueryClauseSyntax) { return true; } // Cases: // (x) -> x // (x.y) -> x.y if (IsSimpleOrDottedName(expression)) { return true; } // Cases: // ('') -> '' // ("") -> "" // (false) -> false // (true) -> true // (null) -> null // (default) -> default; // (1) -> 1 if (expression.IsAnyLiteralExpression()) { return true; } // (this) -> this if (expression.IsKind(SyntaxKind.ThisExpression)) { return true; } // x ?? (throw ...) -> x ?? throw ... if (expression.IsKind(SyntaxKind.ThrowExpression) && node.IsParentKind(SyntaxKind.CoalesceExpression, out BinaryExpressionSyntax binary) && binary.Right == node) { return true; } // case (x): -> case x: if (node.IsParentKind(SyntaxKind.CaseSwitchLabel)) { return true; } // case (x) when y: -> case x when y: if (node.IsParentKind(SyntaxKind.ConstantPattern) && node.Parent.IsParentKind(SyntaxKind.CasePatternSwitchLabel)) { return true; } // case x when (y): -> case x when y: if (node.IsParentKind(SyntaxKind.WhenClause)) { return true; } // #if (x) -> #if x if (node.Parent is DirectiveTriviaSyntax) { return true; } // Switch expression arm // x => (y) if (node.Parent is SwitchExpressionArmSyntax arm && arm.Expression == node) { return true; } // If we have: (X)(++x) or (X)(--x), we don't want to remove the parens. doing so can // make the ++/-- now associate with the previous part of the cast expression. if (parentExpression.IsKind(SyntaxKind.CastExpression)) { if (expression.IsKind(SyntaxKind.PreIncrementExpression) || expression.IsKind(SyntaxKind.PreDecrementExpression)) { return false; } } // (condition ? ref a : ref b ) = SomeValue, parenthesis can't be removed for when conditional expression appears at left // This syntax is only allowed since C# 7.2 if (expression.IsKind(SyntaxKind.ConditionalExpression) && node.IsLeftSideOfAnyAssignExpression()) { return false; } // Don't change (x?.Count)... to x?.Count... // // It very much changes the semantics to have code that always executed (outside the // parenthesized expression) now only conditionally run depending on if 'x' is null or // not. if (expression.IsKind(SyntaxKind.ConditionalAccessExpression)) { return false; } // Operator precedence cases: // - If the parent is not an expression, do not remove parentheses // - Otherwise, parentheses may be removed if doing so does not change operator associations. return parentExpression != null && !RemovalChangesAssociation(node, parentExpression, semanticModel); } private static bool RemovalWouldChangeConstantReferenceToTypeReference( ParenthesizedExpressionSyntax node, ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken) { // With cases like: `if (x is (Y))` then we cannot remove the parens if it would make Y now bind to a type // instead of a constant. if (node.Parent is not ConstantPatternSyntax { Parent: IsPatternExpressionSyntax }) return false; var exprSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).Symbol; if (exprSymbol is not IFieldSymbol { IsConst: true } field) return false; // See if interpreting the same expression as a type in this location binds. var potentialType = semanticModel.GetSpeculativeTypeInfo(expression.SpanStart, expression, SpeculativeBindingOption.BindAsTypeOrNamespace).Type; return potentialType is not (null or IErrorTypeSymbol); } private static readonly ObjectPool<Stack<SyntaxNode>> s_nodeStackPool = SharedPools.Default<Stack<SyntaxNode>>(); private static bool RemovalMayIntroduceInterpolationAmbiguity(ParenthesizedExpressionSyntax node) { // First, find the parenting interpolation. If we find a parenthesize expression first, // we can bail out early. InterpolationSyntax interpolation = null; foreach (var ancestor in node.Parent.AncestorsAndSelf()) { if (ancestor.IsKind(SyntaxKind.ParenthesizedExpression)) { return false; } if (ancestor.IsKind(SyntaxKind.Interpolation, out interpolation)) { break; } } if (interpolation == null) { return false; } // In order determine whether removing this parenthesized expression will introduce a // parsing ambiguity, we must dig into the child tokens and nodes to determine whether // they include any : or :: tokens. If they do, we can't remove the parentheses because // the parser would assume that the first : would begin the format clause of the interpolation. var stack = s_nodeStackPool.AllocateAndClear(); try { stack.Push(node.Expression); while (stack.Count > 0) { var expression = stack.Pop(); foreach (var nodeOrToken in expression.ChildNodesAndTokens()) { // Note: There's no need drill into other parenthesized expressions, since any colons in them would be unambiguous. if (nodeOrToken.IsNode && !nodeOrToken.IsKind(SyntaxKind.ParenthesizedExpression)) { stack.Push(nodeOrToken.AsNode()); } else if (nodeOrToken.IsToken) { if (nodeOrToken.IsKind(SyntaxKind.ColonToken) || nodeOrToken.IsKind(SyntaxKind.ColonColonToken)) { return true; } } } } } finally { s_nodeStackPool.ClearAndFree(stack); } return false; } private static bool RemovalChangesAssociation( ParenthesizedExpressionSyntax node, ExpressionSyntax parentExpression, SemanticModel semanticModel) { var expression = node.Expression; var precedence = expression.GetOperatorPrecedence(); var parentPrecedence = parentExpression.GetOperatorPrecedence(); if (precedence == OperatorPrecedence.None || parentPrecedence == OperatorPrecedence.None) { // Be conservative if the expression or its parent has no precedence. return true; } if (precedence > parentPrecedence) { // Association never changes if the expression's precedence is higher than its parent. return false; } else if (precedence < parentPrecedence) { // Association always changes if the expression's precedence is lower that its parent. return true; } else if (precedence == parentPrecedence) { // If the expression's precedence is the same as its parent, and both are binary expressions, // check for associativity and commutability. if (!(expression is BinaryExpressionSyntax || expression is AssignmentExpressionSyntax)) { // If the expression is not a binary expression, association never changes. return false; } if (parentExpression is BinaryExpressionSyntax parentBinaryExpression) { // If both the expression and its parent are binary expressions and their kinds // are the same, and the parenthesized expression is on hte right and the // operation is associative, it can sometimes be safe to remove these parens. // // i.e. if you have "a && (b && c)" it can be converted to "a && b && c" // as that new interpretation "(a && b) && c" operates the exact same way at // runtime. // // Specifically: // 1) the operands are still executed in the same order: a, b, then c. // So even if they have side effects, it will not matter. // 2) the same shortcircuiting happens. // 3) for logical operators the result will always be the same (there are // additional conditions that are checked for non-logical operators). if (IsAssociative(parentBinaryExpression.Kind()) && node.Expression.Kind() == parentBinaryExpression.Kind() && parentBinaryExpression.Right == node) { return !node.IsSafeToChangeAssociativity( node.Expression, parentBinaryExpression.Left, parentBinaryExpression.Right, semanticModel); } // Null-coalescing is right associative; removing parens from the LHS changes the association. if (parentExpression.IsKind(SyntaxKind.CoalesceExpression)) { return parentBinaryExpression.Left == node; } // All other binary operators are left associative; removing parens from the RHS changes the association. return parentBinaryExpression.Right == node; } if (parentExpression is AssignmentExpressionSyntax parentAssignmentExpression) { // Assignment expressions are right associative; removing parens from the LHS changes the association. return parentAssignmentExpression.Left == node; } // If the parent is not a binary expression, association never changes. return false; } throw ExceptionUtilities.Unreachable; } private static bool IsAssociative(SyntaxKind kind) { switch (kind) { case SyntaxKind.AddExpression: case SyntaxKind.MultiplyExpression: case SyntaxKind.BitwiseOrExpression: case SyntaxKind.ExclusiveOrExpression: case SyntaxKind.LogicalOrExpression: case SyntaxKind.BitwiseAndExpression: case SyntaxKind.LogicalAndExpression: return true; } return false; } private static bool RemovalMayIntroduceCastAmbiguity(ParenthesizedExpressionSyntax node) { // Be careful not to break the special case around (x)(-y) // as defined in section 7.7.6 of the C# language specification. // // cases we can't remove the parens for are: // // (x)(+y) // (x)(-y) // (x)(&y) // unsafe code // (x)(*y) // unsafe code // // Note: we can remove the parens if the (x) part is unambiguously a type. // i.e. if it something like: // // (int)(...) // (x[])(...) // (X*)(...) // (X?)(...) // (global::X)(...) if (node.IsParentKind(SyntaxKind.CastExpression, out CastExpressionSyntax castExpression)) { if (castExpression.Type.IsKind( SyntaxKind.PredefinedType, SyntaxKind.ArrayType, SyntaxKind.PointerType, SyntaxKind.NullableType)) { return false; } if (castExpression.Type is NameSyntax name && StartsWithAlias(name)) { return false; } var expression = node.Expression; if (expression.IsKind( SyntaxKind.UnaryMinusExpression, SyntaxKind.UnaryPlusExpression, SyntaxKind.PointerIndirectionExpression, SyntaxKind.AddressOfExpression)) { return true; } } return false; } private static bool StartsWithAlias(NameSyntax name) { if (name.IsKind(SyntaxKind.AliasQualifiedName)) { return true; } if (name is QualifiedNameSyntax qualifiedName) { return StartsWithAlias(qualifiedName.Left); } return false; } private static bool RemovalMayIntroduceCommaListAmbiguity(ParenthesizedExpressionSyntax node) { if (IsSimpleOrDottedName(node.Expression)) { // We can't remove parentheses from an identifier name in the following cases: // F((x) < x, x > (1 + 2)) // F(x < (x), x > (1 + 2)) // F(x < x, (x) > (1 + 2)) // {(x) < x, x > (1 + 2)} // {x < (x), x > (1 + 2)} // {x < x, (x) > (1 + 2)} if (node.Parent is BinaryExpressionSyntax binaryExpression && binaryExpression.IsKind(SyntaxKind.LessThanExpression, SyntaxKind.GreaterThanExpression) && (binaryExpression.IsParentKind(SyntaxKind.Argument) || binaryExpression.Parent is InitializerExpressionSyntax)) { if (binaryExpression.IsKind(SyntaxKind.LessThanExpression)) { if ((binaryExpression.Left == node && IsSimpleOrDottedName(binaryExpression.Right)) || (binaryExpression.Right == node && IsSimpleOrDottedName(binaryExpression.Left))) { if (IsNextExpressionPotentiallyAmbiguous(binaryExpression)) { return true; } } return false; } else if (binaryExpression.IsKind(SyntaxKind.GreaterThanExpression)) { if (binaryExpression.Left == node && binaryExpression.Right.IsKind(SyntaxKind.ParenthesizedExpression, SyntaxKind.CastExpression)) { if (IsPreviousExpressionPotentiallyAmbiguous(binaryExpression)) { return true; } } return false; } } } else if (node.Expression.IsKind(SyntaxKind.LessThanExpression)) { // We can't remove parentheses from a less-than expression in the following cases: // F((x < x), x > (1 + 2)) // {(x < x), x > (1 + 2)} return IsNextExpressionPotentiallyAmbiguous(node); } else if (node.Expression.IsKind(SyntaxKind.GreaterThanExpression)) { // We can't remove parentheses from a greater-than expression in the following cases: // F(x < x, (x > (1 + 2))) // {x < x, (x > (1 + 2))} return IsPreviousExpressionPotentiallyAmbiguous(node); } return false; } private static bool IsPreviousExpressionPotentiallyAmbiguous(ExpressionSyntax node) { ExpressionSyntax previousExpression = null; if (node.IsParentKind(SyntaxKind.Argument, out ArgumentSyntax argument)) { if (argument.Parent is ArgumentListSyntax argumentList) { var argumentIndex = argumentList.Arguments.IndexOf(argument); if (argumentIndex > 0) { previousExpression = argumentList.Arguments[argumentIndex - 1].Expression; } } } else if (node.Parent is InitializerExpressionSyntax initializer) { var expressionIndex = initializer.Expressions.IndexOf(node); if (expressionIndex > 0) { previousExpression = initializer.Expressions[expressionIndex - 1]; } } if (previousExpression == null || !previousExpression.IsKind(SyntaxKind.LessThanExpression, out BinaryExpressionSyntax lessThanExpression)) { return false; } return (IsSimpleOrDottedName(lessThanExpression.Left) || lessThanExpression.Left.IsKind(SyntaxKind.CastExpression)) && IsSimpleOrDottedName(lessThanExpression.Right); } private static bool IsNextExpressionPotentiallyAmbiguous(ExpressionSyntax node) { ExpressionSyntax nextExpression = null; if (node.IsParentKind(SyntaxKind.Argument, out ArgumentSyntax argument)) { if (argument.Parent is ArgumentListSyntax argumentList) { var argumentIndex = argumentList.Arguments.IndexOf(argument); if (argumentIndex >= 0 && argumentIndex < argumentList.Arguments.Count - 1) { nextExpression = argumentList.Arguments[argumentIndex + 1].Expression; } } } else if (node.Parent is InitializerExpressionSyntax initializer) { var expressionIndex = initializer.Expressions.IndexOf(node); if (expressionIndex >= 0 && expressionIndex < initializer.Expressions.Count - 1) { nextExpression = initializer.Expressions[expressionIndex + 1]; } } if (nextExpression == null || !nextExpression.IsKind(SyntaxKind.GreaterThanExpression, out BinaryExpressionSyntax greaterThanExpression)) { return false; } return IsSimpleOrDottedName(greaterThanExpression.Left) && (greaterThanExpression.Right.IsKind(SyntaxKind.ParenthesizedExpression) || greaterThanExpression.Right.IsKind(SyntaxKind.CastExpression)); } private static bool IsSimpleOrDottedName(ExpressionSyntax expression) => expression.Kind() is SyntaxKind.IdentifierName or SyntaxKind.QualifiedName or SyntaxKind.SimpleMemberAccessExpression; public static bool CanRemoveParentheses(this ParenthesizedPatternSyntax node) { if (node.OpenParenToken.IsMissing || node.CloseParenToken.IsMissing) { // int x = (3; return false; } var pattern = node.Pattern; // We wrap a parenthesized pattern and we're parenthesized. We can remove our parens. if (pattern is ParenthesizedPatternSyntax) return true; // We're parenthesized discard pattern. We cannot remove parens. // x is (_) if (pattern is DiscardPatternSyntax && node.Parent is IsPatternExpressionSyntax) return false; // (not ...) -> not ... // // this is safe because unary patterns have the highest precedence, so even if you had: // (not ...) or (not ...) // // you can safely convert to `not ... or not ...` var patternPrecedence = pattern.GetOperatorPrecedence(); if (patternPrecedence == OperatorPrecedence.Primary || patternPrecedence == OperatorPrecedence.Unary) return true; // We're parenthesized and are inside a parenthesized pattern. We can remove our parens. // ((x)) -> (x) if (node.Parent is ParenthesizedPatternSyntax) return true; // x is (...) -> x is ... if (node.Parent is IsPatternExpressionSyntax) return true; // (x or y) => ... -> x or y => ... if (node.Parent is SwitchExpressionArmSyntax) return true; // X: (y or z) -> X: y or z if (node.Parent is SubpatternSyntax) return true; // case (x or y): -> case x or y: if (node.Parent is CasePatternSwitchLabelSyntax) return true; // Operator precedence cases: // - If the parent is not an expression, do not remove parentheses // - Otherwise, parentheses may be removed if doing so does not change operator associations. return node.Parent is PatternSyntax patternParent && !RemovalChangesAssociation(node, patternParent); } private static bool RemovalChangesAssociation( ParenthesizedPatternSyntax node, PatternSyntax parentPattern) { var pattern = node.Pattern; var precedence = pattern.GetOperatorPrecedence(); var parentPrecedence = parentPattern.GetOperatorPrecedence(); if (precedence == OperatorPrecedence.None || parentPrecedence == OperatorPrecedence.None) { // Be conservative if the expression or its parent has no precedence. return true; } // Association always changes if the expression's precedence is lower that its parent. return precedence < parentPrecedence; } public static OperatorPrecedence GetOperatorPrecedence(this PatternSyntax pattern) { switch (pattern) { case ConstantPatternSyntax _: case DiscardPatternSyntax _: case DeclarationPatternSyntax _: case RecursivePatternSyntax _: case TypePatternSyntax _: case VarPatternSyntax _: return OperatorPrecedence.Primary; case UnaryPatternSyntax _: case RelationalPatternSyntax _: return OperatorPrecedence.Unary; case BinaryPatternSyntax binaryPattern: if (binaryPattern.IsKind(SyntaxKind.AndPattern)) return OperatorPrecedence.ConditionalAnd; if (binaryPattern.IsKind(SyntaxKind.OrPattern)) return OperatorPrecedence.ConditionalOr; break; } Debug.Fail("Unhandled pattern type"); return OperatorPrecedence.None; } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Analyzers/Core/Analyzers/PopulateSwitch/PopulateSwitchExpressionHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.PopulateSwitch { internal static class PopulateSwitchExpressionHelpers { public static ICollection<ISymbol> GetMissingEnumMembers(ISwitchExpressionOperation operation) { var switchExpression = operation.Value; var switchExpressionType = switchExpression?.Type; // Check if the type of the expression is a nullable INamedTypeSymbol // if the type is both nullable and an INamedTypeSymbol extract the type argument from the nullable // and check if it is of enum type if (switchExpressionType != null) switchExpressionType = switchExpressionType.IsNullable(out var underlyingType) ? underlyingType : switchExpressionType; if (switchExpressionType?.TypeKind == TypeKind.Enum) { var enumMembers = new Dictionary<long, ISymbol>(); if (PopulateSwitchStatementHelpers.TryGetAllEnumMembers(switchExpressionType, enumMembers)) { RemoveExistingEnumMembers(operation, enumMembers); return enumMembers.Values; } } return SpecializedCollections.EmptyCollection<ISymbol>(); } private static void RemoveExistingEnumMembers( ISwitchExpressionOperation operation, Dictionary<long, ISymbol> enumMembers) { foreach (var arm in operation.Arms) { RemoveIfConstantPatternHasValue(arm.Pattern, enumMembers); if (arm.Pattern is IBinaryPatternOperation binaryPattern) { HandleBinaryPattern(binaryPattern, enumMembers); } } } private static void HandleBinaryPattern(IBinaryPatternOperation? binaryPattern, Dictionary<long, ISymbol> enumMembers) { if (binaryPattern?.OperatorKind == BinaryOperatorKind.Or) { RemoveIfConstantPatternHasValue(binaryPattern.LeftPattern, enumMembers); RemoveIfConstantPatternHasValue(binaryPattern.RightPattern, enumMembers); HandleBinaryPattern(binaryPattern.LeftPattern as IBinaryPatternOperation, enumMembers); HandleBinaryPattern(binaryPattern.RightPattern as IBinaryPatternOperation, enumMembers); } } private static void RemoveIfConstantPatternHasValue(IOperation operation, Dictionary<long, ISymbol> enumMembers) { if (operation is IConstantPatternOperation { Value: { ConstantValue: { HasValue: true, Value: var value } } }) enumMembers.Remove(IntegerUtilities.ToInt64(value)); } public static bool HasDefaultCase(ISwitchExpressionOperation operation) => operation.Arms.Any(a => IsDefault(a)); public static bool IsDefault(ISwitchExpressionArmOperation arm) { if (arm.Pattern.Kind == OperationKind.DiscardPattern) return true; if (arm.Pattern is IDeclarationPatternOperation declarationPattern) return declarationPattern.MatchesNull; return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.PopulateSwitch { internal static class PopulateSwitchExpressionHelpers { public static ICollection<ISymbol> GetMissingEnumMembers(ISwitchExpressionOperation operation) { var switchExpression = operation.Value; var switchExpressionType = switchExpression?.Type; // Check if the type of the expression is a nullable INamedTypeSymbol // if the type is both nullable and an INamedTypeSymbol extract the type argument from the nullable // and check if it is of enum type if (switchExpressionType != null) switchExpressionType = switchExpressionType.IsNullable(out var underlyingType) ? underlyingType : switchExpressionType; if (switchExpressionType?.TypeKind == TypeKind.Enum) { var enumMembers = new Dictionary<long, ISymbol>(); if (PopulateSwitchStatementHelpers.TryGetAllEnumMembers(switchExpressionType, enumMembers)) { RemoveExistingEnumMembers(operation, enumMembers); return enumMembers.Values; } } return SpecializedCollections.EmptyCollection<ISymbol>(); } private static void RemoveExistingEnumMembers( ISwitchExpressionOperation operation, Dictionary<long, ISymbol> enumMembers) { foreach (var arm in operation.Arms) { RemoveIfConstantPatternHasValue(arm.Pattern, enumMembers); if (arm.Pattern is IBinaryPatternOperation binaryPattern) { HandleBinaryPattern(binaryPattern, enumMembers); } } } private static void HandleBinaryPattern(IBinaryPatternOperation? binaryPattern, Dictionary<long, ISymbol> enumMembers) { if (binaryPattern?.OperatorKind == BinaryOperatorKind.Or) { RemoveIfConstantPatternHasValue(binaryPattern.LeftPattern, enumMembers); RemoveIfConstantPatternHasValue(binaryPattern.RightPattern, enumMembers); HandleBinaryPattern(binaryPattern.LeftPattern as IBinaryPatternOperation, enumMembers); HandleBinaryPattern(binaryPattern.RightPattern as IBinaryPatternOperation, enumMembers); } } private static void RemoveIfConstantPatternHasValue(IOperation operation, Dictionary<long, ISymbol> enumMembers) { if (operation is IConstantPatternOperation { Value: { ConstantValue: { HasValue: true, Value: var value } } }) enumMembers.Remove(IntegerUtilities.ToInt64(value)); } public static bool HasDefaultCase(ISwitchExpressionOperation operation) => operation.Arms.Any(a => IsDefault(a)); public static bool IsDefault(ISwitchExpressionArmOperation arm) { if (arm.Pattern.Kind == OperationKind.DiscardPattern) return true; if (arm.Pattern is IDeclarationPatternOperation declarationPattern) return declarationPattern.MatchesNull; return false; } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/VisualStudio/CSharp/Test/CodeModel/FileCodeClassTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 EnvDTE; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel { public class FileCodeClassTests : AbstractFileCodeElementTests { public FileCodeClassTests() : base(@"using System; public abstract class Goo : IDisposable, ICloneable { } [Serializable] public class Bar { int a; public int A { get { return a; } } public string WindowsUserID => ""Domain""; }") { } private CodeClass GetCodeClass(params object[] path) { return (CodeClass)GetCodeElement(path); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void IsAbstract() { var cc = GetCodeClass("Goo"); Assert.True(cc.IsAbstract); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void Bases() { var cc = GetCodeClass("Goo"); var bases = cc.Bases; Assert.Equal(1, bases.Count); Assert.Equal(1, bases.Cast<CodeElement>().Count()); Assert.NotNull(bases.Parent); var parentClass = bases.Parent as CodeClass; Assert.NotNull(parentClass); Assert.Equal("Goo", parentClass.FullName); Assert.True(bases.Item("object") is CodeClass); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void ImplementedInterfaces() { var cc = GetCodeClass("Goo"); var interfaces = cc.ImplementedInterfaces; Assert.Equal(2, interfaces.Count); Assert.Equal(2, interfaces.Cast<CodeElement>().Count()); Assert.NotNull(interfaces.Parent); var parentClass = interfaces.Parent as CodeClass; Assert.NotNull(parentClass); Assert.Equal("Goo", parentClass.FullName); Assert.True(interfaces.Item("System.IDisposable") is CodeInterface); Assert.True(interfaces.Item("ICloneable") is CodeInterface); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void KindTest() { var cc = GetCodeClass("Goo"); Assert.Equal(vsCMElement.vsCMElementClass, cc.Kind); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Attributes() { var testObject = GetCodeClass("Bar"); Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_AttributesWithDelimiter() { var testObject = GetCodeClass("Bar"); var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartAttributesWithDelimiter); Assert.Equal(7, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Body() { var testObject = GetCodeClass("Bar"); var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartBody); Assert.Equal(10, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_BodyWithDelimiter() { var testObject = GetCodeClass("Bar"); Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Header() { var testObject = GetCodeClass("Bar"); var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartHeader); Assert.Equal(8, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_HeaderWithAttributes() { var testObject = GetCodeClass("Bar"); Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Name() { var testObject = GetCodeClass("Bar"); Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartName)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Navigate() { var testObject = GetCodeClass("Bar"); var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartNavigate); Assert.Equal(8, startPoint.Line); Assert.Equal(14, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Whole() { var testObject = GetCodeClass("Bar"); Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartWhole)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_WholeWithAttributes() { var testObject = GetCodeClass("Bar"); var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes); Assert.Equal(7, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Attributes() { var testObject = GetCodeClass("Bar"); Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_AttributesWithDelimiter() { var testObject = GetCodeClass("Bar"); var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter); Assert.Equal(7, endPoint.Line); Assert.Equal(15, endPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Body() { var testObject = GetCodeClass("Bar"); var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartBody); Assert.Equal(21, endPoint.Line); Assert.Equal(1, endPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_BodyWithDelimiter() { var testObject = GetCodeClass("Bar"); Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Header() { var testObject = GetCodeClass("Bar"); Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartHeader)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_HeaderWithAttributes() { var testObject = GetCodeClass("Bar"); Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Name() { var testObject = GetCodeClass("Bar"); Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartName)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Navigate() { var testObject = GetCodeClass("Bar"); var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartNavigate); Assert.Equal(8, endPoint.Line); Assert.Equal(17, endPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Whole() { var testObject = GetCodeClass("Bar"); Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartWhole)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_WholeWithAttributes() { var testObject = GetCodeClass("Bar"); var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes); Assert.Equal(21, endPoint.Line); Assert.Equal(2, endPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void StartPoint() { var testObject = GetCodeClass("Bar"); var startPoint = testObject.StartPoint; Assert.Equal(7, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void EndPoint() { var testObject = GetCodeClass("Bar"); var endPoint = testObject.EndPoint; Assert.Equal(21, endPoint.Line); Assert.Equal(2, endPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void Accessor() { var testObject = GetCodeClass("Bar"); var l = from p in testObject.Members.OfType<CodeProperty>() where vsCMAccess.vsCMAccessPublic == p.Access && p.Getter != null && !p.Getter.IsShared && vsCMAccess.vsCMAccessPublic == p.Getter.Access select p; var z = l.ToList<CodeProperty>(); Assert.Equal(2, z.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. #nullable disable using System; using System.Linq; using EnvDTE; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel { public class FileCodeClassTests : AbstractFileCodeElementTests { public FileCodeClassTests() : base(@"using System; public abstract class Goo : IDisposable, ICloneable { } [Serializable] public class Bar { int a; public int A { get { return a; } } public string WindowsUserID => ""Domain""; }") { } private CodeClass GetCodeClass(params object[] path) { return (CodeClass)GetCodeElement(path); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void IsAbstract() { var cc = GetCodeClass("Goo"); Assert.True(cc.IsAbstract); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void Bases() { var cc = GetCodeClass("Goo"); var bases = cc.Bases; Assert.Equal(1, bases.Count); Assert.Equal(1, bases.Cast<CodeElement>().Count()); Assert.NotNull(bases.Parent); var parentClass = bases.Parent as CodeClass; Assert.NotNull(parentClass); Assert.Equal("Goo", parentClass.FullName); Assert.True(bases.Item("object") is CodeClass); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void ImplementedInterfaces() { var cc = GetCodeClass("Goo"); var interfaces = cc.ImplementedInterfaces; Assert.Equal(2, interfaces.Count); Assert.Equal(2, interfaces.Cast<CodeElement>().Count()); Assert.NotNull(interfaces.Parent); var parentClass = interfaces.Parent as CodeClass; Assert.NotNull(parentClass); Assert.Equal("Goo", parentClass.FullName); Assert.True(interfaces.Item("System.IDisposable") is CodeInterface); Assert.True(interfaces.Item("ICloneable") is CodeInterface); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void KindTest() { var cc = GetCodeClass("Goo"); Assert.Equal(vsCMElement.vsCMElementClass, cc.Kind); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Attributes() { var testObject = GetCodeClass("Bar"); Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_AttributesWithDelimiter() { var testObject = GetCodeClass("Bar"); var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartAttributesWithDelimiter); Assert.Equal(7, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Body() { var testObject = GetCodeClass("Bar"); var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartBody); Assert.Equal(10, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_BodyWithDelimiter() { var testObject = GetCodeClass("Bar"); Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Header() { var testObject = GetCodeClass("Bar"); var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartHeader); Assert.Equal(8, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_HeaderWithAttributes() { var testObject = GetCodeClass("Bar"); Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Name() { var testObject = GetCodeClass("Bar"); Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartName)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Navigate() { var testObject = GetCodeClass("Bar"); var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartNavigate); Assert.Equal(8, startPoint.Line); Assert.Equal(14, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_Whole() { var testObject = GetCodeClass("Bar"); Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartWhole)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetStartPoint_WholeWithAttributes() { var testObject = GetCodeClass("Bar"); var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes); Assert.Equal(7, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Attributes() { var testObject = GetCodeClass("Bar"); Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_AttributesWithDelimiter() { var testObject = GetCodeClass("Bar"); var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter); Assert.Equal(7, endPoint.Line); Assert.Equal(15, endPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Body() { var testObject = GetCodeClass("Bar"); var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartBody); Assert.Equal(21, endPoint.Line); Assert.Equal(1, endPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_BodyWithDelimiter() { var testObject = GetCodeClass("Bar"); Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Header() { var testObject = GetCodeClass("Bar"); Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartHeader)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_HeaderWithAttributes() { var testObject = GetCodeClass("Bar"); Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Name() { var testObject = GetCodeClass("Bar"); Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartName)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Navigate() { var testObject = GetCodeClass("Bar"); var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartNavigate); Assert.Equal(8, endPoint.Line); Assert.Equal(17, endPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_Whole() { var testObject = GetCodeClass("Bar"); Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartWhole)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void GetEndPoint_WholeWithAttributes() { var testObject = GetCodeClass("Bar"); var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes); Assert.Equal(21, endPoint.Line); Assert.Equal(2, endPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void StartPoint() { var testObject = GetCodeClass("Bar"); var startPoint = testObject.StartPoint; Assert.Equal(7, startPoint.Line); Assert.Equal(1, startPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void EndPoint() { var testObject = GetCodeClass("Bar"); var endPoint = testObject.EndPoint; Assert.Equal(21, endPoint.Line); Assert.Equal(2, endPoint.LineCharOffset); } [WpfFact] [Trait(Traits.Feature, Traits.Features.CodeModel)] public void Accessor() { var testObject = GetCodeClass("Bar"); var l = from p in testObject.Members.OfType<CodeProperty>() where vsCMAccess.vsCMAccessPublic == p.Access && p.Getter != null && !p.Getter.IsShared && vsCMAccess.vsCMAccessPublic == p.Getter.Access select p; var z = l.ToList<CodeProperty>(); Assert.Equal(2, z.Count); } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/CPS/ITempPECompiler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Microsoft.VisualStudio.LanguageServices.ProjectSystem { /// <summary> /// Provides TempPE compiler access /// </summary> /// <remarks> /// This is used by the project system to enable designer support in Visual Studio /// </remarks> internal interface ITempPECompiler { /// <summary> /// Compiles specific files into the TempPE DLL to provide designer support /// </summary> /// <param name="context">The project context</param> /// <param name="outputFileName">The binary output path</param> /// <param name="filesToInclude">Set of file paths from the project that should be included in the output. Should use StringComparer.OrdinalIgnoreCase to avoid file system issues.</param> /// <param name="cancellationToken">The cancellation token</param> /// <returns><see langword="true" /> if the compilation was successful</returns> /// <exception cref="System.IO.IOException">If the <paramref name="outputFileName"/> could not be written</exception> Task<bool> CompileAsync(IWorkspaceProjectContext context, string outputFileName, ISet<string> filesToInclude, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Microsoft.VisualStudio.LanguageServices.ProjectSystem { /// <summary> /// Provides TempPE compiler access /// </summary> /// <remarks> /// This is used by the project system to enable designer support in Visual Studio /// </remarks> internal interface ITempPECompiler { /// <summary> /// Compiles specific files into the TempPE DLL to provide designer support /// </summary> /// <param name="context">The project context</param> /// <param name="outputFileName">The binary output path</param> /// <param name="filesToInclude">Set of file paths from the project that should be included in the output. Should use StringComparer.OrdinalIgnoreCase to avoid file system issues.</param> /// <param name="cancellationToken">The cancellation token</param> /// <returns><see langword="true" /> if the compilation was successful</returns> /// <exception cref="System.IO.IOException">If the <paramref name="outputFileName"/> could not be written</exception> Task<bool> CompileAsync(IWorkspaceProjectContext context, string outputFileName, ISet<string> filesToInclude, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/VisualStudio/Core/Def/Implementation/TableDataSource/VisualStudioTodoListTable.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell.TableManager; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { [ExportEventListener(WellKnownEventListeners.TodoListProvider, WorkspaceKind.Host), Shared] internal class VisualStudioTodoListTableWorkspaceEventListener : IEventListener<ITodoListProvider> { internal const string IdentifierString = nameof(VisualStudioTodoListTable); private readonly ITableManagerProvider _tableManagerProvider; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioTodoListTableWorkspaceEventListener(ITableManagerProvider tableManagerProvider) => _tableManagerProvider = tableManagerProvider; public void StartListening(Workspace workspace, ITodoListProvider service) => new VisualStudioTodoListTable(workspace, service, _tableManagerProvider); internal class VisualStudioTodoListTable : VisualStudioBaseTodoListTable { // internal for testing internal VisualStudioTodoListTable(Workspace workspace, ITodoListProvider todoListProvider, ITableManagerProvider provider) : base(workspace, todoListProvider, IdentifierString, provider) { ConnectWorkspaceEvents(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell.TableManager; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { [ExportEventListener(WellKnownEventListeners.TodoListProvider, WorkspaceKind.Host), Shared] internal class VisualStudioTodoListTableWorkspaceEventListener : IEventListener<ITodoListProvider> { internal const string IdentifierString = nameof(VisualStudioTodoListTable); private readonly ITableManagerProvider _tableManagerProvider; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioTodoListTableWorkspaceEventListener(ITableManagerProvider tableManagerProvider) => _tableManagerProvider = tableManagerProvider; public void StartListening(Workspace workspace, ITodoListProvider service) => new VisualStudioTodoListTable(workspace, service, _tableManagerProvider); internal class VisualStudioTodoListTable : VisualStudioBaseTodoListTable { // internal for testing internal VisualStudioTodoListTable(Workspace workspace, ITodoListProvider todoListProvider, ITableManagerProvider provider) : base(workspace, todoListProvider, IdentifierString, provider) { ConnectWorkspaceEvents(); } } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/VisualStudio/CSharp/Test/PersistentStorage/CloudCachePersistentStorageTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.UnitTests.WorkspaceServices.Mocks; namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices { public class CloudCachePersistentStorageTests : AbstractPersistentStorageTests { internal override AbstractPersistentStorageService GetStorageService( OptionSet options, IMefHostExportProvider exportProvider, IPersistentStorageLocationService locationService, IPersistentStorageFaultInjector? faultInjector, string relativePathBase) { var threadingContext = exportProvider.GetExports<IThreadingContext>().Single().Value; return new MockCloudCachePersistentStorageService( locationService, relativePathBase, cs => { if (cs is IAsyncDisposable asyncDisposable) { threadingContext.JoinableTaskFactory.Run( () => asyncDisposable.DisposeAsync().AsTask()); } else if (cs is IDisposable disposable) { disposable.Dispose(); } }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.UnitTests.WorkspaceServices.Mocks; namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices { public class CloudCachePersistentStorageTests : AbstractPersistentStorageTests { internal override AbstractPersistentStorageService GetStorageService( OptionSet options, IMefHostExportProvider exportProvider, IPersistentStorageLocationService locationService, IPersistentStorageFaultInjector? faultInjector, string relativePathBase) { var threadingContext = exportProvider.GetExports<IThreadingContext>().Single().Value; return new MockCloudCachePersistentStorageService( locationService, relativePathBase, cs => { if (cs is IAsyncDisposable asyncDisposable) { threadingContext.JoinableTaskFactory.Run( () => asyncDisposable.DisposeAsync().AsTask()); } else if (cs is IDisposable disposable) { disposable.Dispose(); } }); } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Tools/ExternalAccess/FSharp/Editor/IFSharpNavigationBarItemService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor { internal interface IFSharpNavigationBarItemService { Task<IList<FSharpNavigationBarItem>> GetItemsAsync(Document document, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor { internal interface IFSharpNavigationBarItemService { Task<IList<FSharpNavigationBarItem>> GetItemsAsync(Document document, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Compilers/Core/CodeAnalysisTest/InternalUtilities/WeakListTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.InternalUtilities { public class WeakListTests : TestBase { private class C { private readonly string _value; public C(string value) { _value = value; } public override string ToString() { return _value; } } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] private ObjectReference<C> Create(string value) { return new ObjectReference<C>(new C(value)); } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] private void Add(WeakList<object> list, ObjectReference<C> value) { value.UseReference(r => list.Add(r)); } [Fact] public void EnumeratorCompacts() { var a = Create("a"); var b = Create("B"); var c = Create("C"); var d = Create("D"); var e = Create("E"); var list = new WeakList<object>(); Assert.Equal(0, list.TestOnly_UnderlyingArray.Length); Add(list, a); Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Add(list, b); Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Add(list, c); Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Add(list, d); Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Add(list, e); Assert.Equal(2 * 4 + 1, list.TestOnly_UnderlyingArray.Length); Assert.Equal(5, list.WeakCount); a.AssertReleased(); c.AssertReleased(); d.AssertReleased(); e.AssertReleased(); Assert.Equal(5, list.WeakCount); Assert.Null(list.GetWeakReference(0).GetTarget()); Assert.Same(b.GetReference(), list.GetWeakReference(1).GetTarget()); Assert.Null(list.GetWeakReference(2).GetTarget()); Assert.Null(list.GetWeakReference(3).GetTarget()); Assert.Null(list.GetWeakReference(4).GetTarget()); var array = list.ToArray(); Assert.Equal(1, array.Length); Assert.Same(b.GetReference(), array[0]); // list was compacted: Assert.Equal(1, list.WeakCount); Assert.Same(b.GetReference(), list.GetWeakReference(0).GetTarget()); Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); GC.KeepAlive(b.GetReference()); } [ConditionalFact(typeof(ClrOnly))] public void ResizeCompactsAllDead() { var a = Create("A"); var list = new WeakList<object>(); for (int i = 0; i < 9; i++) { Add(list, a); } Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full a.AssertReleased(); var b = Create("B"); Add(list, b); // shrinks, #alive < length/4 Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Assert.Equal(1, list.WeakCount); b.AssertReleased(); list.ToArray(); // shrinks, #alive == 0 Assert.Equal(0, list.TestOnly_UnderlyingArray.Length); Assert.Equal(0, list.WeakCount); } [Fact] public void ResizeCompactsFirstFourth() { var a = Create("A"); var b = Create("B"); var list = new WeakList<object>(); for (int i = 0; i < 8; i++) { Add(list, a); } Add(list, b); Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full a.AssertReleased(); Add(list, b); // shrinks, #alive < length/4 Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Assert.Equal(2, list.WeakCount); b.AssertReleased(); list.ToArray(); // shrinks, #alive == 0 Assert.Equal(0, list.TestOnly_UnderlyingArray.Length); Assert.Equal(0, list.WeakCount); } [Fact] public void ResizeCompactsSecondFourth() { var a = Create("A"); var b = Create("B"); var list = new WeakList<object>(); for (int i = 0; i < 6; i++) { Add(list, a); } for (int i = 0; i < 3; i++) { Add(list, b); } Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full a.AssertReleased(); Add(list, b); // just compacts, length/4 < #alive < 3/4 length Assert.Equal(9, list.TestOnly_UnderlyingArray.Length); Assert.Equal(4, list.WeakCount); for (int i = 0; i < list.TestOnly_UnderlyingArray.Length; i++) { if (i < 4) { Assert.Same(b.GetReference(), list.TestOnly_UnderlyingArray[i].GetTarget()); } else { Assert.Null(list.TestOnly_UnderlyingArray[i]); } } GC.KeepAlive(b); } [Fact] public void ResizeCompactsThirdFourth() { var a = Create("A"); var b = Create("B"); var list = new WeakList<object>(); for (int i = 0; i < 4; i++) { Add(list, a); } for (int i = 0; i < 5; i++) { Add(list, b); } Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full a.AssertReleased(); Add(list, b); // compacts #alive < 3/4 length Assert.Equal(9, list.TestOnly_UnderlyingArray.Length); Assert.Equal(6, list.WeakCount); for (int i = 0; i < list.TestOnly_UnderlyingArray.Length; i++) { if (i < 6) { Assert.Same(b.GetReference(), list.TestOnly_UnderlyingArray[i].GetTarget()); } else { Assert.Null(list.TestOnly_UnderlyingArray[i]); } } GC.KeepAlive(b); } [Fact] public void ResizeCompactsLastFourth() { var a = Create("A"); var b = Create("B"); var list = new WeakList<object>(); for (int i = 0; i < 2; i++) { Add(list, a); } for (int i = 0; i < 7; i++) { Add(list, b); } Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full a.AssertReleased(); Add(list, b); // expands #alive > 3/4 length Assert.Equal(9 * 2 + 1, list.TestOnly_UnderlyingArray.Length); Assert.Equal(8, list.WeakCount); for (int i = 0; i < list.TestOnly_UnderlyingArray.Length; i++) { if (i < 8) { Assert.Same(b.GetReference(), list.TestOnly_UnderlyingArray[i].GetTarget()); } else { Assert.Null(list.TestOnly_UnderlyingArray[i]); } } GC.KeepAlive(b); } [Fact] public void ResizeCompactsAllAlive() { var b = Create("B"); var list = new WeakList<object>(); for (int i = 0; i < 9; i++) { Add(list, b); } Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full Add(list, b); // expands #alive > 3/4 length Assert.Equal(9 * 2 + 1, list.TestOnly_UnderlyingArray.Length); Assert.Equal(10, list.WeakCount); for (int i = 0; i < list.TestOnly_UnderlyingArray.Length; i++) { if (i < 10) { Assert.Same(b.GetReference(), list.TestOnly_UnderlyingArray[i].GetTarget()); } else { Assert.Null(list.TestOnly_UnderlyingArray[i]); } } GC.KeepAlive(b); } [Fact] public void Errors() { var list = new WeakList<object>(); Assert.Throws<ArgumentOutOfRangeException>(() => list.GetWeakReference(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => list.GetWeakReference(0)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.InternalUtilities { public class WeakListTests : TestBase { private class C { private readonly string _value; public C(string value) { _value = value; } public override string ToString() { return _value; } } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] private ObjectReference<C> Create(string value) { return new ObjectReference<C>(new C(value)); } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] private void Add(WeakList<object> list, ObjectReference<C> value) { value.UseReference(r => list.Add(r)); } [Fact] public void EnumeratorCompacts() { var a = Create("a"); var b = Create("B"); var c = Create("C"); var d = Create("D"); var e = Create("E"); var list = new WeakList<object>(); Assert.Equal(0, list.TestOnly_UnderlyingArray.Length); Add(list, a); Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Add(list, b); Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Add(list, c); Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Add(list, d); Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Add(list, e); Assert.Equal(2 * 4 + 1, list.TestOnly_UnderlyingArray.Length); Assert.Equal(5, list.WeakCount); a.AssertReleased(); c.AssertReleased(); d.AssertReleased(); e.AssertReleased(); Assert.Equal(5, list.WeakCount); Assert.Null(list.GetWeakReference(0).GetTarget()); Assert.Same(b.GetReference(), list.GetWeakReference(1).GetTarget()); Assert.Null(list.GetWeakReference(2).GetTarget()); Assert.Null(list.GetWeakReference(3).GetTarget()); Assert.Null(list.GetWeakReference(4).GetTarget()); var array = list.ToArray(); Assert.Equal(1, array.Length); Assert.Same(b.GetReference(), array[0]); // list was compacted: Assert.Equal(1, list.WeakCount); Assert.Same(b.GetReference(), list.GetWeakReference(0).GetTarget()); Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); GC.KeepAlive(b.GetReference()); } [ConditionalFact(typeof(ClrOnly))] public void ResizeCompactsAllDead() { var a = Create("A"); var list = new WeakList<object>(); for (int i = 0; i < 9; i++) { Add(list, a); } Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full a.AssertReleased(); var b = Create("B"); Add(list, b); // shrinks, #alive < length/4 Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Assert.Equal(1, list.WeakCount); b.AssertReleased(); list.ToArray(); // shrinks, #alive == 0 Assert.Equal(0, list.TestOnly_UnderlyingArray.Length); Assert.Equal(0, list.WeakCount); } [Fact] public void ResizeCompactsFirstFourth() { var a = Create("A"); var b = Create("B"); var list = new WeakList<object>(); for (int i = 0; i < 8; i++) { Add(list, a); } Add(list, b); Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full a.AssertReleased(); Add(list, b); // shrinks, #alive < length/4 Assert.Equal(4, list.TestOnly_UnderlyingArray.Length); Assert.Equal(2, list.WeakCount); b.AssertReleased(); list.ToArray(); // shrinks, #alive == 0 Assert.Equal(0, list.TestOnly_UnderlyingArray.Length); Assert.Equal(0, list.WeakCount); } [Fact] public void ResizeCompactsSecondFourth() { var a = Create("A"); var b = Create("B"); var list = new WeakList<object>(); for (int i = 0; i < 6; i++) { Add(list, a); } for (int i = 0; i < 3; i++) { Add(list, b); } Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full a.AssertReleased(); Add(list, b); // just compacts, length/4 < #alive < 3/4 length Assert.Equal(9, list.TestOnly_UnderlyingArray.Length); Assert.Equal(4, list.WeakCount); for (int i = 0; i < list.TestOnly_UnderlyingArray.Length; i++) { if (i < 4) { Assert.Same(b.GetReference(), list.TestOnly_UnderlyingArray[i].GetTarget()); } else { Assert.Null(list.TestOnly_UnderlyingArray[i]); } } GC.KeepAlive(b); } [Fact] public void ResizeCompactsThirdFourth() { var a = Create("A"); var b = Create("B"); var list = new WeakList<object>(); for (int i = 0; i < 4; i++) { Add(list, a); } for (int i = 0; i < 5; i++) { Add(list, b); } Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full a.AssertReleased(); Add(list, b); // compacts #alive < 3/4 length Assert.Equal(9, list.TestOnly_UnderlyingArray.Length); Assert.Equal(6, list.WeakCount); for (int i = 0; i < list.TestOnly_UnderlyingArray.Length; i++) { if (i < 6) { Assert.Same(b.GetReference(), list.TestOnly_UnderlyingArray[i].GetTarget()); } else { Assert.Null(list.TestOnly_UnderlyingArray[i]); } } GC.KeepAlive(b); } [Fact] public void ResizeCompactsLastFourth() { var a = Create("A"); var b = Create("B"); var list = new WeakList<object>(); for (int i = 0; i < 2; i++) { Add(list, a); } for (int i = 0; i < 7; i++) { Add(list, b); } Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full a.AssertReleased(); Add(list, b); // expands #alive > 3/4 length Assert.Equal(9 * 2 + 1, list.TestOnly_UnderlyingArray.Length); Assert.Equal(8, list.WeakCount); for (int i = 0; i < list.TestOnly_UnderlyingArray.Length; i++) { if (i < 8) { Assert.Same(b.GetReference(), list.TestOnly_UnderlyingArray[i].GetTarget()); } else { Assert.Null(list.TestOnly_UnderlyingArray[i]); } } GC.KeepAlive(b); } [Fact] public void ResizeCompactsAllAlive() { var b = Create("B"); var list = new WeakList<object>(); for (int i = 0; i < 9; i++) { Add(list, b); } Assert.Equal(list.WeakCount, list.TestOnly_UnderlyingArray.Length); // full Add(list, b); // expands #alive > 3/4 length Assert.Equal(9 * 2 + 1, list.TestOnly_UnderlyingArray.Length); Assert.Equal(10, list.WeakCount); for (int i = 0; i < list.TestOnly_UnderlyingArray.Length; i++) { if (i < 10) { Assert.Same(b.GetReference(), list.TestOnly_UnderlyingArray[i].GetTarget()); } else { Assert.Null(list.TestOnly_UnderlyingArray[i]); } } GC.KeepAlive(b); } [Fact] public void Errors() { var list = new WeakList<object>(); Assert.Throws<ArgumentOutOfRangeException>(() => list.GetWeakReference(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => list.GetWeakReference(0)); } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Features/VisualBasic/Portable/GenerateMember/GenerateParameterizedMember/VisualBasicGenerateMethodService.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.GenerateMember.GenerateMethod <ExportLanguageService(GetType(IGenerateParameterizedMemberService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicGenerateMethodService Inherits AbstractGenerateMethodService(Of VisualBasicGenerateMethodService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides Function IsExplicitInterfaceGeneration(node As SyntaxNode) As Boolean Return TypeOf node Is QualifiedNameSyntax End Function Protected Overrides Function IsSimpleNameGeneration(node As SyntaxNode) As Boolean Return TypeOf node Is SimpleNameSyntax End Function Protected Overrides Function AreSpecialOptionsActive(semanticModel As SemanticModel) As Boolean Return VisualBasicCommonGenerationServiceMethods.AreSpecialOptionsActive(semanticModel) End Function Protected Overrides Function IsValidSymbol(symbol As ISymbol, semanticModel As SemanticModel) As Boolean Return VisualBasicCommonGenerationServiceMethods.IsValidSymbol(symbol, semanticModel) End Function Protected Overrides Function TryInitializeExplicitInterfaceState( document As SemanticDocument, node As SyntaxNode, cancellationToken As CancellationToken, ByRef identifierToken As SyntaxToken, ByRef methodSymbol As IMethodSymbol, ByRef typeToGenerateIn As INamedTypeSymbol) As Boolean Dim qualifiedName = DirectCast(node, QualifiedNameSyntax) identifierToken = qualifiedName.Right.Identifier If qualifiedName.IsParentKind(SyntaxKind.ImplementsClause) Then Dim implementsClause = DirectCast(qualifiedName.Parent, ImplementsClauseSyntax) If implementsClause.IsParentKind(SyntaxKind.SubStatement) OrElse implementsClause.IsParentKind(SyntaxKind.FunctionStatement) Then Dim methodStatement = DirectCast(implementsClause.Parent, MethodStatementSyntax) Dim semanticModel = document.SemanticModel methodSymbol = DirectCast(semanticModel.GetDeclaredSymbol(methodStatement, cancellationToken), IMethodSymbol) If methodSymbol IsNot Nothing AndAlso Not methodSymbol.ExplicitInterfaceImplementations.Any() Then Dim semanticInfo = semanticModel.GetTypeInfo(qualifiedName.Left, cancellationToken) typeToGenerateIn = TryCast(semanticInfo.Type, INamedTypeSymbol) Return typeToGenerateIn IsNot Nothing End If End If End If identifierToken = Nothing methodSymbol = Nothing typeToGenerateIn = Nothing Return False End Function Protected Overrides Function TryInitializeSimpleNameState( document As SemanticDocument, simpleName As SimpleNameSyntax, cancellationToken As CancellationToken, ByRef identifierToken As SyntaxToken, ByRef simpleNameOrMemberAccessExpression As ExpressionSyntax, ByRef invocationExpressionOpt As InvocationExpressionSyntax, ByRef isInConditionalAccessExpression As Boolean) As Boolean identifierToken = simpleName.Identifier Dim memberAccess = TryCast(simpleName?.Parent, MemberAccessExpressionSyntax) Dim conditionalMemberAccessInvocationExpression = TryCast(simpleName?.Parent?.Parent?.Parent, ConditionalAccessExpressionSyntax) Dim conditionalMemberAccessSimpleMemberAccess = TryCast(simpleName?.Parent?.Parent, ConditionalAccessExpressionSyntax) If memberAccess?.Name Is simpleName AndAlso memberAccess.Expression IsNot Nothing Then simpleNameOrMemberAccessExpression = memberAccess ElseIf TryCast(TryCast(conditionalMemberAccessInvocationExpression?.WhenNotNull, InvocationExpressionSyntax)?.Expression, MemberAccessExpressionSyntax)?.Name Is simpleName Then simpleNameOrMemberAccessExpression = conditionalMemberAccessInvocationExpression ElseIf TryCast(conditionalMemberAccessSimpleMemberAccess?.WhenNotNull, MemberAccessExpressionSyntax)?.Name Is simpleName Then simpleNameOrMemberAccessExpression = conditionalMemberAccessSimpleMemberAccess Else simpleNameOrMemberAccessExpression = simpleName End If If memberAccess Is Nothing OrElse memberAccess.Name Is simpleName Then ' VB is ambiguous. Something that looks like a method call might ' actually just be an array access. Check for that here. Dim semanticModel = document.SemanticModel Dim nameSemanticInfo = semanticModel.GetTypeInfo(simpleNameOrMemberAccessExpression, cancellationToken) If TypeOf nameSemanticInfo.Type IsNot IArrayTypeSymbol Then ' Don't offer generate method if it's a call to another constructor inside a ' constructor. If Not memberAccess.IsConstructorInitializer() Then If cancellationToken.IsCancellationRequested Then isInConditionalAccessExpression = False Return False End If isInConditionalAccessExpression = conditionalMemberAccessInvocationExpression IsNot Nothing Or conditionalMemberAccessSimpleMemberAccess IsNot Nothing If simpleNameOrMemberAccessExpression.IsParentKind(SyntaxKind.InvocationExpression) Then invocationExpressionOpt = DirectCast(simpleNameOrMemberAccessExpression.Parent, InvocationExpressionSyntax) Return invocationExpressionOpt.ArgumentList Is Nothing OrElse Not invocationExpressionOpt.ArgumentList.CloseParenToken.IsMissing ElseIf TryCast(TryCast(TryCast(simpleNameOrMemberAccessExpression, ConditionalAccessExpressionSyntax)?.WhenNotNull, InvocationExpressionSyntax)?.Expression, MemberAccessExpressionSyntax)?.Name Is simpleName invocationExpressionOpt = DirectCast(DirectCast(simpleNameOrMemberAccessExpression, ConditionalAccessExpressionSyntax).WhenNotNull, InvocationExpressionSyntax) Return invocationExpressionOpt.ArgumentList Is Nothing OrElse Not invocationExpressionOpt.ArgumentList.CloseParenToken.IsMissing ElseIf TryCast(conditionalMemberAccessSimpleMemberAccess?.WhenNotNull, MemberAccessExpressionSyntax)?.Name Is simpleName AndAlso IsLegal(semanticModel, simpleNameOrMemberAccessExpression, cancellationToken) Then Return True ElseIf simpleNameOrMemberAccessExpression?.Parent?.IsKind(SyntaxKind.AddressOfExpression, SyntaxKind.NameOfExpression) Then Return True ElseIf IsLegal(semanticModel, simpleNameOrMemberAccessExpression, cancellationToken) Then simpleNameOrMemberAccessExpression = If(memberAccess IsNot Nothing AndAlso memberAccess.Name Is simpleName, DirectCast(memberAccess, ExpressionSyntax), simpleName) Return True End If End If End If End If identifierToken = Nothing simpleNameOrMemberAccessExpression = Nothing invocationExpressionOpt = Nothing isInConditionalAccessExpression = False Return False End Function Private Shared Function IsLegal(semanticModel As SemanticModel, expression As ExpressionSyntax, cancellationToken As CancellationToken) As Boolean Dim tree = semanticModel.SyntaxTree Dim position = expression.SpanStart If Not tree.IsExpressionContext(position, cancellationToken) AndAlso Not tree.IsSingleLineStatementContext(position, cancellationToken) Then Return False End If Return expression.CanReplaceWithLValue(semanticModel, cancellationToken) End Function Protected Overrides Function CreateInvocationMethodInfo(document As SemanticDocument, state As AbstractGenerateParameterizedMemberService(Of VisualBasicGenerateMethodService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax).State) As AbstractInvocationInfo Return New VisualBasicGenerateParameterizedMemberService(Of VisualBasicGenerateMethodService).InvocationExpressionInfo(document, state) End Function Protected Overrides Function DetermineReturnTypeForSimpleNameOrMemberAccessExpression(typeInferenceService As ITypeInferenceService, semanticModel As SemanticModel, expression As ExpressionSyntax, cancellationToken As CancellationToken) As ITypeSymbol Return typeInferenceService.InferType(semanticModel, expression, True, cancellationToken) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.GenerateMember.GenerateMethod <ExportLanguageService(GetType(IGenerateParameterizedMemberService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicGenerateMethodService Inherits AbstractGenerateMethodService(Of VisualBasicGenerateMethodService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides Function IsExplicitInterfaceGeneration(node As SyntaxNode) As Boolean Return TypeOf node Is QualifiedNameSyntax End Function Protected Overrides Function IsSimpleNameGeneration(node As SyntaxNode) As Boolean Return TypeOf node Is SimpleNameSyntax End Function Protected Overrides Function AreSpecialOptionsActive(semanticModel As SemanticModel) As Boolean Return VisualBasicCommonGenerationServiceMethods.AreSpecialOptionsActive(semanticModel) End Function Protected Overrides Function IsValidSymbol(symbol As ISymbol, semanticModel As SemanticModel) As Boolean Return VisualBasicCommonGenerationServiceMethods.IsValidSymbol(symbol, semanticModel) End Function Protected Overrides Function TryInitializeExplicitInterfaceState( document As SemanticDocument, node As SyntaxNode, cancellationToken As CancellationToken, ByRef identifierToken As SyntaxToken, ByRef methodSymbol As IMethodSymbol, ByRef typeToGenerateIn As INamedTypeSymbol) As Boolean Dim qualifiedName = DirectCast(node, QualifiedNameSyntax) identifierToken = qualifiedName.Right.Identifier If qualifiedName.IsParentKind(SyntaxKind.ImplementsClause) Then Dim implementsClause = DirectCast(qualifiedName.Parent, ImplementsClauseSyntax) If implementsClause.IsParentKind(SyntaxKind.SubStatement) OrElse implementsClause.IsParentKind(SyntaxKind.FunctionStatement) Then Dim methodStatement = DirectCast(implementsClause.Parent, MethodStatementSyntax) Dim semanticModel = document.SemanticModel methodSymbol = DirectCast(semanticModel.GetDeclaredSymbol(methodStatement, cancellationToken), IMethodSymbol) If methodSymbol IsNot Nothing AndAlso Not methodSymbol.ExplicitInterfaceImplementations.Any() Then Dim semanticInfo = semanticModel.GetTypeInfo(qualifiedName.Left, cancellationToken) typeToGenerateIn = TryCast(semanticInfo.Type, INamedTypeSymbol) Return typeToGenerateIn IsNot Nothing End If End If End If identifierToken = Nothing methodSymbol = Nothing typeToGenerateIn = Nothing Return False End Function Protected Overrides Function TryInitializeSimpleNameState( document As SemanticDocument, simpleName As SimpleNameSyntax, cancellationToken As CancellationToken, ByRef identifierToken As SyntaxToken, ByRef simpleNameOrMemberAccessExpression As ExpressionSyntax, ByRef invocationExpressionOpt As InvocationExpressionSyntax, ByRef isInConditionalAccessExpression As Boolean) As Boolean identifierToken = simpleName.Identifier Dim memberAccess = TryCast(simpleName?.Parent, MemberAccessExpressionSyntax) Dim conditionalMemberAccessInvocationExpression = TryCast(simpleName?.Parent?.Parent?.Parent, ConditionalAccessExpressionSyntax) Dim conditionalMemberAccessSimpleMemberAccess = TryCast(simpleName?.Parent?.Parent, ConditionalAccessExpressionSyntax) If memberAccess?.Name Is simpleName AndAlso memberAccess.Expression IsNot Nothing Then simpleNameOrMemberAccessExpression = memberAccess ElseIf TryCast(TryCast(conditionalMemberAccessInvocationExpression?.WhenNotNull, InvocationExpressionSyntax)?.Expression, MemberAccessExpressionSyntax)?.Name Is simpleName Then simpleNameOrMemberAccessExpression = conditionalMemberAccessInvocationExpression ElseIf TryCast(conditionalMemberAccessSimpleMemberAccess?.WhenNotNull, MemberAccessExpressionSyntax)?.Name Is simpleName Then simpleNameOrMemberAccessExpression = conditionalMemberAccessSimpleMemberAccess Else simpleNameOrMemberAccessExpression = simpleName End If If memberAccess Is Nothing OrElse memberAccess.Name Is simpleName Then ' VB is ambiguous. Something that looks like a method call might ' actually just be an array access. Check for that here. Dim semanticModel = document.SemanticModel Dim nameSemanticInfo = semanticModel.GetTypeInfo(simpleNameOrMemberAccessExpression, cancellationToken) If TypeOf nameSemanticInfo.Type IsNot IArrayTypeSymbol Then ' Don't offer generate method if it's a call to another constructor inside a ' constructor. If Not memberAccess.IsConstructorInitializer() Then If cancellationToken.IsCancellationRequested Then isInConditionalAccessExpression = False Return False End If isInConditionalAccessExpression = conditionalMemberAccessInvocationExpression IsNot Nothing Or conditionalMemberAccessSimpleMemberAccess IsNot Nothing If simpleNameOrMemberAccessExpression.IsParentKind(SyntaxKind.InvocationExpression) Then invocationExpressionOpt = DirectCast(simpleNameOrMemberAccessExpression.Parent, InvocationExpressionSyntax) Return invocationExpressionOpt.ArgumentList Is Nothing OrElse Not invocationExpressionOpt.ArgumentList.CloseParenToken.IsMissing ElseIf TryCast(TryCast(TryCast(simpleNameOrMemberAccessExpression, ConditionalAccessExpressionSyntax)?.WhenNotNull, InvocationExpressionSyntax)?.Expression, MemberAccessExpressionSyntax)?.Name Is simpleName invocationExpressionOpt = DirectCast(DirectCast(simpleNameOrMemberAccessExpression, ConditionalAccessExpressionSyntax).WhenNotNull, InvocationExpressionSyntax) Return invocationExpressionOpt.ArgumentList Is Nothing OrElse Not invocationExpressionOpt.ArgumentList.CloseParenToken.IsMissing ElseIf TryCast(conditionalMemberAccessSimpleMemberAccess?.WhenNotNull, MemberAccessExpressionSyntax)?.Name Is simpleName AndAlso IsLegal(semanticModel, simpleNameOrMemberAccessExpression, cancellationToken) Then Return True ElseIf simpleNameOrMemberAccessExpression?.Parent?.IsKind(SyntaxKind.AddressOfExpression, SyntaxKind.NameOfExpression) Then Return True ElseIf IsLegal(semanticModel, simpleNameOrMemberAccessExpression, cancellationToken) Then simpleNameOrMemberAccessExpression = If(memberAccess IsNot Nothing AndAlso memberAccess.Name Is simpleName, DirectCast(memberAccess, ExpressionSyntax), simpleName) Return True End If End If End If End If identifierToken = Nothing simpleNameOrMemberAccessExpression = Nothing invocationExpressionOpt = Nothing isInConditionalAccessExpression = False Return False End Function Private Shared Function IsLegal(semanticModel As SemanticModel, expression As ExpressionSyntax, cancellationToken As CancellationToken) As Boolean Dim tree = semanticModel.SyntaxTree Dim position = expression.SpanStart If Not tree.IsExpressionContext(position, cancellationToken) AndAlso Not tree.IsSingleLineStatementContext(position, cancellationToken) Then Return False End If Return expression.CanReplaceWithLValue(semanticModel, cancellationToken) End Function Protected Overrides Function CreateInvocationMethodInfo(document As SemanticDocument, state As AbstractGenerateParameterizedMemberService(Of VisualBasicGenerateMethodService, SimpleNameSyntax, ExpressionSyntax, InvocationExpressionSyntax).State) As AbstractInvocationInfo Return New VisualBasicGenerateParameterizedMemberService(Of VisualBasicGenerateMethodService).InvocationExpressionInfo(document, state) End Function Protected Overrides Function DetermineReturnTypeForSimpleNameOrMemberAccessExpression(typeInferenceService As ITypeInferenceService, semanticModel As SemanticModel, expression As ExpressionSyntax, cancellationToken As CancellationToken) As ITypeSymbol Return typeInferenceService.InferType(semanticModel, expression, True, cancellationToken) End Function End Class End Namespace
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/EditorFeatures/Core/Implementation/DocumentationComments/AbstractDocumentationCommentCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.DocumentationComments { internal abstract class AbstractDocumentationCommentCommandHandler : IChainedCommandHandler<TypeCharCommandArgs>, ICommandHandler<ReturnKeyCommandArgs>, ICommandHandler<InsertCommentCommandArgs>, IChainedCommandHandler<OpenLineAboveCommandArgs>, IChainedCommandHandler<OpenLineBelowCommandArgs> { private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly ITextUndoHistoryRegistry _undoHistoryRegistry; private readonly IEditorOperationsFactoryService _editorOperationsFactoryService; protected AbstractDocumentationCommentCommandHandler( IUIThreadOperationExecutor uiThreadOperationExecutor, ITextUndoHistoryRegistry undoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService) { Contract.ThrowIfNull(uiThreadOperationExecutor); Contract.ThrowIfNull(undoHistoryRegistry); Contract.ThrowIfNull(editorOperationsFactoryService); _uiThreadOperationExecutor = uiThreadOperationExecutor; _undoHistoryRegistry = undoHistoryRegistry; _editorOperationsFactoryService = editorOperationsFactoryService; } protected abstract string ExteriorTriviaText { get; } private char TriggerCharacter { get { return ExteriorTriviaText[^1]; } } public string DisplayName => EditorFeaturesResources.Documentation_Comment; private static DocumentationCommentSnippet? InsertOnCharacterTyped(IDocumentationCommentSnippetService service, SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken) => service.GetDocumentationCommentSnippetOnCharacterTyped(syntaxTree, text, position, options, cancellationToken); private static DocumentationCommentSnippet? InsertOnEnterTyped(IDocumentationCommentSnippetService service, SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken) => service.GetDocumentationCommentSnippetOnEnterTyped(syntaxTree, text, position, options, cancellationToken); private static DocumentationCommentSnippet? InsertOnCommandInvoke(IDocumentationCommentSnippetService service, SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken) => service.GetDocumentationCommentSnippetOnCommandInvoke(syntaxTree, text, position, options, cancellationToken); private static void ApplySnippet(DocumentationCommentSnippet snippet, ITextBuffer subjectBuffer, ITextView textView) { var replaceSpan = snippet.SpanToReplace.ToSpan(); subjectBuffer.Replace(replaceSpan, snippet.SnippetText); textView.TryMoveCaretToAndEnsureVisible(subjectBuffer.CurrentSnapshot.GetPoint(replaceSpan.Start + snippet.CaretOffset)); } private static bool CompleteComment( ITextBuffer subjectBuffer, ITextView textView, Func<IDocumentationCommentSnippetService, SyntaxTree, SourceText, int, DocumentOptionSet, CancellationToken, DocumentationCommentSnippet?> getSnippetAction, CancellationToken cancellationToken) { var caretPosition = textView.GetCaretPoint(subjectBuffer) ?? -1; if (caretPosition < 0) { return false; } var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return false; } var service = document.GetRequiredLanguageService<IDocumentationCommentSnippetService>(); var syntaxTree = document.GetRequiredSyntaxTreeSynchronously(cancellationToken); var text = syntaxTree.GetText(cancellationToken); var documentOptions = document.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken); var snippet = getSnippetAction(service, syntaxTree, text, caretPosition, documentOptions, cancellationToken); if (snippet != null) { ApplySnippet(snippet, subjectBuffer, textView); return true; } return false; } public CommandState GetCommandState(TypeCharCommandArgs args, Func<CommandState> nextHandler) => nextHandler(); public void ExecuteCommand(TypeCharCommandArgs args, Action nextHandler, CommandExecutionContext context) { // Ensure the character is actually typed in the editor nextHandler(); if (args.TypedChar != TriggerCharacter) { return; } // Don't execute in cloud environment, as we let LSP handle that if (args.SubjectBuffer.IsInLspEditorContext()) { return; } CompleteComment(args.SubjectBuffer, args.TextView, InsertOnCharacterTyped, CancellationToken.None); } public CommandState GetCommandState(ReturnKeyCommandArgs args) => CommandState.Unspecified; public bool ExecuteCommand(ReturnKeyCommandArgs args, CommandExecutionContext context) { // Don't execute in cloud environment, as we let LSP handle that if (args.SubjectBuffer.IsInLspEditorContext()) { return false; } // Check to see if the current line starts with exterior trivia. If so, we'll take over. // If not, let the nextHandler run. var originalPosition = -1; // The original position should be a position that is consistent with the syntax tree, even // after Enter is pressed. Thus, we use the start of the first selection if there is one. // Otherwise, getting the tokens to the right or the left might return unexpected results. if (args.TextView.Selection.SelectedSpans.Count > 0) { var selectedSpan = args.TextView.Selection .GetSnapshotSpansOnBuffer(args.SubjectBuffer) .FirstOrNull(); originalPosition = selectedSpan != null ? selectedSpan.Value.Start : args.TextView.GetCaretPoint(args.SubjectBuffer) ?? -1; } if (originalPosition < 0) { return false; } if (!CurrentLineStartsWithExteriorTrivia(args.SubjectBuffer, originalPosition)) { return false; } // According to JasonMal, the text undo history is associated with the surface buffer // in projection buffer scenarios, so the following line's usage of the surface buffer // is correct. using (var transaction = _undoHistoryRegistry.GetHistory(args.TextView.TextBuffer).CreateTransaction(EditorFeaturesResources.Insert_new_line)) { var editorOperations = _editorOperationsFactoryService.GetEditorOperations(args.TextView); editorOperations.InsertNewLine(); CompleteComment(args.SubjectBuffer, args.TextView, InsertOnEnterTyped, CancellationToken.None); // Since we're wrapping the ENTER key undo transaction, we always complete // the transaction -- even if we didn't generate anything. transaction.Complete(); } return true; } public CommandState GetCommandState(InsertCommentCommandArgs args) { var caretPosition = args.TextView.GetCaretPoint(args.SubjectBuffer) ?? -1; if (caretPosition < 0) { return CommandState.Unavailable; } var document = args.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return CommandState.Unavailable; } var service = document.GetRequiredLanguageService<IDocumentationCommentSnippetService>(); var isValidTargetMember = false; _uiThreadOperationExecutor.Execute("IntelliSense", defaultDescription: "", allowCancellation: true, showProgress: false, action: c => { var syntaxTree = document.GetRequiredSyntaxTreeSynchronously(c.UserCancellationToken); var text = syntaxTree.GetText(c.UserCancellationToken); isValidTargetMember = service.IsValidTargetMember(syntaxTree, text, caretPosition, c.UserCancellationToken); }); return isValidTargetMember ? CommandState.Available : CommandState.Unavailable; } public bool ExecuteCommand(InsertCommentCommandArgs args, CommandExecutionContext context) { using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Inserting_documentation_comment)) { return CompleteComment(args.SubjectBuffer, args.TextView, InsertOnCommandInvoke, context.OperationContext.UserCancellationToken); } } public CommandState GetCommandState(OpenLineAboveCommandArgs args, Func<CommandState> nextHandler) => nextHandler(); public void ExecuteCommand(OpenLineAboveCommandArgs args, Action nextHandler, CommandExecutionContext context) { // Check to see if the current line starts with exterior trivia. If so, we'll take over. // If not, let the nextHandler run. var subjectBuffer = args.SubjectBuffer; var caretPosition = args.TextView.GetCaretPoint(subjectBuffer) ?? -1; if (caretPosition < 0) { nextHandler(); return; } if (!CurrentLineStartsWithExteriorTrivia(subjectBuffer, caretPosition)) { nextHandler(); return; } // Allow nextHandler() to run and then insert exterior trivia if necessary. nextHandler(); var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return; } var service = document.GetRequiredLanguageService<IDocumentationCommentSnippetService>(); InsertExteriorTriviaIfNeeded(service, args.TextView, subjectBuffer); } public CommandState GetCommandState(OpenLineBelowCommandArgs args, Func<CommandState> nextHandler) => nextHandler(); public void ExecuteCommand(OpenLineBelowCommandArgs args, Action nextHandler, CommandExecutionContext context) { // Check to see if the current line starts with exterior trivia. If so, we'll take over. // If not, let the nextHandler run. var subjectBuffer = args.SubjectBuffer; var caretPosition = args.TextView.GetCaretPoint(subjectBuffer) ?? -1; if (caretPosition < 0) { nextHandler(); return; } if (!CurrentLineStartsWithExteriorTrivia(subjectBuffer, caretPosition)) { nextHandler(); return; } var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return; } var service = document.GetRequiredLanguageService<IDocumentationCommentSnippetService>(); // Allow nextHandler() to run and the insert exterior trivia if necessary. nextHandler(); InsertExteriorTriviaIfNeeded(service, args.TextView, subjectBuffer); } private void InsertExteriorTriviaIfNeeded(IDocumentationCommentSnippetService service, ITextView textView, ITextBuffer subjectBuffer) { var caretPosition = textView.GetCaretPoint(subjectBuffer) ?? -1; if (caretPosition < 0) { return; } var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return; } var text = document .GetTextAsync(CancellationToken.None) .WaitAndGetResult(CancellationToken.None); // We only insert exterior trivia if the current line does not start with exterior trivia // and the previous line does. var currentLine = text.Lines.GetLineFromPosition(caretPosition); if (currentLine.LineNumber <= 0) { return; } var previousLine = text.Lines[currentLine.LineNumber - 1]; if (LineStartsWithExteriorTrivia(currentLine) || !LineStartsWithExteriorTrivia(previousLine)) { return; } var documentOptions = document.GetOptionsAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); var snippet = service.GetDocumentationCommentSnippetFromPreviousLine(documentOptions, currentLine, previousLine); if (snippet != null) { ApplySnippet(snippet, subjectBuffer, textView); } } private bool CurrentLineStartsWithExteriorTrivia(ITextBuffer subjectBuffer, int position) { var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return false; } var text = document .GetTextAsync(CancellationToken.None) .WaitAndGetResult(CancellationToken.None); var currentLine = text.Lines.GetLineFromPosition(position); return LineStartsWithExteriorTrivia(currentLine); } private bool LineStartsWithExteriorTrivia(TextLine line) { var lineText = line.ToString(); var lineOffset = lineText.GetFirstNonWhitespaceOffset() ?? -1; if (lineOffset < 0) { return false; } return string.CompareOrdinal(lineText, lineOffset, ExteriorTriviaText, 0, ExteriorTriviaText.Length) == 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.DocumentationComments { internal abstract class AbstractDocumentationCommentCommandHandler : IChainedCommandHandler<TypeCharCommandArgs>, ICommandHandler<ReturnKeyCommandArgs>, ICommandHandler<InsertCommentCommandArgs>, IChainedCommandHandler<OpenLineAboveCommandArgs>, IChainedCommandHandler<OpenLineBelowCommandArgs> { private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly ITextUndoHistoryRegistry _undoHistoryRegistry; private readonly IEditorOperationsFactoryService _editorOperationsFactoryService; protected AbstractDocumentationCommentCommandHandler( IUIThreadOperationExecutor uiThreadOperationExecutor, ITextUndoHistoryRegistry undoHistoryRegistry, IEditorOperationsFactoryService editorOperationsFactoryService) { Contract.ThrowIfNull(uiThreadOperationExecutor); Contract.ThrowIfNull(undoHistoryRegistry); Contract.ThrowIfNull(editorOperationsFactoryService); _uiThreadOperationExecutor = uiThreadOperationExecutor; _undoHistoryRegistry = undoHistoryRegistry; _editorOperationsFactoryService = editorOperationsFactoryService; } protected abstract string ExteriorTriviaText { get; } private char TriggerCharacter { get { return ExteriorTriviaText[^1]; } } public string DisplayName => EditorFeaturesResources.Documentation_Comment; private static DocumentationCommentSnippet? InsertOnCharacterTyped(IDocumentationCommentSnippetService service, SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken) => service.GetDocumentationCommentSnippetOnCharacterTyped(syntaxTree, text, position, options, cancellationToken); private static DocumentationCommentSnippet? InsertOnEnterTyped(IDocumentationCommentSnippetService service, SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken) => service.GetDocumentationCommentSnippetOnEnterTyped(syntaxTree, text, position, options, cancellationToken); private static DocumentationCommentSnippet? InsertOnCommandInvoke(IDocumentationCommentSnippetService service, SyntaxTree syntaxTree, SourceText text, int position, DocumentOptionSet options, CancellationToken cancellationToken) => service.GetDocumentationCommentSnippetOnCommandInvoke(syntaxTree, text, position, options, cancellationToken); private static void ApplySnippet(DocumentationCommentSnippet snippet, ITextBuffer subjectBuffer, ITextView textView) { var replaceSpan = snippet.SpanToReplace.ToSpan(); subjectBuffer.Replace(replaceSpan, snippet.SnippetText); textView.TryMoveCaretToAndEnsureVisible(subjectBuffer.CurrentSnapshot.GetPoint(replaceSpan.Start + snippet.CaretOffset)); } private static bool CompleteComment( ITextBuffer subjectBuffer, ITextView textView, Func<IDocumentationCommentSnippetService, SyntaxTree, SourceText, int, DocumentOptionSet, CancellationToken, DocumentationCommentSnippet?> getSnippetAction, CancellationToken cancellationToken) { var caretPosition = textView.GetCaretPoint(subjectBuffer) ?? -1; if (caretPosition < 0) { return false; } var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return false; } var service = document.GetRequiredLanguageService<IDocumentationCommentSnippetService>(); var syntaxTree = document.GetRequiredSyntaxTreeSynchronously(cancellationToken); var text = syntaxTree.GetText(cancellationToken); var documentOptions = document.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken); var snippet = getSnippetAction(service, syntaxTree, text, caretPosition, documentOptions, cancellationToken); if (snippet != null) { ApplySnippet(snippet, subjectBuffer, textView); return true; } return false; } public CommandState GetCommandState(TypeCharCommandArgs args, Func<CommandState> nextHandler) => nextHandler(); public void ExecuteCommand(TypeCharCommandArgs args, Action nextHandler, CommandExecutionContext context) { // Ensure the character is actually typed in the editor nextHandler(); if (args.TypedChar != TriggerCharacter) { return; } // Don't execute in cloud environment, as we let LSP handle that if (args.SubjectBuffer.IsInLspEditorContext()) { return; } CompleteComment(args.SubjectBuffer, args.TextView, InsertOnCharacterTyped, CancellationToken.None); } public CommandState GetCommandState(ReturnKeyCommandArgs args) => CommandState.Unspecified; public bool ExecuteCommand(ReturnKeyCommandArgs args, CommandExecutionContext context) { // Don't execute in cloud environment, as we let LSP handle that if (args.SubjectBuffer.IsInLspEditorContext()) { return false; } // Check to see if the current line starts with exterior trivia. If so, we'll take over. // If not, let the nextHandler run. var originalPosition = -1; // The original position should be a position that is consistent with the syntax tree, even // after Enter is pressed. Thus, we use the start of the first selection if there is one. // Otherwise, getting the tokens to the right or the left might return unexpected results. if (args.TextView.Selection.SelectedSpans.Count > 0) { var selectedSpan = args.TextView.Selection .GetSnapshotSpansOnBuffer(args.SubjectBuffer) .FirstOrNull(); originalPosition = selectedSpan != null ? selectedSpan.Value.Start : args.TextView.GetCaretPoint(args.SubjectBuffer) ?? -1; } if (originalPosition < 0) { return false; } if (!CurrentLineStartsWithExteriorTrivia(args.SubjectBuffer, originalPosition)) { return false; } // According to JasonMal, the text undo history is associated with the surface buffer // in projection buffer scenarios, so the following line's usage of the surface buffer // is correct. using (var transaction = _undoHistoryRegistry.GetHistory(args.TextView.TextBuffer).CreateTransaction(EditorFeaturesResources.Insert_new_line)) { var editorOperations = _editorOperationsFactoryService.GetEditorOperations(args.TextView); editorOperations.InsertNewLine(); CompleteComment(args.SubjectBuffer, args.TextView, InsertOnEnterTyped, CancellationToken.None); // Since we're wrapping the ENTER key undo transaction, we always complete // the transaction -- even if we didn't generate anything. transaction.Complete(); } return true; } public CommandState GetCommandState(InsertCommentCommandArgs args) { var caretPosition = args.TextView.GetCaretPoint(args.SubjectBuffer) ?? -1; if (caretPosition < 0) { return CommandState.Unavailable; } var document = args.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return CommandState.Unavailable; } var service = document.GetRequiredLanguageService<IDocumentationCommentSnippetService>(); var isValidTargetMember = false; _uiThreadOperationExecutor.Execute("IntelliSense", defaultDescription: "", allowCancellation: true, showProgress: false, action: c => { var syntaxTree = document.GetRequiredSyntaxTreeSynchronously(c.UserCancellationToken); var text = syntaxTree.GetText(c.UserCancellationToken); isValidTargetMember = service.IsValidTargetMember(syntaxTree, text, caretPosition, c.UserCancellationToken); }); return isValidTargetMember ? CommandState.Available : CommandState.Unavailable; } public bool ExecuteCommand(InsertCommentCommandArgs args, CommandExecutionContext context) { using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Inserting_documentation_comment)) { return CompleteComment(args.SubjectBuffer, args.TextView, InsertOnCommandInvoke, context.OperationContext.UserCancellationToken); } } public CommandState GetCommandState(OpenLineAboveCommandArgs args, Func<CommandState> nextHandler) => nextHandler(); public void ExecuteCommand(OpenLineAboveCommandArgs args, Action nextHandler, CommandExecutionContext context) { // Check to see if the current line starts with exterior trivia. If so, we'll take over. // If not, let the nextHandler run. var subjectBuffer = args.SubjectBuffer; var caretPosition = args.TextView.GetCaretPoint(subjectBuffer) ?? -1; if (caretPosition < 0) { nextHandler(); return; } if (!CurrentLineStartsWithExteriorTrivia(subjectBuffer, caretPosition)) { nextHandler(); return; } // Allow nextHandler() to run and then insert exterior trivia if necessary. nextHandler(); var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return; } var service = document.GetRequiredLanguageService<IDocumentationCommentSnippetService>(); InsertExteriorTriviaIfNeeded(service, args.TextView, subjectBuffer); } public CommandState GetCommandState(OpenLineBelowCommandArgs args, Func<CommandState> nextHandler) => nextHandler(); public void ExecuteCommand(OpenLineBelowCommandArgs args, Action nextHandler, CommandExecutionContext context) { // Check to see if the current line starts with exterior trivia. If so, we'll take over. // If not, let the nextHandler run. var subjectBuffer = args.SubjectBuffer; var caretPosition = args.TextView.GetCaretPoint(subjectBuffer) ?? -1; if (caretPosition < 0) { nextHandler(); return; } if (!CurrentLineStartsWithExteriorTrivia(subjectBuffer, caretPosition)) { nextHandler(); return; } var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return; } var service = document.GetRequiredLanguageService<IDocumentationCommentSnippetService>(); // Allow nextHandler() to run and the insert exterior trivia if necessary. nextHandler(); InsertExteriorTriviaIfNeeded(service, args.TextView, subjectBuffer); } private void InsertExteriorTriviaIfNeeded(IDocumentationCommentSnippetService service, ITextView textView, ITextBuffer subjectBuffer) { var caretPosition = textView.GetCaretPoint(subjectBuffer) ?? -1; if (caretPosition < 0) { return; } var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return; } var text = document .GetTextAsync(CancellationToken.None) .WaitAndGetResult(CancellationToken.None); // We only insert exterior trivia if the current line does not start with exterior trivia // and the previous line does. var currentLine = text.Lines.GetLineFromPosition(caretPosition); if (currentLine.LineNumber <= 0) { return; } var previousLine = text.Lines[currentLine.LineNumber - 1]; if (LineStartsWithExteriorTrivia(currentLine) || !LineStartsWithExteriorTrivia(previousLine)) { return; } var documentOptions = document.GetOptionsAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); var snippet = service.GetDocumentationCommentSnippetFromPreviousLine(documentOptions, currentLine, previousLine); if (snippet != null) { ApplySnippet(snippet, subjectBuffer, textView); } } private bool CurrentLineStartsWithExteriorTrivia(ITextBuffer subjectBuffer, int position) { var document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return false; } var text = document .GetTextAsync(CancellationToken.None) .WaitAndGetResult(CancellationToken.None); var currentLine = text.Lines.GetLineFromPosition(position); return LineStartsWithExteriorTrivia(currentLine); } private bool LineStartsWithExteriorTrivia(TextLine line) { var lineText = line.ToString(); var lineOffset = lineText.GetFirstNonWhitespaceOffset() ?? -1; if (lineOffset < 0) { return false; } return string.CompareOrdinal(lineText, lineOffset, ExteriorTriviaText, 0, ExteriorTriviaText.Length) == 0; } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/EditorFeatures/Core.Wpf/Preview/PreviewStaticClassificationTaggerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel.Composition; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.Implementation.Classification; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { /// <summary> /// This tagger assumes content of the buffer never get changed. /// and the buffer provides static classification information on the buffer content /// through <see cref="PredefinedPreviewTaggerKeys.StaticClassificationSpansKey" /> in the buffer property bag /// </summary> [Export(typeof(ITaggerProvider))] [TagType(typeof(IClassificationTag))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TextViewRole(TextViewRoles.PreviewRole)] internal class PreviewStaticClassificationTaggerProvider : ITaggerProvider { private readonly ClassificationTypeMap _typeMap; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewStaticClassificationTaggerProvider(ClassificationTypeMap typeMap) => _typeMap = typeMap; public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag { return new Tagger(_typeMap, buffer) as ITagger<T>; } private class Tagger : ITagger<IClassificationTag> { private readonly ClassificationTypeMap _typeMap; private readonly ITextBuffer _buffer; public Tagger(ClassificationTypeMap typeMap, ITextBuffer buffer) { _typeMap = typeMap; _buffer = buffer; } /// <summary> /// The tags never change for this tagger. /// </summary> event EventHandler<SnapshotSpanEventArgs> ITagger<IClassificationTag>.TagsChanged { add { } remove { } } public IEnumerable<ITagSpan<IClassificationTag>> GetTags(NormalizedSnapshotSpanCollection spans) { if (!_buffer.Properties.TryGetProperty(PredefinedPreviewTaggerKeys.StaticClassificationSpansKey, out ImmutableArray<ClassifiedSpan> classifiedSpans)) { yield break; } foreach (var span in spans) { // we don't need to care about snapshot since everything is static and never changes in preview var requestSpan = span.Span.ToTextSpan(); foreach (var classifiedSpan in classifiedSpans) { if (classifiedSpan.TextSpan.IntersectsWith(requestSpan)) { yield return ClassificationUtilities.Convert(_typeMap, span.Snapshot, classifiedSpan); } } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel.Composition; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.Implementation.Classification; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { /// <summary> /// This tagger assumes content of the buffer never get changed. /// and the buffer provides static classification information on the buffer content /// through <see cref="PredefinedPreviewTaggerKeys.StaticClassificationSpansKey" /> in the buffer property bag /// </summary> [Export(typeof(ITaggerProvider))] [TagType(typeof(IClassificationTag))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TextViewRole(TextViewRoles.PreviewRole)] internal class PreviewStaticClassificationTaggerProvider : ITaggerProvider { private readonly ClassificationTypeMap _typeMap; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewStaticClassificationTaggerProvider(ClassificationTypeMap typeMap) => _typeMap = typeMap; public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag { return new Tagger(_typeMap, buffer) as ITagger<T>; } private class Tagger : ITagger<IClassificationTag> { private readonly ClassificationTypeMap _typeMap; private readonly ITextBuffer _buffer; public Tagger(ClassificationTypeMap typeMap, ITextBuffer buffer) { _typeMap = typeMap; _buffer = buffer; } /// <summary> /// The tags never change for this tagger. /// </summary> event EventHandler<SnapshotSpanEventArgs> ITagger<IClassificationTag>.TagsChanged { add { } remove { } } public IEnumerable<ITagSpan<IClassificationTag>> GetTags(NormalizedSnapshotSpanCollection spans) { if (!_buffer.Properties.TryGetProperty(PredefinedPreviewTaggerKeys.StaticClassificationSpansKey, out ImmutableArray<ClassifiedSpan> classifiedSpans)) { yield break; } foreach (var span in spans) { // we don't need to care about snapshot since everything is static and never changes in preview var requestSpan = span.Span.ToTextSpan(); foreach (var classifiedSpan in classifiedSpans) { if (classifiedSpan.TextSpan.IntersectsWith(requestSpan)) { yield return ClassificationUtilities.Convert(_typeMap, span.Snapshot, classifiedSpan); } } } } } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/ExpressionEvaluator/Core/Source/ResultProvider/NetFX20/Helpers/Placeholders.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection; using System.Runtime.Versioning; [assembly: TargetFramework(".NETFramework,Version=v2.0")] namespace Microsoft.CodeAnalysis { internal static class ReflectionTypeExtensions { // Replaces a missing 4.5 method. internal static Type GetTypeInfo(this Type type) { return type; } // Replaces a missing 4.5 method. public static FieldInfo GetDeclaredField(this Type type, string name) { return type.GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly); } // Replaces a missing 4.5 method. public static MethodInfo GetDeclaredMethod(this Type type, string name, Type[] parameterTypes) { return type.GetMethod(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly, null, parameterTypes, null); } } /// <summary> /// Required by <see cref="SymbolDisplayPartKind"/>. /// </summary> internal static class IErrorTypeSymbol { } /// <summary> /// Required by <see cref="Microsoft.CodeAnalysis.FailFast"/> /// </summary> internal static class Environment { public static void FailFast(string message) => System.Environment.FailFast(message); public static void FailFast(string message, Exception exception) => System.Environment.FailFast(exception.ToString()); public static string NewLine => System.Environment.NewLine; public static int ProcessorCount => System.Environment.ProcessorCount; } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] // To allow this dll to use extension methods even though we are targeting CLR v2, re-define ExtensionAttribute internal class ExtensionAttribute : Attribute { } /// <summary> /// This satisfies a cref on <see cref="Microsoft.CodeAnalysis.ExpressionEvaluator.DynamicFlagsCustomTypeInfo.CopyTo"/>. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] internal class DynamicAttribute : Attribute { } /// <summary> /// This satisfies a cref on <see cref="Microsoft.CodeAnalysis.WellKnownMemberNames"/>. /// </summary> internal interface INotifyCompletion { void OnCompleted(); } } namespace System.Text { internal static class StringBuilderExtensions { public static void Clear(this StringBuilder builder) { builder.Length = 0; // Matches the real definition. } } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] internal sealed class TargetFrameworkAttribute : Attribute { public string FrameworkName { get; } public string FrameworkDisplayName { get; set; } public TargetFrameworkAttribute(string frameworkName) => FrameworkName = frameworkName; } } namespace System.Threading { public readonly struct CancellationToken { /// <summary> /// .NET Framework 2.0 does not support cancellation via <see cref="CancellationToken"/>. /// </summary> public bool IsCancellationRequested => 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; using System.Reflection; using System.Runtime.Versioning; [assembly: TargetFramework(".NETFramework,Version=v2.0")] namespace Microsoft.CodeAnalysis { internal static class ReflectionTypeExtensions { // Replaces a missing 4.5 method. internal static Type GetTypeInfo(this Type type) { return type; } // Replaces a missing 4.5 method. public static FieldInfo GetDeclaredField(this Type type, string name) { return type.GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly); } // Replaces a missing 4.5 method. public static MethodInfo GetDeclaredMethod(this Type type, string name, Type[] parameterTypes) { return type.GetMethod(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly, null, parameterTypes, null); } } /// <summary> /// Required by <see cref="SymbolDisplayPartKind"/>. /// </summary> internal static class IErrorTypeSymbol { } /// <summary> /// Required by <see cref="Microsoft.CodeAnalysis.FailFast"/> /// </summary> internal static class Environment { public static void FailFast(string message) => System.Environment.FailFast(message); public static void FailFast(string message, Exception exception) => System.Environment.FailFast(exception.ToString()); public static string NewLine => System.Environment.NewLine; public static int ProcessorCount => System.Environment.ProcessorCount; } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] // To allow this dll to use extension methods even though we are targeting CLR v2, re-define ExtensionAttribute internal class ExtensionAttribute : Attribute { } /// <summary> /// This satisfies a cref on <see cref="Microsoft.CodeAnalysis.ExpressionEvaluator.DynamicFlagsCustomTypeInfo.CopyTo"/>. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] internal class DynamicAttribute : Attribute { } /// <summary> /// This satisfies a cref on <see cref="Microsoft.CodeAnalysis.WellKnownMemberNames"/>. /// </summary> internal interface INotifyCompletion { void OnCompleted(); } } namespace System.Text { internal static class StringBuilderExtensions { public static void Clear(this StringBuilder builder) { builder.Length = 0; // Matches the real definition. } } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] internal sealed class TargetFrameworkAttribute : Attribute { public string FrameworkName { get; } public string FrameworkDisplayName { get; set; } public TargetFrameworkAttribute(string frameworkName) => FrameworkName = frameworkName; } } namespace System.Threading { public readonly struct CancellationToken { /// <summary> /// .NET Framework 2.0 does not support cancellation via <see cref="CancellationToken"/>. /// </summary> public bool IsCancellationRequested => false; } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/CodeStyle/VisualBasic/Tests/Microsoft.CodeAnalysis.VisualBasic.CodeStyle.UnitTests.vbproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <TargetFramework>net472</TargetFramework> <RootNamespace></RootNamespace> <DefineConstants>$(DefineConstants),CODE_STYLE</DefineConstants> <!-- https://github.com/dotnet/roslyn/issues/31412 --> <SkipTests Condition="'$(TestRuntime)' == 'Mono'">true</SkipTests> </PropertyGroup> <ItemGroup> <Compile Include="..\..\..\EditorFeatures\VisualBasicTest\Diagnostics\AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest.vb" Link="AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest.vb" /> <Compile Include="..\..\..\EditorFeatures\VisualBasicTest\Utils.vb" Link="Utils.vb" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.CodeAnalysis.VisualBasic.CodeFix.Testing.XUnit" Version="$(MicrosoftCodeAnalysisVisualBasicCodeFixTestingXUnitVersion)" /> </ItemGroup> <ItemGroup Label="Project References"> <!-- Directly reference the Workspaces project so we always test against the latest Roslyn bits --> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> </ItemGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Core\Analyzers\Microsoft.CodeAnalysis.CodeStyle.csproj" /> <ProjectReference Include="..\..\Core\CodeFixes\Microsoft.CodeAnalysis.CodeStyle.Fixes.csproj" /> <ProjectReference Include="..\..\Core\Tests\Microsoft.CodeAnalysis.CodeStyle.UnitTestUtilities.csproj" /> <ProjectReference Include="..\..\Core\Tests\Microsoft.CodeAnalysis.CodeStyle.LegacyTestFramework.UnitTestUtilities.csproj" /> <ProjectReference Include="..\Analyzers\Microsoft.CodeAnalysis.VisualBasic.CodeStyle.vbproj" /> <ProjectReference Include="..\CodeFixes\Microsoft.CodeAnalysis.VisualBasic.CodeStyle.Fixes.vbproj" /> </ItemGroup> <ItemGroup Label="Project References"> <!-- TODO: Remove all the below project references once all analyzer/code fix tests are switched to Microsoft.CodeAnalysis.Testing --> <ProjectReference Include="..\..\..\Compilers\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Core.Wpf\Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj" /> <ProjectReference Include="..\..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" /> <ProjectReference Include="..\..\..\Interactive\Host\Microsoft.CodeAnalysis.InteractiveHost.csproj" /> <ProjectReference Include="..\..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\..\..\Scripting\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" /> <ProjectReference Include="..\..\..\Features\LanguageServer\Protocol\Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" /> <ProjectReference Include="..\..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\TestUtilities\Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> <ProjectReference Include="..\..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Workspaces\CoreTestUtilities\Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj" /> </ItemGroup> <ItemGroup> <Import Include="Microsoft.CodeAnalysis.Editor.Shared.Extensions" /> <Import Include="Microsoft.CodeAnalysis.Shared.Extensions" /> <Import Include="Microsoft.CodeAnalysis.Test.Utilities" /> <Import Include="Microsoft.CodeAnalysis.VisualBasic" /> <Import Include="Microsoft.CodeAnalysis.VisualBasic.UnitTests" /> <Import Include="Roslyn.Test.Utilities" /> <Import Include="System.Threading.Tasks" /> <Import Include="Xunit" /> </ItemGroup> <Import Project="..\..\..\Analyzers\VisualBasic\Tests\VisualBasicAnalyzers.UnitTests.projitems" Label="Shared" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <TargetFramework>net472</TargetFramework> <RootNamespace></RootNamespace> <DefineConstants>$(DefineConstants),CODE_STYLE</DefineConstants> <!-- https://github.com/dotnet/roslyn/issues/31412 --> <SkipTests Condition="'$(TestRuntime)' == 'Mono'">true</SkipTests> </PropertyGroup> <ItemGroup> <Compile Include="..\..\..\EditorFeatures\VisualBasicTest\Diagnostics\AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest.vb" Link="AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest.vb" /> <Compile Include="..\..\..\EditorFeatures\VisualBasicTest\Utils.vb" Link="Utils.vb" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.CodeAnalysis.VisualBasic.CodeFix.Testing.XUnit" Version="$(MicrosoftCodeAnalysisVisualBasicCodeFixTestingXUnitVersion)" /> </ItemGroup> <ItemGroup Label="Project References"> <!-- Directly reference the Workspaces project so we always test against the latest Roslyn bits --> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> </ItemGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Core\Analyzers\Microsoft.CodeAnalysis.CodeStyle.csproj" /> <ProjectReference Include="..\..\Core\CodeFixes\Microsoft.CodeAnalysis.CodeStyle.Fixes.csproj" /> <ProjectReference Include="..\..\Core\Tests\Microsoft.CodeAnalysis.CodeStyle.UnitTestUtilities.csproj" /> <ProjectReference Include="..\..\Core\Tests\Microsoft.CodeAnalysis.CodeStyle.LegacyTestFramework.UnitTestUtilities.csproj" /> <ProjectReference Include="..\Analyzers\Microsoft.CodeAnalysis.VisualBasic.CodeStyle.vbproj" /> <ProjectReference Include="..\CodeFixes\Microsoft.CodeAnalysis.VisualBasic.CodeStyle.Fixes.vbproj" /> </ItemGroup> <ItemGroup Label="Project References"> <!-- TODO: Remove all the below project references once all analyzer/code fix tests are switched to Microsoft.CodeAnalysis.Testing --> <ProjectReference Include="..\..\..\Compilers\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Core.Wpf\Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj" /> <ProjectReference Include="..\..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" /> <ProjectReference Include="..\..\..\Interactive\Host\Microsoft.CodeAnalysis.InteractiveHost.csproj" /> <ProjectReference Include="..\..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\..\..\Scripting\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" /> <ProjectReference Include="..\..\..\Features\LanguageServer\Protocol\Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" /> <ProjectReference Include="..\..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\TestUtilities\Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> <ProjectReference Include="..\..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Workspaces\CoreTestUtilities\Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj" /> </ItemGroup> <ItemGroup> <Import Include="Microsoft.CodeAnalysis.Editor.Shared.Extensions" /> <Import Include="Microsoft.CodeAnalysis.Shared.Extensions" /> <Import Include="Microsoft.CodeAnalysis.Test.Utilities" /> <Import Include="Microsoft.CodeAnalysis.VisualBasic" /> <Import Include="Microsoft.CodeAnalysis.VisualBasic.UnitTests" /> <Import Include="Roslyn.Test.Utilities" /> <Import Include="System.Threading.Tasks" /> <Import Include="Xunit" /> </ItemGroup> <Import Project="..\..\..\Analyzers\VisualBasic\Tests\VisualBasicAnalyzers.UnitTests.projitems" Label="Shared" /> </Project>
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Tools/ExternalAccess/OmniSharp/ExtractClass/IOmniSharpExtractClassOptionsService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.ExtractClass { internal interface IOmniSharpExtractClassOptionsService { Task<OmniSharpExtractClassOptions?> GetExtractClassOptionsAsync(Document document, INamedTypeSymbol originalType, ISymbol? selectedMember); } internal sealed class OmniSharpExtractClassOptions { public string FileName { get; } public string TypeName { get; } public bool SameFile { get; } public ImmutableArray<OmniSharpExtractClassMemberAnalysisResult> MemberAnalysisResults { get; } public OmniSharpExtractClassOptions( string fileName, string typeName, bool sameFile, ImmutableArray<OmniSharpExtractClassMemberAnalysisResult> memberAnalysisResults) { FileName = fileName; TypeName = typeName; SameFile = sameFile; MemberAnalysisResults = memberAnalysisResults; } } internal sealed class OmniSharpExtractClassMemberAnalysisResult { /// <summary> /// The member needs to be pulled up. /// </summary> public ISymbol Member { get; } /// <summary> /// Whether to make the member abstract when added to the new class /// </summary> public bool MakeAbstract { get; } public OmniSharpExtractClassMemberAnalysisResult( ISymbol member, bool makeAbstract) { Member = member; MakeAbstract = makeAbstract; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.ExtractClass { internal interface IOmniSharpExtractClassOptionsService { Task<OmniSharpExtractClassOptions?> GetExtractClassOptionsAsync(Document document, INamedTypeSymbol originalType, ISymbol? selectedMember); } internal sealed class OmniSharpExtractClassOptions { public string FileName { get; } public string TypeName { get; } public bool SameFile { get; } public ImmutableArray<OmniSharpExtractClassMemberAnalysisResult> MemberAnalysisResults { get; } public OmniSharpExtractClassOptions( string fileName, string typeName, bool sameFile, ImmutableArray<OmniSharpExtractClassMemberAnalysisResult> memberAnalysisResults) { FileName = fileName; TypeName = typeName; SameFile = sameFile; MemberAnalysisResults = memberAnalysisResults; } } internal sealed class OmniSharpExtractClassMemberAnalysisResult { /// <summary> /// The member needs to be pulled up. /// </summary> public ISymbol Member { get; } /// <summary> /// Whether to make the member abstract when added to the new class /// </summary> public bool MakeAbstract { get; } public OmniSharpExtractClassMemberAnalysisResult( ISymbol member, bool makeAbstract) { Member = member; MakeAbstract = makeAbstract; } } }
-1