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,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenWithBlock.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenWithBlock Inherits BasicTestBase <Fact()> Public Sub WithTestModuleField() CompileAndVerify( <compilation> <file name="a.vb"> Module ModuleWithField Public field1 As String = "a" End Module Module WithTestModuleField Sub Main() With field1 Dim l = .Length System.Console.WriteLine(.ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="a") End Sub <Fact()> Public Sub WithTestLineContinuation() CompileAndVerify( <compilation> <file name="a.vb"> Class Class1 Public Property Property1 As Class1 Public Property Property2 As String End Class Module WithTestLineContinuation Sub Main() With New Class1() .Property1 = New Class1() .Property1. Property1 = New Class1() .Property1 _ . Property1 _ .Property2 = "a" System.Console.WriteLine(.Property1 _ .Property1. Property2) End With End Sub End Module </file> </compilation>, expectedOutput:="a") End Sub <Fact()> Public Sub WithTestNested() CompileAndVerify( <compilation> <file name="a.vb"> Class Class2 Default Public ReadOnly Property Item(x As Integer) As Class2 Get Return New Class2 End Get End Property Public Property Property2 As String End Class Module WithTestNested Sub Main() Dim c2 As New Class2() With c2(3) .Property2 = "b" With .Item(4) .Property2 = "a" System.Console.Write(.Property2) End With System.Console.Write(.Property2) End With End Sub End Module </file> </compilation>, expectedOutput:="ab") End Sub <Fact()> Public Sub TestSimpleWithWithNothingLiteral() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Sub Main(args As String()) With Nothing End With End Sub End Module </file> </compilation>, expectedOutput:=""). VerifyDiagnostics(). VerifyIL("Program.Main", <![CDATA[ { // Code size 3 (0x3) .maxstack 1 IL_0000: ldnull IL_0001: pop IL_0002: ret } ]]>) End Sub <Fact()> Public Sub WithUnused() CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x(10) As S x(0).s = "hello" Dim s As String Dim dummy As Integer For i As Integer = 0 To 5 With x(i) s = .s dummy += .i End With Next End Sub Structure S Public s As String Public i As Integer End Structure End Module </file> </compilation>, expectedOutput:=""). VerifyDiagnostics(). VerifyIL("Module1.Main", <![CDATA[ { // Code size 53 (0x35) .maxstack 2 .locals init (Module1.S() V_0, //x Integer V_1, //dummy Integer V_2, //i Module1.S& V_3) //$W0 IL_0000: ldc.i4.s 11 IL_0002: newarr "Module1.S" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.0 IL_000a: ldelema "Module1.S" IL_000f: ldstr "hello" IL_0014: stfld "Module1.S.s As String" IL_0019: ldc.i4.0 IL_001a: stloc.2 IL_001b: ldloc.0 IL_001c: ldloc.2 IL_001d: ldelema "Module1.S" IL_0022: stloc.3 IL_0023: ldloc.1 IL_0024: ldloc.3 IL_0025: ldfld "Module1.S.i As Integer" IL_002a: add.ovf IL_002b: stloc.1 IL_002c: ldloc.2 IL_002d: ldc.i4.1 IL_002e: add.ovf IL_002f: stloc.2 IL_0030: ldloc.2 IL_0031: ldc.i4.5 IL_0032: ble.s IL_001b IL_0034: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithNothingLiteralAndExtensionMethod() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Runtime.CompilerServices Module Program Sub Main(args As String()) With Nothing Try .ExtMethod() Catch ex As NullReferenceException Console.WriteLine("Success") End Try End With End Sub End Module Module Ext &lt;ExtensionAttribute&gt; Sub ExtMeth(this As Object) End Sub End Module </file> </compilation>, expectedOutput:="Success").VerifyDiagnostics() End Sub <Fact()> Public Sub TestSimpleWithWithExtensionMethod() CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Runtime.CompilerServices Class C1 End Class Module Program Sub Main(args As String()) With New C1() .Goo() End With End Sub &lt;Extension()&gt; Public Sub Goo(ByRef x As C1) End Sub End Module </file> </compilation>, expectedOutput:=""). VerifyDiagnostics(). VerifyIL("Program.Main", <![CDATA[ { // Code size 16 (0x10) .maxstack 1 .locals init (C1 V_0) IL_0000: newobj "Sub C1..ctor()" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: call "Sub Program.Goo(ByRef C1)" IL_000d: ldnull IL_000e: pop IL_000f: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithStringLiteral() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) With "abc" Dim a = .GetType() Console.WriteLine(a.ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="System.String").VerifyDiagnostics() End Sub <Fact()> Public Sub TestSimpleWithWithStringExpression() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) With "abc|" + "cba".ToString() Console.WriteLine(.GetType().ToString() + ": " + .ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="System.String: abc|cba") c.VerifyDiagnostics() c.VerifyIL("Program.Main", <![CDATA[ { // Code size 56 (0x38) .maxstack 3 .locals init (String V_0) //$W0 IL_0000: ldstr "abc|" IL_0005: ldstr "cba" IL_000a: callvirt "Function String.ToString() As String" IL_000f: call "Function String.Concat(String, String) As String" IL_0014: stloc.0 IL_0015: ldloc.0 IL_0016: callvirt "Function Object.GetType() As System.Type" IL_001b: callvirt "Function System.Type.ToString() As String" IL_0020: ldstr ": " IL_0025: ldloc.0 IL_0026: callvirt "Function String.ToString() As String" IL_002b: call "Function String.Concat(String, String, String) As String" IL_0030: call "Sub System.Console.WriteLine(String)" IL_0035: ldnull IL_0036: stloc.0 IL_0037: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithStringArrayLValue() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim sss(10) As String sss(3) = "#3" With sss("123".Length) Console.WriteLine(.GetType().ToString() + ": " + .ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="System.String: #3"). VerifyDiagnostics(). VerifyIL("Program.Main", <![CDATA[ { // Code size 62 (0x3e) .maxstack 4 .locals init (String V_0) //$W0 IL_0000: ldc.i4.s 11 IL_0002: newarr "String" IL_0007: dup IL_0008: ldc.i4.3 IL_0009: ldstr "#3" IL_000e: stelem.ref IL_000f: ldstr "123" IL_0014: call "Function String.get_Length() As Integer" IL_0019: ldelem.ref IL_001a: stloc.0 IL_001b: ldloc.0 IL_001c: callvirt "Function Object.GetType() As System.Type" IL_0021: callvirt "Function System.Type.ToString() As String" IL_0026: ldstr ": " IL_002b: ldloc.0 IL_002c: callvirt "Function String.ToString() As String" IL_0031: call "Function String.Concat(String, String, String) As String" IL_0036: call "Sub System.Console.WriteLine(String)" IL_003b: ldnull IL_003c: stloc.0 IL_003d: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithNumericLiteral() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) With 1 Dim a = .GetType() Console.WriteLine(a.ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="System.Int32") c.VerifyDiagnostics() c.VerifyIL("Program.Main", <![CDATA[ { // Code size 24 (0x18) .maxstack 1 .locals init (Integer V_0) //$W0 IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: box "Integer" IL_0008: call "Function Object.GetType() As System.Type" IL_000d: callvirt "Function System.Type.ToString() As String" IL_0012: call "Sub System.Console.WriteLine(String)" IL_0017: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithNumericRValue() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) With IntProp Dim a = .GetType() Console.WriteLine(a.ToString()) End With End Sub Public Property IntProp As Integer End Module </file> </compilation>, expectedOutput:="System.Int32") c.VerifyDiagnostics() c.VerifyIL("Program.Main", <![CDATA[ { // Code size 28 (0x1c) .maxstack 1 .locals init (Integer V_0) //$W0 IL_0000: call "Function Program.get_IntProp() As Integer" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: box "Integer" IL_000c: call "Function Object.GetType() As System.Type" IL_0011: callvirt "Function System.Type.ToString() As String" IL_0016: call "Sub System.Console.WriteLine(String)" IL_001b: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithNumericLValue() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim i As Integer = 1 With i Dim a = .GetType() Console.WriteLine(a.ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="System.Int32"). VerifyDiagnostics(). VerifyIL("Program.Main", <![CDATA[ { // Code size 24 (0x18) .maxstack 1 .locals init (Integer V_0) //i IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: box "Integer" IL_0008: call "Function Object.GetType() As System.Type" IL_000d: callvirt "Function System.Type.ToString() As String" IL_0012: call "Sub System.Console.WriteLine(String)" IL_0017: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithNumericLValue2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Public i As Integer = 1 Sub Main(args As String()) With i Dim a = .GetType() Console.WriteLine(a.ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="System.Int32"). VerifyDiagnostics(). VerifyIL("Program.Main", <![CDATA[ { // Code size 27 (0x1b) .maxstack 1 IL_0000: ldsflda "Program.i As Integer" IL_0005: ldind.i4 IL_0006: box "Integer" IL_000b: call "Function Object.GetType() As System.Type" IL_0010: callvirt "Function System.Type.ToString() As String" IL_0015: call "Sub System.Console.WriteLine(String)" IL_001a: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithStructureLValueAndExtensionMethod() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Runtime.CompilerServices Structure C1 Public field As Integer Public Property GooProp As Integer End Structure Class C2 Public Shared Sub Main() Dim x = New C1() With x .field = 123 .ExtMeth End With End Sub End Class Module program &lt;ExtensionAttribute&gt; Sub ExtMeth(this As C1) Console.Write(this.field) End Sub End Module </file> </compilation>, expectedOutput:="123"). VerifyDiagnostics(). VerifyIL("C2.Main", <![CDATA[ { // Code size 24 (0x18) .maxstack 2 .locals init (C1 V_0) //x IL_0000: ldloca.s V_0 IL_0002: initobj "C1" IL_0008: ldloca.s V_0 IL_000a: ldc.i4.s 123 IL_000c: stfld "C1.field As Integer" IL_0011: ldloc.0 IL_0012: call "Sub program.ExtMeth(C1)" IL_0017: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithStructureLValueAndExtensionMethod2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Runtime.CompilerServices Structure C1 Public field As Integer Public Property GooProp As Integer End Structure Class C2 Public X As New C1() Public Sub Main2() With X .field = 123 .ExtMeth End With End Sub Public Shared Sub Main() Call New C2().Main2() End Sub End Class Module program &lt;ExtensionAttribute&gt; Sub ExtMeth(this As C1) Console.Write(this.field) End Sub End Module </file> </compilation>, expectedOutput:="123"). VerifyDiagnostics(). VerifyIL("C2.Main2", <![CDATA[ { // Code size 25 (0x19) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldflda "C2.X As C1" IL_0006: dup IL_0007: ldc.i4.s 123 IL_0009: stfld "C1.field As Integer" IL_000e: ldobj "C1" IL_0013: call "Sub program.ExtMeth(C1)" IL_0018: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithStructureLValueAndExtensionMethod3() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Runtime.CompilerServices Structure C1 Public field As Integer Public Property GooProp As Integer End Structure Class C2 Public X As New C1() Public Sub Main2() With X Dim val = 123 Dim _sub As Action = Sub() .field = val .ExtMeth End Sub _sub() End With End Sub Public Shared Sub Main() Call New C2().Main2() End Sub End Class Module program &lt;ExtensionAttribute&gt; Sub ExtMeth(this As C1) Console.Write(this.field) End Sub End Module </file> </compilation>, expectedOutput:="123") c.VerifyDiagnostics() c.VerifyIL("C2.Main2", <![CDATA[ { // Code size 37 (0x25) .maxstack 3 IL_0000: newobj "Sub C2._Closure$__2-0..ctor()" IL_0005: dup IL_0006: ldarg.0 IL_0007: stfld "C2._Closure$__2-0.$VB$Me As C2" IL_000c: dup IL_000d: ldc.i4.s 123 IL_000f: stfld "C2._Closure$__2-0.$VB$Local_val As Integer" IL_0014: ldftn "Sub C2._Closure$__2-0._Lambda$__0()" IL_001a: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_001f: callvirt "Sub System.Action.Invoke()" IL_0024: ret } ]]>) c.VerifyIL("C2._Closure$__2-0._Lambda$__0", <![CDATA[ { // Code size 39 (0x27) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld "C2._Closure$__2-0.$VB$Me As C2" IL_0006: ldflda "C2.X As C1" IL_000b: ldarg.0 IL_000c: ldfld "C2._Closure$__2-0.$VB$Local_val As Integer" IL_0011: stfld "C1.field As Integer" IL_0016: ldarg.0 IL_0017: ldfld "C2._Closure$__2-0.$VB$Me As C2" IL_001c: ldfld "C2.X As C1" IL_0021: call "Sub program.ExtMeth(C1)" IL_0026: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithStructRValue() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Structure SSS Public Sub New(i As Integer) End Sub Public Function M() As String Return Me.GetType().ToString() End Function End Structure Sub Main(args As String()) With New SSS(1) Dim a = .M() Console.WriteLine(a.ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="Program+SSS") c.VerifyDiagnostics() c.VerifyIL("Program.Main", <![CDATA[ { // Code size 26 (0x1a) .maxstack 2 .locals init (Program.SSS V_0) //$W0 IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: call "Sub Program.SSS..ctor(Integer)" IL_0008: ldloca.s V_0 IL_000a: call "Function Program.SSS.M() As String" IL_000f: callvirt "Function String.ToString() As String" IL_0014: call "Sub System.Console.WriteLine(String)" IL_0019: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithStructRValueAndCleanup() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Structure SSSS Private S As String End Structure Structure SSS Public Sub New(i As Integer) End Sub Private A As SSSS Public Function M() As String Return Me.GetType().ToString() End Function End Structure Sub Main(args As String()) With New SSS(1) Dim a = .M() Console.WriteLine(a.ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="Program+SSS"). VerifyDiagnostics(). VerifyIL("Program.Main", <![CDATA[ { // Code size 34 (0x22) .maxstack 2 .locals init (Program.SSS V_0) //$W0 IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: call "Sub Program.SSS..ctor(Integer)" IL_0008: ldloca.s V_0 IL_000a: call "Function Program.SSS.M() As String" IL_000f: callvirt "Function String.ToString() As String" IL_0014: call "Sub System.Console.WriteLine(String)" IL_0019: ldloca.s V_0 IL_001b: initobj "Program.SSS" IL_0021: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithMutatingStructRValue() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C2 Structure SSS Public F As Integer Public Sub SetF(f As Integer) Me.F = f End Sub End Structure Public Shared Sub Main(args() As String) With New SSS .SetF(1) Console.Write(.F) .SetF(2) Console.Write(.F) End With End Sub End Class </file> </compilation>, expectedOutput:="12"). VerifyDiagnostics(). VerifyIL("C2.Main", <![CDATA[ { // Code size 47 (0x2f) .maxstack 2 .locals init (C2.SSS V_0) //$W0 IL_0000: ldloca.s V_0 IL_0002: initobj "C2.SSS" IL_0008: ldloca.s V_0 IL_000a: ldc.i4.1 IL_000b: call "Sub C2.SSS.SetF(Integer)" IL_0010: ldloc.0 IL_0011: ldfld "C2.SSS.F As Integer" IL_0016: call "Sub System.Console.Write(Integer)" IL_001b: ldloca.s V_0 IL_001d: ldc.i4.2 IL_001e: call "Sub C2.SSS.SetF(Integer)" IL_0023: ldloc.0 IL_0024: ldfld "C2.SSS.F As Integer" IL_0029: call "Sub System.Console.Write(Integer)" IL_002e: ret } ]]>) End Sub <Fact()> Public Sub TestWithInsideUsingOfStructureValue() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure STRUCT Implements IDisposable Public C As String Public D As Integer Public Sub Dispose() Implements IDisposable.Dispose End Sub End Structure Class Clazz Public Shared Sub Main(args() As String) Using s = New STRUCT() With s Goo(.D) End With Console.Write(s.D) End Using End Sub Public Shared Sub Goo(ByRef x As Integer) x = 123 End Sub End Class </file> </compilation>, expectedOutput:="0"). VerifyDiagnostics(Diagnostic(ERRID.WRN_MutableStructureInUsing, "s = New STRUCT()").WithArguments("s")). VerifyIL("Clazz.Main", <![CDATA[ { // Code size 50 (0x32) .maxstack 1 .locals init (STRUCT V_0, //s Integer V_1) IL_0000: ldloca.s V_0 IL_0002: initobj "STRUCT" .try { IL_0008: ldloc.0 IL_0009: ldfld "STRUCT.D As Integer" IL_000e: stloc.1 IL_000f: ldloca.s V_1 IL_0011: call "Sub Clazz.Goo(ByRef Integer)" IL_0016: ldloc.0 IL_0017: ldfld "STRUCT.D As Integer" IL_001c: call "Sub System.Console.Write(Integer)" IL_0021: leave.s IL_0031 } finally { IL_0023: ldloca.s V_0 IL_0025: constrained. "STRUCT" IL_002b: callvirt "Sub System.IDisposable.Dispose()" IL_0030: endfinally } IL_0031: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithStructLValue() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Structure SSS Public Sub New(i As Integer) End Sub Public Function M() As String Return Me.GetType().ToString() End Function End Structure Sub Main(args As String()) Dim s1 As New SSS(1) With s1 Dim a = .M() Console.WriteLine(a.ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="Program+SSS"). VerifyDiagnostics(). VerifyIL("Program.Main", <![CDATA[ { // Code size 26 (0x1a) .maxstack 2 .locals init (Program.SSS V_0) //s1 IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: call "Sub Program.SSS..ctor(Integer)" IL_0008: ldloca.s V_0 IL_000a: call "Function Program.SSS.M() As String" IL_000f: callvirt "Function String.ToString() As String" IL_0014: call "Sub System.Console.WriteLine(String)" IL_0019: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithStructLValue2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Structure SSS Public Sub New(i As Integer) End Sub Public Function M() As String Return Me.GetType().ToString() End Function End Structure Sub Main(args As String()) Test(New SSS(1)) End Sub Sub Test(s1 As SSS) With s1 Dim a = .M() Console.WriteLine(a.ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="Program+SSS"). VerifyDiagnostics(). VerifyIL("Program.Test", <![CDATA[ { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarga.s V_0 IL_0002: call "Function Program.SSS.M() As String" IL_0007: callvirt "Function String.ToString() As String" IL_000c: call "Sub System.Console.WriteLine(String)" IL_0011: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithStructLValue3() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Structure SSS Public Sub New(i As Integer) End Sub Public Function M() As String Return Me.GetType().ToString() End Function End Structure Public s1 As New SSS(1) Sub Main(args As String()) With s1 Dim a = .M() Console.WriteLine(a.ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="Program+SSS"). VerifyDiagnostics(). VerifyIL("Program.Main", <![CDATA[ { // Code size 21 (0x15) .maxstack 1 IL_0000: ldsflda "Program.s1 As Program.SSS" IL_0005: call "Function Program.SSS.M() As String" IL_000a: callvirt "Function String.ToString() As String" IL_000f: call "Sub System.Console.WriteLine(String)" IL_0014: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithMutatingStructLValue() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C2 Structure SSS Public F As Integer Public Sub SetF(f As Integer) Me.F = f End Sub End Structure Public Shared Sub Main(args() As String) Dim sss As New SSS With sss .SetF(1) Console.Write(.F) .SetF(2) Console.Write(.F) End With End Sub End Class </file> </compilation>, expectedOutput:="12"). VerifyDiagnostics(). VerifyIL("C2.Main", <![CDATA[ { // Code size 47 (0x2f) .maxstack 2 .locals init (C2.SSS V_0) //sss IL_0000: ldloca.s V_0 IL_0002: initobj "C2.SSS" IL_0008: ldloca.s V_0 IL_000a: ldc.i4.1 IL_000b: call "Sub C2.SSS.SetF(Integer)" IL_0010: ldloc.0 IL_0011: ldfld "C2.SSS.F As Integer" IL_0016: call "Sub System.Console.Write(Integer)" IL_001b: ldloca.s V_0 IL_001d: ldc.i4.2 IL_001e: call "Sub C2.SSS.SetF(Integer)" IL_0023: ldloc.0 IL_0024: ldfld "C2.SSS.F As Integer" IL_0029: call "Sub System.Console.Write(Integer)" IL_002e: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithMutatingStructLValue2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C2 Structure SSS Public F As Integer Public Sub SetF(f As Integer) Me.F = f End Sub End Structure Public Shared _sss As New SSS Public Shared Sub Main(args() As String) With _sss .SetF(1) Console.Write(.F) .SetF(2) Console.Write(.F) End With End Sub End Class </file> </compilation>, expectedOutput:="12"). VerifyDiagnostics(). VerifyIL("C2.Main", <![CDATA[ { // Code size 41 (0x29) .maxstack 3 IL_0000: ldsflda "C2._sss As C2.SSS" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: call "Sub C2.SSS.SetF(Integer)" IL_000c: dup IL_000d: ldfld "C2.SSS.F As Integer" IL_0012: call "Sub System.Console.Write(Integer)" IL_0017: dup IL_0018: ldc.i4.2 IL_0019: call "Sub C2.SSS.SetF(Integer)" IL_001e: ldfld "C2.SSS.F As Integer" IL_0023: call "Sub System.Console.Write(Integer)" IL_0028: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithStructArrayLValue() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Structure SSS Public Sub New(i As Integer) End Sub Public Function M() As String Return Me.GetType().ToString() End Function End Structure Sub Main(args As String()) Dim s1(100) As SSS With s1("123".Length) Dim a = .M() Console.WriteLine(a.ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="Program+SSS") c.VerifyDiagnostics() c.VerifyIL("Program.Main", <![CDATA[ { // Code size 38 (0x26) .maxstack 2 IL_0000: ldc.i4.s 101 IL_0002: newarr "Program.SSS" IL_0007: ldstr "123" IL_000c: call "Function String.get_Length() As Integer" IL_0011: ldelema "Program.SSS" IL_0016: call "Function Program.SSS.M() As String" IL_001b: callvirt "Function String.ToString() As String" IL_0020: call "Sub System.Console.WriteLine(String)" IL_0025: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithTypeParameterRValue() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C(Of T) Public Shared Sub M() With TProp Dim a = .GetType() Console.WriteLine(a.ToString()) End With End Sub Shared Public Property TProp As T End Class Module Program Sub Main(args As String()) C(Of Date).M() End Sub End Module </file> </compilation>, expectedOutput:="System.DateTime"). VerifyDiagnostics(). VerifyIL("C(Of T).M", <![CDATA[ { // Code size 38 (0x26) .maxstack 1 .locals init (T V_0) //$W0 IL_0000: call "Function C(Of T).get_TProp() As T" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: constrained. "T" IL_000e: callvirt "Function Object.GetType() As System.Type" IL_0013: callvirt "Function System.Type.ToString() As String" IL_0018: call "Sub System.Console.WriteLine(String)" IL_001d: ldloca.s V_0 IL_001f: initobj "T" IL_0025: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithTypeParameterRValue2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C(Of T As New) Public Shared Sub M() With New T Dim a = .GetType() Console.WriteLine(a.ToString()) End With End Sub End Class Module Program Sub Main(args As String()) C(Of Date).M() End Sub End Module </file> </compilation>, expectedOutput:="System.DateTime"). VerifyDiagnostics(). VerifyIL("C(Of T).M", <![CDATA[ { // Code size 38 (0x26) .maxstack 1 .locals init (T V_0) //$W0 IL_0000: call "Function System.Activator.CreateInstance(Of T)() As T" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: constrained. "T" IL_000e: callvirt "Function Object.GetType() As System.Type" IL_0013: callvirt "Function System.Type.ToString() As String" IL_0018: call "Sub System.Console.WriteLine(String)" IL_001d: ldloca.s V_0 IL_001f: initobj "T" IL_0025: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithTypeParameterLValue() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C(Of T As New) Public Shared Sub M() Dim t As New T With t Dim a = .GetType() Console.WriteLine(a.ToString()) End With End Sub End Class Module Program Sub Main(args As String()) C(Of Date).M() End Sub End Module </file> </compilation>, expectedOutput:="System.DateTime"). VerifyDiagnostics(). VerifyIL("C(Of T).M", <![CDATA[ { // Code size 30 (0x1e) .maxstack 1 .locals init (T V_0) //t IL_0000: call "Function System.Activator.CreateInstance(Of T)() As T" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: constrained. "T" IL_000e: callvirt "Function Object.GetType() As System.Type" IL_0013: callvirt "Function System.Type.ToString() As String" IL_0018: call "Sub System.Console.WriteLine(String)" IL_001d: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithTypeParameterArrayLValue() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C(Of T As New) Public Shared Sub M() Dim t(10) As T With t("123".Length) Dim a = .GetType() Console.Write(a.ToString()) If a IsNot Nothing Then Console.WriteLine(.GetHashCode()) End If End With End Sub End Class Module Program Sub Main(args As String()) C(Of Date).M() End Sub End Module </file> </compilation>, expectedOutput:="System.DateTime0"). VerifyDiagnostics(). VerifyIL("C(Of T).M", <![CDATA[ { // Code size 80 (0x50) .maxstack 2 .locals init (T() V_0, //$W0 Integer V_1) //$W1 IL_0000: ldc.i4.s 11 IL_0002: newarr "T" IL_0007: stloc.0 IL_0008: ldstr "123" IL_000d: call "Function String.get_Length() As Integer" IL_0012: stloc.1 IL_0013: ldloc.0 IL_0014: ldloc.1 IL_0015: readonly. IL_0017: ldelema "T" IL_001c: constrained. "T" IL_0022: callvirt "Function Object.GetType() As System.Type" IL_0027: dup IL_0028: callvirt "Function System.Type.ToString() As String" IL_002d: call "Sub System.Console.Write(String)" IL_0032: brfalse.s IL_004d IL_0034: ldloc.0 IL_0035: ldloc.1 IL_0036: readonly. IL_0038: ldelema "T" IL_003d: constrained. "T" IL_0043: callvirt "Function Object.GetHashCode() As Integer" IL_0048: call "Sub System.Console.WriteLine(Integer)" IL_004d: ldnull IL_004e: stloc.0 IL_004f: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithAnonymousType() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim a = New With {.a = 1, .b="text"} With a .a = 123 Console.WriteLine(.a &amp; .b) End With End Sub End Module </file> </compilation>, expectedOutput:="123text") c.VerifyDiagnostics() c.VerifyIL("Program.Main", <![CDATA[ { // Code size 50 (0x32) .maxstack 2 .locals init (VB$AnonymousType_0(Of Integer, String) V_0) //$W0 IL_0000: ldc.i4.1 IL_0001: ldstr "text" IL_0006: newobj "Sub VB$AnonymousType_0(Of Integer, String)..ctor(Integer, String)" IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: ldc.i4.s 123 IL_000f: callvirt "Sub VB$AnonymousType_0(Of Integer, String).set_a(Integer)" IL_0014: ldloc.0 IL_0015: callvirt "Function VB$AnonymousType_0(Of Integer, String).get_a() As Integer" IL_001a: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String" IL_001f: ldloc.0 IL_0020: callvirt "Function VB$AnonymousType_0(Of Integer, String).get_b() As String" IL_0025: call "Function String.Concat(String, String) As String" IL_002a: call "Sub System.Console.WriteLine(String)" IL_002f: ldnull IL_0030: stloc.0 IL_0031: ret } ]]>) End Sub <Fact()> Public Sub TestNestedWithWithAnonymousType() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) With New With {.a = 1, .b= New With { Key .x = "---", .y="text"} } Console.Write(.ToString()) Console.Write("|") With .b Console.Write(.ToString()) End With End With End Sub End Module </file> </compilation>, expectedOutput:="{ a = 1, b = { x = ---, y = text } }|{ x = ---, y = text }"). VerifyDiagnostics(). VerifyIL("Program.Main", <![CDATA[ { // Code size 62 (0x3e) .maxstack 3 IL_0000: ldc.i4.1 IL_0001: ldstr "---" IL_0006: ldstr "text" IL_000b: newobj "Sub VB$AnonymousType_1(Of String, String)..ctor(String, String)" IL_0010: newobj "Sub VB$AnonymousType_0(Of Integer, <anonymous type: Key x As String, y As String>)..ctor(Integer, <anonymous type: Key x As String, y As String>)" IL_0015: dup IL_0016: callvirt "Function VB$AnonymousType_0(Of Integer, <anonymous type: Key x As String, y As String>).ToString() As String" IL_001b: call "Sub System.Console.Write(String)" IL_0020: ldstr "|" IL_0025: call "Sub System.Console.Write(String)" IL_002a: callvirt "Function VB$AnonymousType_0(Of Integer, <anonymous type: Key x As String, y As String>).get_b() As <anonymous type: Key x As String, y As String>" IL_002f: callvirt "Function VB$AnonymousType_1(Of String, String).ToString() As String" IL_0034: call "Sub System.Console.Write(String)" IL_0039: ldnull IL_003a: pop IL_003b: ldnull IL_003c: pop IL_003d: ret } ]]>) End Sub <Fact()> Public Sub TestWithStatement() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C Structure S Public S() As SS End Structure Structure SS Public s As SSS End Structure Structure SSS Public F As Integer Public Overrides Function ToString() As String Return "Hello, " &amp; Me.F End Function End Structure Public Shared Sub Main(args() As String) Dim s(10) As S With s("1".Length) .S = New SS(2) {} End With With s("1".Length).S(1).s .F = 123 End With Console.Write(s(1).S(1).s) End Sub End Class </file> </compilation>, expectedOutput:="Hello, 123").VerifyDiagnostics() End Sub <Fact()> Public Sub TestWithStatement_MyClass() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure Clazz Structure SS Public FLD As String End Structure Public FLD As SS Sub TEST() With MyClass.FLD Console.Write(.GetType().ToString()) End With End Sub Public Shared Sub Main(args() As String) Call New Clazz().TEST() End Sub End Structure </file> </compilation>, expectedOutput:="Clazz+SS").VerifyDiagnostics() End Sub <Fact()> Public Sub TestWithStatement_MyBase() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class Clazz Public Structure SS Public FLD As String End Structure Public FLD As SS End Class Class Derived Inherits Clazz Sub TEST() With MyBase.FLD Console.Write(.GetType().ToString()) End With End Sub Public Shared Sub Main(args() As String) Call New Derived().TEST() End Sub End Class </file> </compilation>, expectedOutput:="Clazz+SS").VerifyDiagnostics() End Sub <Fact()> Public Sub TestSimpleWithWithMeReference_Class() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C2 Public A As Integer Public B As Date Public C As String Public Sub New() With Me .A = 1 .B = #1/2/2003# .C = "!" End With End Sub Public Overrides Function ToString() As String Return ".A = " &amp; Me.A &amp; "; .B = " &amp; Me.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) &amp; "; .C = " &amp; Me.C End Function Public Shared Sub Main(args() As String) Console.Write(New C2().ToString()) End Sub End Class </file> </compilation>, expectedOutput:=".A = 1; .B = 1/2/2003; .C = !"). VerifyDiagnostics(). VerifyIL("C2..ctor", <![CDATA[ { // Code size 45 (0x2d) .maxstack 2 IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: ldc.i4.1 IL_0008: stfld "C2.A As Integer" IL_000d: ldarg.0 IL_000e: ldc.i8 0x8c48009070c0000 IL_0017: newobj "Sub Date..ctor(Long)" IL_001c: stfld "C2.B As Date" IL_0021: ldarg.0 IL_0022: ldstr "!" IL_0027: stfld "C2.C As String" IL_002c: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithMeReference_Struct() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure C2 Public A As Integer Public B As Date Public C As String Public Sub New(i As Integer) With Me .A = 1 .B = #1/2/2003# .C = "!" End With End Sub Public Overrides Function ToString() As String Return ".A = " &amp; Me.A &amp; "; .B = " &amp; Me.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) &amp; "; .C = " &amp; Me.C End Function Public Shared Sub Main(args() As String) Console.Write(New C2(1).ToString()) End Sub End Structure </file> </compilation>, expectedOutput:=".A = 1; .B = 1/2/2003; .C = !"). VerifyDiagnostics(). VerifyIL("C2..ctor", <![CDATA[ { // Code size 46 (0x2e) .maxstack 2 IL_0000: ldarg.0 IL_0001: initobj "C2" IL_0007: ldarg.0 IL_0008: ldc.i4.1 IL_0009: stfld "C2.A As Integer" IL_000e: ldarg.0 IL_000f: ldc.i8 0x8c48009070c0000 IL_0018: newobj "Sub Date..ctor(Long)" IL_001d: stfld "C2.B As Date" IL_0022: ldarg.0 IL_0023: ldstr "!" IL_0028: stfld "C2.C As String" IL_002d: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithMeReference_Class_Capture() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C2 Public A As Integer Public B As Date Public C As String Public Sub New() With Me .A = 1 Dim a As Action = Sub() .B = #1/2/2003# .C = "!" End Sub a() End With End Sub Public Overrides Function ToString() As String Return ".A = " &amp; Me.A &amp; "; .B = " &amp; Me.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) &amp; "; .C = " &amp; Me.C End Function Public Shared Sub Main(args() As String) Console.Write(New C2().ToString()) End Sub End Class </file> </compilation>, expectedOutput:=".A = 1; .B = 1/2/2003; .C = !") c.VerifyDiagnostics() c.VerifyIL("C2..ctor", <![CDATA[ { // Code size 31 (0x1f) .maxstack 2 IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: ldc.i4.1 IL_0008: stfld "C2.A As Integer" IL_000d: ldarg.0 IL_000e: ldftn "Sub C2._Lambda$__3-0()" IL_0014: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_0019: callvirt "Sub System.Action.Invoke()" IL_001e: ret } ]]>) c.VerifyIL("C2._Lambda$__3-0", <![CDATA[ { // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i8 0x8c48009070c0000 IL_000a: newobj "Sub Date..ctor(Long)" IL_000f: stfld "C2.B As Date" IL_0014: ldarg.0 IL_0015: ldstr "!" IL_001a: stfld "C2.C As String" IL_001f: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWith_LiftedStructLValue() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure C2 Public _abc As ABC Structure ABC Public A As Integer Public B As Date Public C As String End Structure Public Sub New(i As ABC) With i .A = 1 Dim a As Action = Sub() .B = #1/2/2003# .C = "!" End Sub a() End With Me._abc = i End Sub Public Overrides Function ToString() As String Return ".A = " &amp; Me._abc.A &amp; "; .B = " &amp; Me._abc.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) &amp; "; .C = " &amp; Me._abc.C End Function Public Shared Sub Main(args() As String) Console.Write(New C2(Nothing).ToString()) End Sub End Structure </file> </compilation>, expectedOutput:=".A = 1; .B = 1/2/2003; .C = !") c.VerifyDiagnostics() c.VerifyIL("C2..ctor", <![CDATA[ { // Code size 62 (0x3e) .maxstack 2 .locals init (C2._Closure$__3-0 V_0) //$VB$Closure_0 IL_0000: newobj "Sub C2._Closure$__3-0..ctor()" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.1 IL_0008: stfld "C2._Closure$__3-0.$VB$Local_i As C2.ABC" IL_000d: ldarg.0 IL_000e: initobj "C2" IL_0014: ldloc.0 IL_0015: ldflda "C2._Closure$__3-0.$VB$Local_i As C2.ABC" IL_001a: ldc.i4.1 IL_001b: stfld "C2.ABC.A As Integer" IL_0020: ldloc.0 IL_0021: ldftn "Sub C2._Closure$__3-0._Lambda$__0()" IL_0027: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_002c: callvirt "Sub System.Action.Invoke()" IL_0031: ldarg.0 IL_0032: ldloc.0 IL_0033: ldfld "C2._Closure$__3-0.$VB$Local_i As C2.ABC" IL_0038: stfld "C2._abc As C2.ABC" IL_003d: ret } ]]>) c.VerifyIL("C2._Closure$__3-0._Lambda$__0", <![CDATA[ { // Code size 42 (0x2a) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda "C2._Closure$__3-0.$VB$Local_i As C2.ABC" IL_0006: ldc.i8 0x8c48009070c0000 IL_000f: newobj "Sub Date..ctor(Long)" IL_0014: stfld "C2.ABC.B As Date" IL_0019: ldarg.0 IL_001a: ldflda "C2._Closure$__3-0.$VB$Local_i As C2.ABC" IL_001f: ldstr "!" IL_0024: stfld "C2.ABC.C As String" IL_0029: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWith_LiftedStructLValue_Nested() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure C2 Public _abc As ABC Structure ABC Public A As Integer Public B As Date Public C As String End Structure Public Sub New(i As ABC) Dim b = Function() As ABC Dim x As New ABC With x .A = 1 Dim a As Action = Sub() .B = #1/2/2003# .C = "!" End Sub a() End With Return x End Function Me._abc = b() End Sub Public Overrides Function ToString() As String Return ".A = " &amp; Me._abc.A &amp; "; .B = " &amp; Me._abc.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) &amp; "; .C = " &amp; Me._abc.C End Function Public Shared Sub Main(args() As String) Console.Write(New C2(Nothing).ToString()) End Sub End Structure </file> </compilation>, expectedOutput:=".A = 1; .B = 1/2/2003; .C = !") c.VerifyDiagnostics() c.VerifyIL("C2..ctor", <![CDATA[ { // Code size 57 (0x39) .maxstack 2 .locals init (VB$AnonymousDelegate_0(Of C2.ABC) V_0) //b IL_0000: ldarg.0 IL_0001: initobj "C2" IL_0007: ldsfld "C2._Closure$__.$I3-0 As <generated method>" IL_000c: brfalse.s IL_0015 IL_000e: ldsfld "C2._Closure$__.$I3-0 As <generated method>" IL_0013: br.s IL_002b IL_0015: ldsfld "C2._Closure$__.$I As C2._Closure$__" IL_001a: ldftn "Function C2._Closure$__._Lambda$__3-0() As C2.ABC" IL_0020: newobj "Sub VB$AnonymousDelegate_0(Of C2.ABC)..ctor(Object, System.IntPtr)" IL_0025: dup IL_0026: stsfld "C2._Closure$__.$I3-0 As <generated method>" IL_002b: stloc.0 IL_002c: ldarg.0 IL_002d: ldloc.0 IL_002e: callvirt "Function VB$AnonymousDelegate_0(Of C2.ABC).Invoke() As C2.ABC" IL_0033: stfld "C2._abc As C2.ABC" IL_0038: ret } ]]>) c.VerifyIL("C2._Closure$__._Lambda$__3-0", <![CDATA[ { // Code size 52 (0x34) .maxstack 3 IL_0000: newobj "Sub C2._Closure$__3-0..ctor()" IL_0005: dup IL_0006: ldflda "C2._Closure$__3-0.$VB$Local_x As C2.ABC" IL_000b: initobj "C2.ABC" IL_0011: dup IL_0012: ldflda "C2._Closure$__3-0.$VB$Local_x As C2.ABC" IL_0017: ldc.i4.1 IL_0018: stfld "C2.ABC.A As Integer" IL_001d: dup IL_001e: ldftn "Sub C2._Closure$__3-0._Lambda$__1()" IL_0024: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_0029: callvirt "Sub System.Action.Invoke()" IL_002e: ldfld "C2._Closure$__3-0.$VB$Local_x As C2.ABC" IL_0033: ret } ]]>) c.VerifyIL("C2._Closure$__3-0._Lambda$__1", <![CDATA[ { // Code size 42 (0x2a) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda "C2._Closure$__3-0.$VB$Local_x As C2.ABC" IL_0006: ldc.i8 0x8c48009070c0000 IL_000f: newobj "Sub Date..ctor(Long)" IL_0014: stfld "C2.ABC.B As Date" IL_0019: ldarg.0 IL_001a: ldflda "C2._Closure$__3-0.$VB$Local_x As C2.ABC" IL_001f: ldstr "!" IL_0024: stfld "C2.ABC.C As String" IL_0029: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWith_LiftedStructLValueArrayElement() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure C2 Public _abc As ABC Structure ABC Public A As Integer Public B As Date Public C As String End Structure Private ARR() As ABC Public Sub New(i As ABC) ARR = New ABC(2) {} ARR(0).A = 1 With ARR(ARR(0).A) Dim b = Sub() .A = 2 Dim a As Action = Sub() .B = #6/6/2006# .C = "?" End Sub a() End Sub b() End With Print(ARR(1)) End Sub Public Sub Print(a As ABC) Console.Write("A = " &amp; a.A &amp; "; B = " &amp; a.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) &amp; "; C = " &amp; a.C) End Sub Public Shared Sub Main(args() As String) Dim a As New C2(Nothing) End Sub End Structure </file> </compilation>, expectedOutput:="A = 2; B = 6/6/2006; C = ?") c.VerifyDiagnostics() c.VerifyIL("C2..ctor", <![CDATA[ { // Code size 112 (0x70) .maxstack 4 IL_0000: ldarg.0 IL_0001: initobj "C2" IL_0007: ldarg.0 IL_0008: ldc.i4.3 IL_0009: newarr "C2.ABC" IL_000e: stfld "C2.ARR As C2.ABC()" IL_0013: ldarg.0 IL_0014: ldfld "C2.ARR As C2.ABC()" IL_0019: ldc.i4.0 IL_001a: ldelema "C2.ABC" IL_001f: ldc.i4.1 IL_0020: stfld "C2.ABC.A As Integer" IL_0025: newobj "Sub C2._Closure$__4-0..ctor()" IL_002a: dup IL_002b: ldarg.0 IL_002c: ldfld "C2.ARR As C2.ABC()" IL_0031: stfld "C2._Closure$__4-0.$W2 As C2.ABC()" IL_0036: dup IL_0037: ldarg.0 IL_0038: ldfld "C2.ARR As C2.ABC()" IL_003d: ldc.i4.0 IL_003e: ldelema "C2.ABC" IL_0043: ldfld "C2.ABC.A As Integer" IL_0048: stfld "C2._Closure$__4-0.$W3 As Integer" IL_004d: ldftn "Sub C2._Closure$__4-0._Lambda$__0()" IL_0053: newobj "Sub VB$AnonymousDelegate_0..ctor(Object, System.IntPtr)" IL_0058: callvirt "Sub VB$AnonymousDelegate_0.Invoke()" IL_005d: ldarg.0 IL_005e: ldarg.0 IL_005f: ldfld "C2.ARR As C2.ABC()" IL_0064: ldc.i4.1 IL_0065: ldelem "C2.ABC" IL_006a: call "Sub C2.Print(C2.ABC)" IL_006f: ret } ]]>) c.VerifyIL("C2._Closure$__4-0._Lambda$__0", <![CDATA[ { // Code size 66 (0x42) .maxstack 3 .locals init (System.Action V_0) IL_0000: ldarg.0 IL_0001: ldfld "C2._Closure$__4-0.$W2 As C2.ABC()" IL_0006: ldarg.0 IL_0007: ldfld "C2._Closure$__4-0.$W3 As Integer" IL_000c: ldelema "C2.ABC" IL_0011: ldc.i4.2 IL_0012: stfld "C2.ABC.A As Integer" IL_0017: ldarg.0 IL_0018: ldfld "C2._Closure$__4-0.$I1 As System.Action" IL_001d: brfalse.s IL_0027 IL_001f: ldarg.0 IL_0020: ldfld "C2._Closure$__4-0.$I1 As System.Action" IL_0025: br.s IL_003c IL_0027: ldarg.0 IL_0028: ldarg.0 IL_0029: ldftn "Sub C2._Closure$__4-0._Lambda$__1()" IL_002f: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_0034: dup IL_0035: stloc.0 IL_0036: stfld "C2._Closure$__4-0.$I1 As System.Action" IL_003b: ldloc.0 IL_003c: callvirt "Sub System.Action.Invoke()" IL_0041: ret } ]]>) c.VerifyIL("C2._Closure$__4-0._Lambda$__1", <![CDATA[ { // Code size 64 (0x40) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld "C2._Closure$__4-0.$W2 As C2.ABC()" IL_0006: ldarg.0 IL_0007: ldfld "C2._Closure$__4-0.$W3 As Integer" IL_000c: ldelema "C2.ABC" IL_0011: ldc.i8 0x8c8571349d14000 IL_001a: newobj "Sub Date..ctor(Long)" IL_001f: stfld "C2.ABC.B As Date" IL_0024: ldarg.0 IL_0025: ldfld "C2._Closure$__4-0.$W2 As C2.ABC()" IL_002a: ldarg.0 IL_002b: ldfld "C2._Closure$__4-0.$W3 As Integer" IL_0030: ldelema "C2.ABC" IL_0035: ldstr "?" IL_003a: stfld "C2.ABC.C As String" IL_003f: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWith_LiftedStructLValueArrayElement2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C2 Public _abc As ABC Structure ABC Public A As Integer Public B As Date Public C As String End Structure Private ARR() As ABC Public Sub S_TEST() ARR = New ABC(2) {} ARR(0).A = 1 Dim outer As Action = Sub() With ARR(ARR(0).A) Dim b = Sub() .A = 2 Dim a As Action = Sub() .B = #6/6/2006# .C = "?" End Sub a() End Sub b() End With End Sub outer() Print(ARR(1)) End Sub Public Sub Print(a As ABC) Console.Write("A = " &amp; a.A &amp; "; B = " &amp; a.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) &amp; "; C = " &amp; a.C) End Sub Public Shared Sub Main(args() As String) Dim a As New C2() a.S_TEST() End Sub End Class </file> </compilation>, expectedOutput:="A = 2; B = 6/6/2006; C = ?").VerifyDiagnostics() End Sub <Fact()> Public Sub TestSimpleWith_LiftedStructLValueFieldAccess() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C2 Structure ABC Public A As Integer Public B As Date Public C As String End Structure Private ARR As ABC Public Sub New() Dim sss As String = "?" With Me.ARR Dim b = Sub() .A = 2 Dim a As Action = Sub() .B = #6/6/2006# .C = sss End Sub a() End Sub b() End With Print(Me.ARR) End Sub Public Sub Print(a As ABC) Console.Write("A = " &amp; a.A &amp; "; B = " &amp; a.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) &amp; "; C = " &amp; a.C) End Sub Public Shared Sub Main(args() As String) Dim a As New C2() End Sub End Class </file> </compilation>, expectedOutput:="A = 2; B = 6/6/2006; C = ?") c.VerifyDiagnostics() c.VerifyIL("C2..ctor", <![CDATA[ { // Code size 58 (0x3a) .maxstack 3 IL_0000: newobj "Sub C2._Closure$__2-0..ctor()" IL_0005: ldarg.0 IL_0006: call "Sub Object..ctor()" IL_000b: dup IL_000c: ldarg.0 IL_000d: stfld "C2._Closure$__2-0.$VB$Me As C2" IL_0012: dup IL_0013: ldstr "?" IL_0018: stfld "C2._Closure$__2-0.$VB$Local_sss As String" IL_001d: ldftn "Sub C2._Closure$__2-0._Lambda$__0()" IL_0023: newobj "Sub VB$AnonymousDelegate_0..ctor(Object, System.IntPtr)" IL_0028: callvirt "Sub VB$AnonymousDelegate_0.Invoke()" IL_002d: ldarg.0 IL_002e: ldarg.0 IL_002f: ldfld "C2.ARR As C2.ABC" IL_0034: call "Sub C2.Print(C2.ABC)" IL_0039: ret } ]]>) c.VerifyIL("C2._Closure$__2-0._Lambda$__0", <![CDATA[ { // Code size 60 (0x3c) .maxstack 3 .locals init (System.Action V_0) IL_0000: ldarg.0 IL_0001: ldfld "C2._Closure$__2-0.$VB$Me As C2" IL_0006: ldflda "C2.ARR As C2.ABC" IL_000b: ldc.i4.2 IL_000c: stfld "C2.ABC.A As Integer" IL_0011: ldarg.0 IL_0012: ldfld "C2._Closure$__2-0.$I1 As System.Action" IL_0017: brfalse.s IL_0021 IL_0019: ldarg.0 IL_001a: ldfld "C2._Closure$__2-0.$I1 As System.Action" IL_001f: br.s IL_0036 IL_0021: ldarg.0 IL_0022: ldarg.0 IL_0023: ldftn "Sub C2._Closure$__2-0._Lambda$__1()" IL_0029: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_002e: dup IL_002f: stloc.0 IL_0030: stfld "C2._Closure$__2-0.$I1 As System.Action" IL_0035: ldloc.0 IL_0036: callvirt "Sub System.Action.Invoke()" IL_003b: ret } ]]>) c.VerifyIL("C2._Closure$__2-0._Lambda$__1", <![CDATA[ { // Code size 53 (0x35) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld "C2._Closure$__2-0.$VB$Me As C2" IL_0006: ldflda "C2.ARR As C2.ABC" IL_000b: ldc.i8 0x8c8571349d14000 IL_0014: newobj "Sub Date..ctor(Long)" IL_0019: stfld "C2.ABC.B As Date" IL_001e: ldarg.0 IL_001f: ldfld "C2._Closure$__2-0.$VB$Me As C2" IL_0024: ldflda "C2.ARR As C2.ABC" IL_0029: ldarg.0 IL_002a: ldfld "C2._Closure$__2-0.$VB$Local_sss As String" IL_002f: stfld "C2.ABC.C As String" IL_0034: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWith_LiftedStructLValueFieldAccess_Shared() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure C2 Structure ABC Public A As Integer Public B As Date Public C As String End Structure Private Shared ARR As ABC Public Sub New(i As Integer) With Me.ARR Dim b = Sub() Dim x = "?" .A = 2 Dim a As Action = Sub() .B = #6/6/2006# .C = x End Sub a() End Sub b() End With Print(C2.ARR) End Sub Public Sub Print(a As ABC) Console.Write("A = " &amp; a.A &amp; "; B = " &amp; a.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) &amp; "; C = " &amp; a.C) End Sub Public Shared Sub Main(args() As String) Dim a As New C2(0) End Sub End Structure </file> </compilation>, expectedOutput:="A = 2; B = 6/6/2006; C = ?") c.VerifyDiagnostics(Diagnostic(ERRID.WRN_SharedMemberThroughInstance, "Me.ARR")) c.VerifyIL("C2..ctor", <![CDATA[ { // Code size 60 (0x3c) .maxstack 2 IL_0000: ldarg.0 IL_0001: initobj "C2" IL_0007: ldsfld "C2._Closure$__.$I3-0 As <generated method>" IL_000c: brfalse.s IL_0015 IL_000e: ldsfld "C2._Closure$__.$I3-0 As <generated method>" IL_0013: br.s IL_002b IL_0015: ldsfld "C2._Closure$__.$I As C2._Closure$__" IL_001a: ldftn "Sub C2._Closure$__._Lambda$__3-0()" IL_0020: newobj "Sub VB$AnonymousDelegate_0..ctor(Object, System.IntPtr)" IL_0025: dup IL_0026: stsfld "C2._Closure$__.$I3-0 As <generated method>" IL_002b: callvirt "Sub VB$AnonymousDelegate_0.Invoke()" IL_0030: ldarg.0 IL_0031: ldsfld "C2.ARR As C2.ABC" IL_0036: call "Sub C2.Print(C2.ABC)" IL_003b: ret } ]]>) c.VerifyIL("C2._Closure$__._Lambda$__3-0", <![CDATA[ { // Code size 44 (0x2c) .maxstack 3 IL_0000: newobj "Sub C2._Closure$__3-0..ctor()" IL_0005: dup IL_0006: ldstr "?" IL_000b: stfld "C2._Closure$__3-0.$VB$Local_x As String" IL_0010: ldsflda "C2.ARR As C2.ABC" IL_0015: ldc.i4.2 IL_0016: stfld "C2.ABC.A As Integer" IL_001b: ldftn "Sub C2._Closure$__3-0._Lambda$__1()" IL_0021: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_0026: callvirt "Sub System.Action.Invoke()" IL_002b: ret } ]]>) c.VerifyIL("C2._Closure$__3-0._Lambda$__1", <![CDATA[ { // Code size 41 (0x29) .maxstack 2 IL_0000: ldsflda "C2.ARR As C2.ABC" IL_0005: ldc.i8 0x8c8571349d14000 IL_000e: newobj "Sub Date..ctor(Long)" IL_0013: stfld "C2.ABC.B As Date" IL_0018: ldsflda "C2.ARR As C2.ABC" IL_001d: ldarg.0 IL_001e: ldfld "C2._Closure$__3-0.$VB$Local_x As String" IL_0023: stfld "C2.ABC.C As String" IL_0028: ret } ]]>) End Sub <Fact()> Public Sub TestWithAndReadOnlyValueTypedFields() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure STRUCT Public C As String Public D As Integer End Structure Class Clazz Public Shared ReadOnly FLD1 As New STRUCT Public Shared FLD2 As New STRUCT Shared Sub New() Console.Write(FLD1.D) Console.Write(" ") Console.Write(FLD2.D) Console.Write(" ") With FLD1 Goo(.D, 1) End With With FLD2 Goo(.D, 1) End With Console.Write(FLD1.D) Console.Write(" ") Console.Write(FLD2.D) Console.Write(" ") End Sub Public Shared Sub Main(args() As String) With FLD1 Goo(.D, 2) End With With FLD2 Goo(.D, 2) End With Console.Write(FLD1.D) Console.Write(" ") Console.Write(FLD2.D) End Sub Public Shared Sub Goo(ByRef x As Integer, val As Integer) x = val End Sub End Class </file> </compilation>, expectedOutput:="0 0 1 1 1 2") End Sub <Fact()> Public Sub TestSimpleWith_ValueTypeLValueInParentheses() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure C2 Structure SSS Public A As Integer Public B As Date Public Sub SetA(_a As Integer) Me.A = _a End Sub End Structure Public Sub New(i As Integer) Dim a As New SSS With (a) .SetA(222) End With Console.Write(a.A) Console.Write(" ") With a .SetA(222) End With Console.Write(a.A) End Sub Public Shared Sub main(args() As String) Dim a As New C2(1) End Sub End Structure </file> </compilation>, expectedOutput:="0 222").VerifyDiagnostics() End Sub <Fact()> Public Sub TestWith_WithDisposableStruct_RValue() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure Struct Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Structure Structure Clazz Sub S() With New Struct .Dispose() End With End Sub End Structure </file> </compilation>). VerifyDiagnostics(). VerifyIL("Clazz.S", <![CDATA[ { // Code size 16 (0x10) .maxstack 1 .locals init (Struct V_0) //$W0 IL_0000: ldloca.s V_0 IL_0002: initobj "Struct" IL_0008: ldloca.s V_0 IL_000a: call "Sub Struct.Dispose()" IL_000f: ret } ]]>) End Sub <Fact()> Public Sub TestWith_WithDisposableStruct_LValue() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure Struct Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Structure Structure Clazz Sub S() Dim s As New Struct With s .Dispose() End With End Sub End Structure </file> </compilation>). VerifyDiagnostics(). VerifyIL("Clazz.S", <![CDATA[ { // Code size 16 (0x10) .maxstack 1 .locals init (Struct V_0) //s IL_0000: ldloca.s V_0 IL_0002: initobj "Struct" IL_0008: ldloca.s V_0 IL_000a: call "Sub Struct.Dispose()" IL_000f: ret } ]]>) End Sub <Fact()> Public Sub TestWith_Arrays() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Structure Clazz Shared Sub Main() With New Integer() {} Dim cnt = .Count Console.Write(cnt) End With End Sub End Structure </file> </compilation>, expectedOutput:="0"). VerifyDiagnostics(). VerifyIL("Clazz.Main", <![CDATA[ { // Code size 19 (0x13) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: newarr "Integer" IL_0006: call "Function System.Linq.Enumerable.Count(Of Integer)(System.Collections.Generic.IEnumerable(Of Integer)) As Integer" IL_000b: call "Sub System.Console.Write(Integer)" IL_0010: ldnull IL_0011: pop IL_0012: ret } ]]>) End Sub <Fact()> Public Sub TestWith_NestedWithWithInferredVarType() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure Struct Public A As String Public B As String End Structure Structure Clazz Public S As Struct Shared Sub TEST() Dim c = New Clazz With c .S = New Struct() .S.A = "" .S.B = .S.A With .S Dim a = .A Dim b = .B Console.Write(a.GetType()) Console.Write("|") Console.Write(b.GetType()) End With End With End Sub Shared Sub Main(args() As String) TEST() End Sub End Structure </file> </compilation>, expectedOutput:="System.String|System.String").VerifyDiagnostics() End Sub <Fact()> Public Sub TestWith_NestedWithWithInferredVarType2() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Structure Struct Public A As String Public B As String End Structure Structure Clazz Public S As Struct Shared Sub TEST() Dim c = New Clazz With c .S = New Struct() .S.A = "" .S.B = .S.A Dim a = New With {.y = New Struct(), .x = Sub() With .y Dim a = .A Dim b = .B End With End Sub} End With End Sub Shared Sub Main(args() As String) TEST() End Sub End Structure </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_CannotLiftAnonymousType1, ".y").WithArguments("y"), Diagnostic(ERRID.ERR_BlockLocalShadowing1, "a").WithArguments("a")) End Sub <Fact()> Public Sub TestWith_NestedWithWithInferredVarType3() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Structure Struct Public A As String Public B As String End Structure Structure Struct2 Public X As Struct Public Y As String End Structure Structure Clazz Shared Sub TEST() Dim c As Struct2 With c .Y = "" With .X .A = "" End With End With Console.Write(c) With c With .X .B = "" End With End With Console.WriteLine(c) End Sub End Structure </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "c").WithArguments("c")) End Sub <WorkItem(545120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545120")> <Fact()> Public Sub TestWith_NestedWithWithLambdasAndObjectInitializers() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Structure SS1 Public A As String Public B As String End Structure Structure SS2 Public X As SS1 Public Y As SS1 End Structure Structure Clazz Shared Sub Main(args() As String) Dim t As New Clazz(1) End Sub Public F As SS2 Sub New(i As Integer) F = New SS2() With F Dim a As New SS2() With {.X = Function() As SS1 With .Y .A = "xyz" End With Return .Y End Function.Invoke()} End With End Sub End Structure </file> </compilation>).VerifyDiagnostics() End Sub <Fact()> Public Sub TestWith_NestedWithWithQuery() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Structure Struct Public A As String Public B As String End Structure Class Clazz Structure SS Public FLD As Struct End Structure Public FLD As SS Sub TEST() With MyClass.FLD .FLD.A = "Success" Dim q = From x In "a" Select .FLD.A &amp; "=" &amp; x Console.Write(q.First()) End With End Sub Shared Sub Main(args() As String) Call New Clazz().TEST() End Sub End Class </file> </compilation>, expectedOutput:="Success=a").VerifyDiagnostics() End Sub <ConditionalFact(GetType(DesktopOnly), Reason:=ConditionalSkipReason.TestExecutionNeedsDesktopTypes)> Public Sub TestWith_MyBase() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Class Base Public Structure SS Public FLD As String End Structure Public FLD As SS End Class Class Clazz Inherits Base Public Shadows FLD As Integer Sub TEST() With MyBase.FLD Dim q = From x In "" Select .FLD Console.Write(q.GetType().ToString()) End With End Sub Shared Sub Main(args() As String) Call New Clazz().TEST() End Sub End Class </file> </compilation>, expectedOutput:="System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Char,System.String]") c.VerifyDiagnostics() c.VerifyIL("Clazz.TEST", <![CDATA[ { // Code size 38 (0x26) .maxstack 3 IL_0000: ldstr "" IL_0005: ldarg.0 IL_0006: ldftn "Function Clazz._Lambda$__2-0(Char) As String" IL_000c: newobj "Sub System.Func(Of Char, String)..ctor(Object, System.IntPtr)" IL_0011: call "Function System.Linq.Enumerable.Select(Of Char, String)(System.Collections.Generic.IEnumerable(Of Char), System.Func(Of Char, String)) As System.Collections.Generic.IEnumerable(Of String)" IL_0016: callvirt "Function Object.GetType() As System.Type" IL_001b: callvirt "Function System.Type.ToString() As String" IL_0020: call "Sub System.Console.Write(String)" IL_0025: ret } ]]>) c.VerifyIL("Clazz._Lambda$__2-0", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda "Base.FLD As Base.SS" IL_0006: ldfld "Base.SS.FLD As String" IL_000b: ret } ]]>) End Sub <Fact()> Public Sub TestWith_NestedWithWithQuery2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Structure Struct Public A As String Public B As String End Structure Class Clazz_Base Public Structure SS Public FLD As Struct End Structure Public FLD As SS End Class Class Clazz Inherits Clazz_Base Sub TEST() With MyBase.FLD .FLD.A = "Success" Dim q = From x In "a" Select .FLD.A &amp; "=" &amp; x Console.Write(q.First()) End With End Sub Shared Sub Main(args() As String) Call New Clazz().TEST() End Sub End Class </file> </compilation>, expectedOutput:="Success=a").VerifyDiagnostics() End Sub <Fact()> Public Sub TestWith_NestedWithWithQuery3() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Structure Struct Public A As String Public B As String End Structure Class Clazz_Base Public Structure SS Public FLD As Struct End Structure Public FLD As SS End Class Class Clazz Inherits Clazz_Base Sub TEST() With MyBase.FLD Dim _sub As Action = Sub() .FLD.A = "Success" End Sub _sub() Dim q = From x In "a" Select .FLD.A &amp; "=" &amp; x Console.Write(q.First()) End With End Sub Shared Sub Main(args() As String) Call New Clazz().TEST() End Sub End Class </file> </compilation>, expectedOutput:="Success=a").VerifyDiagnostics() End Sub <Fact()> Public Sub TestWith_NestedWithWithQuery4() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Structure STRUCT Public C As String Public D As Integer End Structure Class Clazz Public Shared Sub Main(args() As String) Dim source(10) As STRUCT Dim result = From x In source Select DirectCast(Function() With x Goo(.D) End With Return x End Function, Func(Of STRUCT))() Console.Write(result.FirstOrDefault.D) End Sub Public Shared Sub Goo(ByRef x As Integer) x = 123 End Sub End Class </file> </compilation>, expectedOutput:="0") c.VerifyDiagnostics() c.VerifyIL("Clazz._Closure$__1-0._Lambda$__1", <![CDATA[ { // Code size 26 (0x1a) .maxstack 1 .locals init (Integer V_0) IL_0000: ldarg.0 IL_0001: ldfld "Clazz._Closure$__1-0.$VB$Local_x As STRUCT" IL_0006: ldfld "STRUCT.D As Integer" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: call "Sub Clazz.Goo(ByRef Integer)" IL_0013: ldarg.0 IL_0014: ldfld "Clazz._Closure$__1-0.$VB$Local_x As STRUCT" IL_0019: ret } ]]>) End Sub <Fact()> Public Sub TestWith_PropertyAccess_Simple() CompileAndVerify( <compilation> <file name="a.vb"> Interface IBar Property F As Integer End Interface Structure Clazz Implements IBar Public Property F As Integer Implements IBar.F Sub S() With Me .F += 1 End With End Sub End Structure </file> </compilation>). VerifyDiagnostics(). VerifyIL("Clazz.S", <![CDATA[ { // Code size 15 (0xf) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: call "Function Clazz.get_F() As Integer" IL_0007: ldc.i4.1 IL_0008: add.ovf IL_0009: call "Sub Clazz.set_F(Integer)" IL_000e: ret } ]]>) End Sub <Fact()> Public Sub TestWith_DictionaryAccess_Simple() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure Clazz Sub TEST() Dim x As New Clazz With x Console.Write(!Success) !A = "aaa" End With End Sub Default Public Property F(s As String) As String Get Return s End Get Set(value As String) End Set End Property Shared Sub Main(args() As String) Call New Clazz().TEST() End Sub End Structure </file> </compilation>, expectedOutput:="Success"). VerifyDiagnostics(). VerifyIL("Clazz.TEST", <![CDATA[ { // Code size 43 (0x2b) .maxstack 3 .locals init (Clazz V_0) //x IL_0000: ldloca.s V_0 IL_0002: initobj "Clazz" IL_0008: ldloca.s V_0 IL_000a: ldstr "Success" IL_000f: call "Function Clazz.get_F(String) As String" IL_0014: call "Sub System.Console.Write(String)" IL_0019: ldloca.s V_0 IL_001b: ldstr "A" IL_0020: ldstr "aaa" IL_0025: call "Sub Clazz.set_F(String, String)" IL_002a: ret } ]]>) End Sub <Fact()> Public Sub TestWith_DictionaryAccess_ArrayAccess_Lambda() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure Clazz Sub TEST(x() As Clazz, i As Integer) With x(i - 5) Console.Write(!Success) Console.Write(" ") Dim _sub As Action = Sub() Console.Write(!Lambda) End Sub _sub() End With End Sub Default Public Property F(s As String) As String Get Return s End Get Set(value As String) End Set End Property Shared Sub Main(args() As String) Call New Clazz().TEST(New Clazz() {New Clazz}, 5) End Sub End Structure </file> </compilation>, expectedOutput:="Success Lambda") c.VerifyDiagnostics() c.VerifyIL("Clazz.TEST", <![CDATA[ { // Code size 82 (0x52) .maxstack 3 .locals init (Clazz._Closure$__1-0 V_0) //$VB$Closure_0 IL_0000: newobj "Sub Clazz._Closure$__1-0..ctor()" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.1 IL_0008: stfld "Clazz._Closure$__1-0.$W2 As Clazz()" IL_000d: ldloc.0 IL_000e: ldarg.2 IL_000f: ldc.i4.5 IL_0010: sub.ovf IL_0011: stfld "Clazz._Closure$__1-0.$W3 As Integer" IL_0016: ldloc.0 IL_0017: ldfld "Clazz._Closure$__1-0.$W2 As Clazz()" IL_001c: ldloc.0 IL_001d: ldfld "Clazz._Closure$__1-0.$W3 As Integer" IL_0022: ldelema "Clazz" IL_0027: ldstr "Success" IL_002c: call "Function Clazz.get_F(String) As String" IL_0031: call "Sub System.Console.Write(String)" IL_0036: ldstr " " IL_003b: call "Sub System.Console.Write(String)" IL_0040: ldloc.0 IL_0041: ldftn "Sub Clazz._Closure$__1-0._Lambda$__0()" IL_0047: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_004c: callvirt "Sub System.Action.Invoke()" IL_0051: ret } ]]>) c.VerifyIL("Clazz._Closure$__1-0._Lambda$__0", <![CDATA[ { // Code size 33 (0x21) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld "Clazz._Closure$__1-0.$W2 As Clazz()" IL_0006: ldarg.0 IL_0007: ldfld "Clazz._Closure$__1-0.$W3 As Integer" IL_000c: ldelema "Clazz" IL_0011: ldstr "Lambda" IL_0016: call "Function Clazz.get_F(String) As String" IL_001b: call "Sub System.Console.Write(String)" IL_0020: ret } ]]>) End Sub <Fact()> Public Sub TestWith_MemberAccess_ArrayAccess_Lambda() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure Clazz Sub TEST(x() As Clazz, i As Integer) With x(i - 5) Console.Write(.F("Success")) Console.Write(" ") Dim _sub As Action = Sub() Console.Write(.F("Lambda")) End Sub _sub() End With End Sub Default Public Property F(s As String) As String Get Return s End Get Set(value As String) End Set End Property Shared Sub Main(args() As String) Call New Clazz().TEST(New Clazz() {New Clazz}, 5) End Sub End Structure </file> </compilation>, expectedOutput:="Success Lambda") c.VerifyDiagnostics() c.VerifyIL("Clazz.TEST", <![CDATA[ { // Code size 82 (0x52) .maxstack 3 .locals init (Clazz._Closure$__1-0 V_0) //$VB$Closure_0 IL_0000: newobj "Sub Clazz._Closure$__1-0..ctor()" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.1 IL_0008: stfld "Clazz._Closure$__1-0.$W2 As Clazz()" IL_000d: ldloc.0 IL_000e: ldarg.2 IL_000f: ldc.i4.5 IL_0010: sub.ovf IL_0011: stfld "Clazz._Closure$__1-0.$W3 As Integer" IL_0016: ldloc.0 IL_0017: ldfld "Clazz._Closure$__1-0.$W2 As Clazz()" IL_001c: ldloc.0 IL_001d: ldfld "Clazz._Closure$__1-0.$W3 As Integer" IL_0022: ldelema "Clazz" IL_0027: ldstr "Success" IL_002c: call "Function Clazz.get_F(String) As String" IL_0031: call "Sub System.Console.Write(String)" IL_0036: ldstr " " IL_003b: call "Sub System.Console.Write(String)" IL_0040: ldloc.0 IL_0041: ldftn "Sub Clazz._Closure$__1-0._Lambda$__0()" IL_0047: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_004c: callvirt "Sub System.Action.Invoke()" IL_0051: ret } ]]>) c.VerifyIL("Clazz._Closure$__1-0._Lambda$__0", <![CDATA[ { // Code size 33 (0x21) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld "Clazz._Closure$__1-0.$W2 As Clazz()" IL_0006: ldarg.0 IL_0007: ldfld "Clazz._Closure$__1-0.$W3 As Integer" IL_000c: ldelema "Clazz" IL_0011: ldstr "Lambda" IL_0016: call "Function Clazz.get_F(String) As String" IL_001b: call "Sub System.Console.Write(String)" IL_0020: ret } ]]>) End Sub <Fact()> Public Sub TestWith_DictionaryAccess_NestedWithWithQuery() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Structure Clazz Public Str As String Public Sub New(_str As String) Me.Str = _str End Sub Sub TEST(x() As Clazz, i As Integer) With x(i - 5) With !One With !Two With !Three Console.Write(!Success.Str) Console.Write(" || ") Dim q = From z In "*" Select U = !Query.Str Console.Write(q.FirstOrDefault) End With End With End With End With End Sub Default Public Property F(s As String) As Clazz Get Return New Clazz(Me.Str &amp; " > " &amp; s) End Get Set(value As Clazz) End Set End Property Shared Sub Main(args() As String) Dim p = New Clazz(0) {} p(0) = New Clazz("##") Call New Clazz().TEST(p, 5) End Sub End Structure </file> </compilation>, expectedOutput:="## > One > Two > Three > Success || ## > One > Two > Three > Query") c.VerifyDiagnostics() c.VerifyIL("Clazz.TEST", <![CDATA[ { // Code size 142 (0x8e) .maxstack 3 .locals init (Clazz V_0, //$W0 Clazz V_1, //$W1 Clazz._Closure$__3-0 V_2) //$VB$Closure_2 IL_0000: ldarg.1 IL_0001: ldarg.2 IL_0002: ldc.i4.5 IL_0003: sub.ovf IL_0004: ldelema "Clazz" IL_0009: ldstr "One" IL_000e: call "Function Clazz.get_F(String) As Clazz" IL_0013: stloc.0 IL_0014: ldloca.s V_0 IL_0016: ldstr "Two" IL_001b: call "Function Clazz.get_F(String) As Clazz" IL_0020: stloc.1 IL_0021: newobj "Sub Clazz._Closure$__3-0..ctor()" IL_0026: stloc.2 IL_0027: ldloc.2 IL_0028: ldloca.s V_1 IL_002a: ldstr "Three" IL_002f: call "Function Clazz.get_F(String) As Clazz" IL_0034: stfld "Clazz._Closure$__3-0.$W2 As Clazz" IL_0039: ldloc.2 IL_003a: ldflda "Clazz._Closure$__3-0.$W2 As Clazz" IL_003f: ldstr "Success" IL_0044: call "Function Clazz.get_F(String) As Clazz" IL_0049: ldfld "Clazz.Str As String" IL_004e: call "Sub System.Console.Write(String)" IL_0053: ldstr " || " IL_0058: call "Sub System.Console.Write(String)" IL_005d: ldstr "*" IL_0062: ldloc.2 IL_0063: ldftn "Function Clazz._Closure$__3-0._Lambda$__0(Char) As String" IL_0069: newobj "Sub System.Func(Of Char, String)..ctor(Object, System.IntPtr)" IL_006e: call "Function System.Linq.Enumerable.Select(Of Char, String)(System.Collections.Generic.IEnumerable(Of Char), System.Func(Of Char, String)) As System.Collections.Generic.IEnumerable(Of String)" IL_0073: call "Function System.Linq.Enumerable.FirstOrDefault(Of String)(System.Collections.Generic.IEnumerable(Of String)) As String" IL_0078: call "Sub System.Console.Write(String)" IL_007d: ldloca.s V_1 IL_007f: initobj "Clazz" IL_0085: ldloca.s V_0 IL_0087: initobj "Clazz" IL_008d: ret } ]]>) c.VerifyIL("Clazz._Closure$__3-0._Lambda$__0", <![CDATA[ { // Code size 22 (0x16) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda "Clazz._Closure$__3-0.$W2 As Clazz" IL_0006: ldstr "Query" IL_000b: call "Function Clazz.get_F(String) As Clazz" IL_0010: ldfld "Clazz.Str As String" IL_0015: ret } ]]>) End Sub <Fact()> Public Sub TestWith_ByRefExtensionMethodOfLValuePlaceholder() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Runtime.CompilerServices Class C1 Public Field As Integer Public Sub New(p As Integer) Field = p End Sub End Class Module Program Sub Main(args As String()) With New C1(23) Console.WriteLine(.Field) .Goo() Console.WriteLine(.Field) End With End Sub &lt;Extension()&gt; Public Sub Goo(ByRef x As C1) x = New C1(42) Console.WriteLine(x.Field) End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>, expectedOutput:=<![CDATA[ 23 42 23 ]]>). VerifyDiagnostics() End Sub <Fact(), WorkItem(2640, "https://github.com/dotnet/roslyn/issues/2640")> Public Sub WithUnusedArrayElement() CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Private Structure MyStructure Public x As Single End Structure Sub Main() Dim unusedArrayInWith(0) As MyStructure With unusedArrayInWith(GetIndex()) System.Console.WriteLine("Hello, World") End With End Sub Function GetIndex() as Integer System.Console.WriteLine("GetIndex") Return 0 End Function End Module </file> </compilation>, options:=TestOptions.ReleaseExe, expectedOutput:=<![CDATA[ GetIndex Hello, World ]]>) End Sub <Fact()> <WorkItem(16968, "https://github.com/dotnet/roslyn/issues/16968")> Public Sub WithExpressionIsAccessedFromLambdaExecutedAfterTheBlock() CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Private f As EventOwner Sub Main() f = New EventOwner() With f AddHandler .Baz, Sub() .Bar = "called" End Sub End With f.RaiseBaz() System.Console.WriteLine(f.Bar) End Sub End Module Class EventOwner Public Property Bar As String Public Event Baz As System.Action Public Sub RaiseBaz() RaiseEvent Baz() End Sub End Class </file> </compilation>, expectedOutput:="called") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenWithBlock Inherits BasicTestBase <Fact()> Public Sub WithTestModuleField() CompileAndVerify( <compilation> <file name="a.vb"> Module ModuleWithField Public field1 As String = "a" End Module Module WithTestModuleField Sub Main() With field1 Dim l = .Length System.Console.WriteLine(.ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="a") End Sub <Fact()> Public Sub WithTestLineContinuation() CompileAndVerify( <compilation> <file name="a.vb"> Class Class1 Public Property Property1 As Class1 Public Property Property2 As String End Class Module WithTestLineContinuation Sub Main() With New Class1() .Property1 = New Class1() .Property1. Property1 = New Class1() .Property1 _ . Property1 _ .Property2 = "a" System.Console.WriteLine(.Property1 _ .Property1. Property2) End With End Sub End Module </file> </compilation>, expectedOutput:="a") End Sub <Fact()> Public Sub WithTestNested() CompileAndVerify( <compilation> <file name="a.vb"> Class Class2 Default Public ReadOnly Property Item(x As Integer) As Class2 Get Return New Class2 End Get End Property Public Property Property2 As String End Class Module WithTestNested Sub Main() Dim c2 As New Class2() With c2(3) .Property2 = "b" With .Item(4) .Property2 = "a" System.Console.Write(.Property2) End With System.Console.Write(.Property2) End With End Sub End Module </file> </compilation>, expectedOutput:="ab") End Sub <Fact()> Public Sub TestSimpleWithWithNothingLiteral() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Sub Main(args As String()) With Nothing End With End Sub End Module </file> </compilation>, expectedOutput:=""). VerifyDiagnostics(). VerifyIL("Program.Main", <![CDATA[ { // Code size 3 (0x3) .maxstack 1 IL_0000: ldnull IL_0001: pop IL_0002: ret } ]]>) End Sub <Fact()> Public Sub WithUnused() CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x(10) As S x(0).s = "hello" Dim s As String Dim dummy As Integer For i As Integer = 0 To 5 With x(i) s = .s dummy += .i End With Next End Sub Structure S Public s As String Public i As Integer End Structure End Module </file> </compilation>, expectedOutput:=""). VerifyDiagnostics(). VerifyIL("Module1.Main", <![CDATA[ { // Code size 53 (0x35) .maxstack 2 .locals init (Module1.S() V_0, //x Integer V_1, //dummy Integer V_2, //i Module1.S& V_3) //$W0 IL_0000: ldc.i4.s 11 IL_0002: newarr "Module1.S" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.0 IL_000a: ldelema "Module1.S" IL_000f: ldstr "hello" IL_0014: stfld "Module1.S.s As String" IL_0019: ldc.i4.0 IL_001a: stloc.2 IL_001b: ldloc.0 IL_001c: ldloc.2 IL_001d: ldelema "Module1.S" IL_0022: stloc.3 IL_0023: ldloc.1 IL_0024: ldloc.3 IL_0025: ldfld "Module1.S.i As Integer" IL_002a: add.ovf IL_002b: stloc.1 IL_002c: ldloc.2 IL_002d: ldc.i4.1 IL_002e: add.ovf IL_002f: stloc.2 IL_0030: ldloc.2 IL_0031: ldc.i4.5 IL_0032: ble.s IL_001b IL_0034: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithNothingLiteralAndExtensionMethod() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Runtime.CompilerServices Module Program Sub Main(args As String()) With Nothing Try .ExtMethod() Catch ex As NullReferenceException Console.WriteLine("Success") End Try End With End Sub End Module Module Ext &lt;ExtensionAttribute&gt; Sub ExtMeth(this As Object) End Sub End Module </file> </compilation>, expectedOutput:="Success").VerifyDiagnostics() End Sub <Fact()> Public Sub TestSimpleWithWithExtensionMethod() CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Runtime.CompilerServices Class C1 End Class Module Program Sub Main(args As String()) With New C1() .Goo() End With End Sub &lt;Extension()&gt; Public Sub Goo(ByRef x As C1) End Sub End Module </file> </compilation>, expectedOutput:=""). VerifyDiagnostics(). VerifyIL("Program.Main", <![CDATA[ { // Code size 16 (0x10) .maxstack 1 .locals init (C1 V_0) IL_0000: newobj "Sub C1..ctor()" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: call "Sub Program.Goo(ByRef C1)" IL_000d: ldnull IL_000e: pop IL_000f: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithStringLiteral() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) With "abc" Dim a = .GetType() Console.WriteLine(a.ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="System.String").VerifyDiagnostics() End Sub <Fact()> Public Sub TestSimpleWithWithStringExpression() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) With "abc|" + "cba".ToString() Console.WriteLine(.GetType().ToString() + ": " + .ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="System.String: abc|cba") c.VerifyDiagnostics() c.VerifyIL("Program.Main", <![CDATA[ { // Code size 56 (0x38) .maxstack 3 .locals init (String V_0) //$W0 IL_0000: ldstr "abc|" IL_0005: ldstr "cba" IL_000a: callvirt "Function String.ToString() As String" IL_000f: call "Function String.Concat(String, String) As String" IL_0014: stloc.0 IL_0015: ldloc.0 IL_0016: callvirt "Function Object.GetType() As System.Type" IL_001b: callvirt "Function System.Type.ToString() As String" IL_0020: ldstr ": " IL_0025: ldloc.0 IL_0026: callvirt "Function String.ToString() As String" IL_002b: call "Function String.Concat(String, String, String) As String" IL_0030: call "Sub System.Console.WriteLine(String)" IL_0035: ldnull IL_0036: stloc.0 IL_0037: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithStringArrayLValue() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim sss(10) As String sss(3) = "#3" With sss("123".Length) Console.WriteLine(.GetType().ToString() + ": " + .ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="System.String: #3"). VerifyDiagnostics(). VerifyIL("Program.Main", <![CDATA[ { // Code size 62 (0x3e) .maxstack 4 .locals init (String V_0) //$W0 IL_0000: ldc.i4.s 11 IL_0002: newarr "String" IL_0007: dup IL_0008: ldc.i4.3 IL_0009: ldstr "#3" IL_000e: stelem.ref IL_000f: ldstr "123" IL_0014: call "Function String.get_Length() As Integer" IL_0019: ldelem.ref IL_001a: stloc.0 IL_001b: ldloc.0 IL_001c: callvirt "Function Object.GetType() As System.Type" IL_0021: callvirt "Function System.Type.ToString() As String" IL_0026: ldstr ": " IL_002b: ldloc.0 IL_002c: callvirt "Function String.ToString() As String" IL_0031: call "Function String.Concat(String, String, String) As String" IL_0036: call "Sub System.Console.WriteLine(String)" IL_003b: ldnull IL_003c: stloc.0 IL_003d: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithNumericLiteral() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) With 1 Dim a = .GetType() Console.WriteLine(a.ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="System.Int32") c.VerifyDiagnostics() c.VerifyIL("Program.Main", <![CDATA[ { // Code size 24 (0x18) .maxstack 1 .locals init (Integer V_0) //$W0 IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: box "Integer" IL_0008: call "Function Object.GetType() As System.Type" IL_000d: callvirt "Function System.Type.ToString() As String" IL_0012: call "Sub System.Console.WriteLine(String)" IL_0017: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithNumericRValue() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) With IntProp Dim a = .GetType() Console.WriteLine(a.ToString()) End With End Sub Public Property IntProp As Integer End Module </file> </compilation>, expectedOutput:="System.Int32") c.VerifyDiagnostics() c.VerifyIL("Program.Main", <![CDATA[ { // Code size 28 (0x1c) .maxstack 1 .locals init (Integer V_0) //$W0 IL_0000: call "Function Program.get_IntProp() As Integer" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: box "Integer" IL_000c: call "Function Object.GetType() As System.Type" IL_0011: callvirt "Function System.Type.ToString() As String" IL_0016: call "Sub System.Console.WriteLine(String)" IL_001b: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithNumericLValue() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim i As Integer = 1 With i Dim a = .GetType() Console.WriteLine(a.ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="System.Int32"). VerifyDiagnostics(). VerifyIL("Program.Main", <![CDATA[ { // Code size 24 (0x18) .maxstack 1 .locals init (Integer V_0) //i IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: box "Integer" IL_0008: call "Function Object.GetType() As System.Type" IL_000d: callvirt "Function System.Type.ToString() As String" IL_0012: call "Sub System.Console.WriteLine(String)" IL_0017: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithNumericLValue2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Public i As Integer = 1 Sub Main(args As String()) With i Dim a = .GetType() Console.WriteLine(a.ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="System.Int32"). VerifyDiagnostics(). VerifyIL("Program.Main", <![CDATA[ { // Code size 27 (0x1b) .maxstack 1 IL_0000: ldsflda "Program.i As Integer" IL_0005: ldind.i4 IL_0006: box "Integer" IL_000b: call "Function Object.GetType() As System.Type" IL_0010: callvirt "Function System.Type.ToString() As String" IL_0015: call "Sub System.Console.WriteLine(String)" IL_001a: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithStructureLValueAndExtensionMethod() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Runtime.CompilerServices Structure C1 Public field As Integer Public Property GooProp As Integer End Structure Class C2 Public Shared Sub Main() Dim x = New C1() With x .field = 123 .ExtMeth End With End Sub End Class Module program &lt;ExtensionAttribute&gt; Sub ExtMeth(this As C1) Console.Write(this.field) End Sub End Module </file> </compilation>, expectedOutput:="123"). VerifyDiagnostics(). VerifyIL("C2.Main", <![CDATA[ { // Code size 24 (0x18) .maxstack 2 .locals init (C1 V_0) //x IL_0000: ldloca.s V_0 IL_0002: initobj "C1" IL_0008: ldloca.s V_0 IL_000a: ldc.i4.s 123 IL_000c: stfld "C1.field As Integer" IL_0011: ldloc.0 IL_0012: call "Sub program.ExtMeth(C1)" IL_0017: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithStructureLValueAndExtensionMethod2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Runtime.CompilerServices Structure C1 Public field As Integer Public Property GooProp As Integer End Structure Class C2 Public X As New C1() Public Sub Main2() With X .field = 123 .ExtMeth End With End Sub Public Shared Sub Main() Call New C2().Main2() End Sub End Class Module program &lt;ExtensionAttribute&gt; Sub ExtMeth(this As C1) Console.Write(this.field) End Sub End Module </file> </compilation>, expectedOutput:="123"). VerifyDiagnostics(). VerifyIL("C2.Main2", <![CDATA[ { // Code size 25 (0x19) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldflda "C2.X As C1" IL_0006: dup IL_0007: ldc.i4.s 123 IL_0009: stfld "C1.field As Integer" IL_000e: ldobj "C1" IL_0013: call "Sub program.ExtMeth(C1)" IL_0018: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithStructureLValueAndExtensionMethod3() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Runtime.CompilerServices Structure C1 Public field As Integer Public Property GooProp As Integer End Structure Class C2 Public X As New C1() Public Sub Main2() With X Dim val = 123 Dim _sub As Action = Sub() .field = val .ExtMeth End Sub _sub() End With End Sub Public Shared Sub Main() Call New C2().Main2() End Sub End Class Module program &lt;ExtensionAttribute&gt; Sub ExtMeth(this As C1) Console.Write(this.field) End Sub End Module </file> </compilation>, expectedOutput:="123") c.VerifyDiagnostics() c.VerifyIL("C2.Main2", <![CDATA[ { // Code size 37 (0x25) .maxstack 3 IL_0000: newobj "Sub C2._Closure$__2-0..ctor()" IL_0005: dup IL_0006: ldarg.0 IL_0007: stfld "C2._Closure$__2-0.$VB$Me As C2" IL_000c: dup IL_000d: ldc.i4.s 123 IL_000f: stfld "C2._Closure$__2-0.$VB$Local_val As Integer" IL_0014: ldftn "Sub C2._Closure$__2-0._Lambda$__0()" IL_001a: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_001f: callvirt "Sub System.Action.Invoke()" IL_0024: ret } ]]>) c.VerifyIL("C2._Closure$__2-0._Lambda$__0", <![CDATA[ { // Code size 39 (0x27) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld "C2._Closure$__2-0.$VB$Me As C2" IL_0006: ldflda "C2.X As C1" IL_000b: ldarg.0 IL_000c: ldfld "C2._Closure$__2-0.$VB$Local_val As Integer" IL_0011: stfld "C1.field As Integer" IL_0016: ldarg.0 IL_0017: ldfld "C2._Closure$__2-0.$VB$Me As C2" IL_001c: ldfld "C2.X As C1" IL_0021: call "Sub program.ExtMeth(C1)" IL_0026: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithStructRValue() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Structure SSS Public Sub New(i As Integer) End Sub Public Function M() As String Return Me.GetType().ToString() End Function End Structure Sub Main(args As String()) With New SSS(1) Dim a = .M() Console.WriteLine(a.ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="Program+SSS") c.VerifyDiagnostics() c.VerifyIL("Program.Main", <![CDATA[ { // Code size 26 (0x1a) .maxstack 2 .locals init (Program.SSS V_0) //$W0 IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: call "Sub Program.SSS..ctor(Integer)" IL_0008: ldloca.s V_0 IL_000a: call "Function Program.SSS.M() As String" IL_000f: callvirt "Function String.ToString() As String" IL_0014: call "Sub System.Console.WriteLine(String)" IL_0019: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithStructRValueAndCleanup() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Structure SSSS Private S As String End Structure Structure SSS Public Sub New(i As Integer) End Sub Private A As SSSS Public Function M() As String Return Me.GetType().ToString() End Function End Structure Sub Main(args As String()) With New SSS(1) Dim a = .M() Console.WriteLine(a.ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="Program+SSS"). VerifyDiagnostics(). VerifyIL("Program.Main", <![CDATA[ { // Code size 34 (0x22) .maxstack 2 .locals init (Program.SSS V_0) //$W0 IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: call "Sub Program.SSS..ctor(Integer)" IL_0008: ldloca.s V_0 IL_000a: call "Function Program.SSS.M() As String" IL_000f: callvirt "Function String.ToString() As String" IL_0014: call "Sub System.Console.WriteLine(String)" IL_0019: ldloca.s V_0 IL_001b: initobj "Program.SSS" IL_0021: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithMutatingStructRValue() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C2 Structure SSS Public F As Integer Public Sub SetF(f As Integer) Me.F = f End Sub End Structure Public Shared Sub Main(args() As String) With New SSS .SetF(1) Console.Write(.F) .SetF(2) Console.Write(.F) End With End Sub End Class </file> </compilation>, expectedOutput:="12"). VerifyDiagnostics(). VerifyIL("C2.Main", <![CDATA[ { // Code size 47 (0x2f) .maxstack 2 .locals init (C2.SSS V_0) //$W0 IL_0000: ldloca.s V_0 IL_0002: initobj "C2.SSS" IL_0008: ldloca.s V_0 IL_000a: ldc.i4.1 IL_000b: call "Sub C2.SSS.SetF(Integer)" IL_0010: ldloc.0 IL_0011: ldfld "C2.SSS.F As Integer" IL_0016: call "Sub System.Console.Write(Integer)" IL_001b: ldloca.s V_0 IL_001d: ldc.i4.2 IL_001e: call "Sub C2.SSS.SetF(Integer)" IL_0023: ldloc.0 IL_0024: ldfld "C2.SSS.F As Integer" IL_0029: call "Sub System.Console.Write(Integer)" IL_002e: ret } ]]>) End Sub <Fact()> Public Sub TestWithInsideUsingOfStructureValue() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure STRUCT Implements IDisposable Public C As String Public D As Integer Public Sub Dispose() Implements IDisposable.Dispose End Sub End Structure Class Clazz Public Shared Sub Main(args() As String) Using s = New STRUCT() With s Goo(.D) End With Console.Write(s.D) End Using End Sub Public Shared Sub Goo(ByRef x As Integer) x = 123 End Sub End Class </file> </compilation>, expectedOutput:="0"). VerifyDiagnostics(Diagnostic(ERRID.WRN_MutableStructureInUsing, "s = New STRUCT()").WithArguments("s")). VerifyIL("Clazz.Main", <![CDATA[ { // Code size 50 (0x32) .maxstack 1 .locals init (STRUCT V_0, //s Integer V_1) IL_0000: ldloca.s V_0 IL_0002: initobj "STRUCT" .try { IL_0008: ldloc.0 IL_0009: ldfld "STRUCT.D As Integer" IL_000e: stloc.1 IL_000f: ldloca.s V_1 IL_0011: call "Sub Clazz.Goo(ByRef Integer)" IL_0016: ldloc.0 IL_0017: ldfld "STRUCT.D As Integer" IL_001c: call "Sub System.Console.Write(Integer)" IL_0021: leave.s IL_0031 } finally { IL_0023: ldloca.s V_0 IL_0025: constrained. "STRUCT" IL_002b: callvirt "Sub System.IDisposable.Dispose()" IL_0030: endfinally } IL_0031: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithStructLValue() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Structure SSS Public Sub New(i As Integer) End Sub Public Function M() As String Return Me.GetType().ToString() End Function End Structure Sub Main(args As String()) Dim s1 As New SSS(1) With s1 Dim a = .M() Console.WriteLine(a.ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="Program+SSS"). VerifyDiagnostics(). VerifyIL("Program.Main", <![CDATA[ { // Code size 26 (0x1a) .maxstack 2 .locals init (Program.SSS V_0) //s1 IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: call "Sub Program.SSS..ctor(Integer)" IL_0008: ldloca.s V_0 IL_000a: call "Function Program.SSS.M() As String" IL_000f: callvirt "Function String.ToString() As String" IL_0014: call "Sub System.Console.WriteLine(String)" IL_0019: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithStructLValue2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Structure SSS Public Sub New(i As Integer) End Sub Public Function M() As String Return Me.GetType().ToString() End Function End Structure Sub Main(args As String()) Test(New SSS(1)) End Sub Sub Test(s1 As SSS) With s1 Dim a = .M() Console.WriteLine(a.ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="Program+SSS"). VerifyDiagnostics(). VerifyIL("Program.Test", <![CDATA[ { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarga.s V_0 IL_0002: call "Function Program.SSS.M() As String" IL_0007: callvirt "Function String.ToString() As String" IL_000c: call "Sub System.Console.WriteLine(String)" IL_0011: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithStructLValue3() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Structure SSS Public Sub New(i As Integer) End Sub Public Function M() As String Return Me.GetType().ToString() End Function End Structure Public s1 As New SSS(1) Sub Main(args As String()) With s1 Dim a = .M() Console.WriteLine(a.ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="Program+SSS"). VerifyDiagnostics(). VerifyIL("Program.Main", <![CDATA[ { // Code size 21 (0x15) .maxstack 1 IL_0000: ldsflda "Program.s1 As Program.SSS" IL_0005: call "Function Program.SSS.M() As String" IL_000a: callvirt "Function String.ToString() As String" IL_000f: call "Sub System.Console.WriteLine(String)" IL_0014: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithMutatingStructLValue() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C2 Structure SSS Public F As Integer Public Sub SetF(f As Integer) Me.F = f End Sub End Structure Public Shared Sub Main(args() As String) Dim sss As New SSS With sss .SetF(1) Console.Write(.F) .SetF(2) Console.Write(.F) End With End Sub End Class </file> </compilation>, expectedOutput:="12"). VerifyDiagnostics(). VerifyIL("C2.Main", <![CDATA[ { // Code size 47 (0x2f) .maxstack 2 .locals init (C2.SSS V_0) //sss IL_0000: ldloca.s V_0 IL_0002: initobj "C2.SSS" IL_0008: ldloca.s V_0 IL_000a: ldc.i4.1 IL_000b: call "Sub C2.SSS.SetF(Integer)" IL_0010: ldloc.0 IL_0011: ldfld "C2.SSS.F As Integer" IL_0016: call "Sub System.Console.Write(Integer)" IL_001b: ldloca.s V_0 IL_001d: ldc.i4.2 IL_001e: call "Sub C2.SSS.SetF(Integer)" IL_0023: ldloc.0 IL_0024: ldfld "C2.SSS.F As Integer" IL_0029: call "Sub System.Console.Write(Integer)" IL_002e: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithMutatingStructLValue2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C2 Structure SSS Public F As Integer Public Sub SetF(f As Integer) Me.F = f End Sub End Structure Public Shared _sss As New SSS Public Shared Sub Main(args() As String) With _sss .SetF(1) Console.Write(.F) .SetF(2) Console.Write(.F) End With End Sub End Class </file> </compilation>, expectedOutput:="12"). VerifyDiagnostics(). VerifyIL("C2.Main", <![CDATA[ { // Code size 41 (0x29) .maxstack 3 IL_0000: ldsflda "C2._sss As C2.SSS" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: call "Sub C2.SSS.SetF(Integer)" IL_000c: dup IL_000d: ldfld "C2.SSS.F As Integer" IL_0012: call "Sub System.Console.Write(Integer)" IL_0017: dup IL_0018: ldc.i4.2 IL_0019: call "Sub C2.SSS.SetF(Integer)" IL_001e: ldfld "C2.SSS.F As Integer" IL_0023: call "Sub System.Console.Write(Integer)" IL_0028: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithStructArrayLValue() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Structure SSS Public Sub New(i As Integer) End Sub Public Function M() As String Return Me.GetType().ToString() End Function End Structure Sub Main(args As String()) Dim s1(100) As SSS With s1("123".Length) Dim a = .M() Console.WriteLine(a.ToString()) End With End Sub End Module </file> </compilation>, expectedOutput:="Program+SSS") c.VerifyDiagnostics() c.VerifyIL("Program.Main", <![CDATA[ { // Code size 38 (0x26) .maxstack 2 IL_0000: ldc.i4.s 101 IL_0002: newarr "Program.SSS" IL_0007: ldstr "123" IL_000c: call "Function String.get_Length() As Integer" IL_0011: ldelema "Program.SSS" IL_0016: call "Function Program.SSS.M() As String" IL_001b: callvirt "Function String.ToString() As String" IL_0020: call "Sub System.Console.WriteLine(String)" IL_0025: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithTypeParameterRValue() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C(Of T) Public Shared Sub M() With TProp Dim a = .GetType() Console.WriteLine(a.ToString()) End With End Sub Shared Public Property TProp As T End Class Module Program Sub Main(args As String()) C(Of Date).M() End Sub End Module </file> </compilation>, expectedOutput:="System.DateTime"). VerifyDiagnostics(). VerifyIL("C(Of T).M", <![CDATA[ { // Code size 38 (0x26) .maxstack 1 .locals init (T V_0) //$W0 IL_0000: call "Function C(Of T).get_TProp() As T" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: constrained. "T" IL_000e: callvirt "Function Object.GetType() As System.Type" IL_0013: callvirt "Function System.Type.ToString() As String" IL_0018: call "Sub System.Console.WriteLine(String)" IL_001d: ldloca.s V_0 IL_001f: initobj "T" IL_0025: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithTypeParameterRValue2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C(Of T As New) Public Shared Sub M() With New T Dim a = .GetType() Console.WriteLine(a.ToString()) End With End Sub End Class Module Program Sub Main(args As String()) C(Of Date).M() End Sub End Module </file> </compilation>, expectedOutput:="System.DateTime"). VerifyDiagnostics(). VerifyIL("C(Of T).M", <![CDATA[ { // Code size 38 (0x26) .maxstack 1 .locals init (T V_0) //$W0 IL_0000: call "Function System.Activator.CreateInstance(Of T)() As T" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: constrained. "T" IL_000e: callvirt "Function Object.GetType() As System.Type" IL_0013: callvirt "Function System.Type.ToString() As String" IL_0018: call "Sub System.Console.WriteLine(String)" IL_001d: ldloca.s V_0 IL_001f: initobj "T" IL_0025: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithTypeParameterLValue() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C(Of T As New) Public Shared Sub M() Dim t As New T With t Dim a = .GetType() Console.WriteLine(a.ToString()) End With End Sub End Class Module Program Sub Main(args As String()) C(Of Date).M() End Sub End Module </file> </compilation>, expectedOutput:="System.DateTime"). VerifyDiagnostics(). VerifyIL("C(Of T).M", <![CDATA[ { // Code size 30 (0x1e) .maxstack 1 .locals init (T V_0) //t IL_0000: call "Function System.Activator.CreateInstance(Of T)() As T" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: constrained. "T" IL_000e: callvirt "Function Object.GetType() As System.Type" IL_0013: callvirt "Function System.Type.ToString() As String" IL_0018: call "Sub System.Console.WriteLine(String)" IL_001d: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithTypeParameterArrayLValue() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C(Of T As New) Public Shared Sub M() Dim t(10) As T With t("123".Length) Dim a = .GetType() Console.Write(a.ToString()) If a IsNot Nothing Then Console.WriteLine(.GetHashCode()) End If End With End Sub End Class Module Program Sub Main(args As String()) C(Of Date).M() End Sub End Module </file> </compilation>, expectedOutput:="System.DateTime0"). VerifyDiagnostics(). VerifyIL("C(Of T).M", <![CDATA[ { // Code size 80 (0x50) .maxstack 2 .locals init (T() V_0, //$W0 Integer V_1) //$W1 IL_0000: ldc.i4.s 11 IL_0002: newarr "T" IL_0007: stloc.0 IL_0008: ldstr "123" IL_000d: call "Function String.get_Length() As Integer" IL_0012: stloc.1 IL_0013: ldloc.0 IL_0014: ldloc.1 IL_0015: readonly. IL_0017: ldelema "T" IL_001c: constrained. "T" IL_0022: callvirt "Function Object.GetType() As System.Type" IL_0027: dup IL_0028: callvirt "Function System.Type.ToString() As String" IL_002d: call "Sub System.Console.Write(String)" IL_0032: brfalse.s IL_004d IL_0034: ldloc.0 IL_0035: ldloc.1 IL_0036: readonly. IL_0038: ldelema "T" IL_003d: constrained. "T" IL_0043: callvirt "Function Object.GetHashCode() As Integer" IL_0048: call "Sub System.Console.WriteLine(Integer)" IL_004d: ldnull IL_004e: stloc.0 IL_004f: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithAnonymousType() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim a = New With {.a = 1, .b="text"} With a .a = 123 Console.WriteLine(.a &amp; .b) End With End Sub End Module </file> </compilation>, expectedOutput:="123text") c.VerifyDiagnostics() c.VerifyIL("Program.Main", <![CDATA[ { // Code size 50 (0x32) .maxstack 2 .locals init (VB$AnonymousType_0(Of Integer, String) V_0) //$W0 IL_0000: ldc.i4.1 IL_0001: ldstr "text" IL_0006: newobj "Sub VB$AnonymousType_0(Of Integer, String)..ctor(Integer, String)" IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: ldc.i4.s 123 IL_000f: callvirt "Sub VB$AnonymousType_0(Of Integer, String).set_a(Integer)" IL_0014: ldloc.0 IL_0015: callvirt "Function VB$AnonymousType_0(Of Integer, String).get_a() As Integer" IL_001a: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String" IL_001f: ldloc.0 IL_0020: callvirt "Function VB$AnonymousType_0(Of Integer, String).get_b() As String" IL_0025: call "Function String.Concat(String, String) As String" IL_002a: call "Sub System.Console.WriteLine(String)" IL_002f: ldnull IL_0030: stloc.0 IL_0031: ret } ]]>) End Sub <Fact()> Public Sub TestNestedWithWithAnonymousType() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) With New With {.a = 1, .b= New With { Key .x = "---", .y="text"} } Console.Write(.ToString()) Console.Write("|") With .b Console.Write(.ToString()) End With End With End Sub End Module </file> </compilation>, expectedOutput:="{ a = 1, b = { x = ---, y = text } }|{ x = ---, y = text }"). VerifyDiagnostics(). VerifyIL("Program.Main", <![CDATA[ { // Code size 62 (0x3e) .maxstack 3 IL_0000: ldc.i4.1 IL_0001: ldstr "---" IL_0006: ldstr "text" IL_000b: newobj "Sub VB$AnonymousType_1(Of String, String)..ctor(String, String)" IL_0010: newobj "Sub VB$AnonymousType_0(Of Integer, <anonymous type: Key x As String, y As String>)..ctor(Integer, <anonymous type: Key x As String, y As String>)" IL_0015: dup IL_0016: callvirt "Function VB$AnonymousType_0(Of Integer, <anonymous type: Key x As String, y As String>).ToString() As String" IL_001b: call "Sub System.Console.Write(String)" IL_0020: ldstr "|" IL_0025: call "Sub System.Console.Write(String)" IL_002a: callvirt "Function VB$AnonymousType_0(Of Integer, <anonymous type: Key x As String, y As String>).get_b() As <anonymous type: Key x As String, y As String>" IL_002f: callvirt "Function VB$AnonymousType_1(Of String, String).ToString() As String" IL_0034: call "Sub System.Console.Write(String)" IL_0039: ldnull IL_003a: pop IL_003b: ldnull IL_003c: pop IL_003d: ret } ]]>) End Sub <Fact()> Public Sub TestWithStatement() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C Structure S Public S() As SS End Structure Structure SS Public s As SSS End Structure Structure SSS Public F As Integer Public Overrides Function ToString() As String Return "Hello, " &amp; Me.F End Function End Structure Public Shared Sub Main(args() As String) Dim s(10) As S With s("1".Length) .S = New SS(2) {} End With With s("1".Length).S(1).s .F = 123 End With Console.Write(s(1).S(1).s) End Sub End Class </file> </compilation>, expectedOutput:="Hello, 123").VerifyDiagnostics() End Sub <Fact()> Public Sub TestWithStatement_MyClass() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure Clazz Structure SS Public FLD As String End Structure Public FLD As SS Sub TEST() With MyClass.FLD Console.Write(.GetType().ToString()) End With End Sub Public Shared Sub Main(args() As String) Call New Clazz().TEST() End Sub End Structure </file> </compilation>, expectedOutput:="Clazz+SS").VerifyDiagnostics() End Sub <Fact()> Public Sub TestWithStatement_MyBase() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class Clazz Public Structure SS Public FLD As String End Structure Public FLD As SS End Class Class Derived Inherits Clazz Sub TEST() With MyBase.FLD Console.Write(.GetType().ToString()) End With End Sub Public Shared Sub Main(args() As String) Call New Derived().TEST() End Sub End Class </file> </compilation>, expectedOutput:="Clazz+SS").VerifyDiagnostics() End Sub <Fact()> Public Sub TestSimpleWithWithMeReference_Class() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C2 Public A As Integer Public B As Date Public C As String Public Sub New() With Me .A = 1 .B = #1/2/2003# .C = "!" End With End Sub Public Overrides Function ToString() As String Return ".A = " &amp; Me.A &amp; "; .B = " &amp; Me.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) &amp; "; .C = " &amp; Me.C End Function Public Shared Sub Main(args() As String) Console.Write(New C2().ToString()) End Sub End Class </file> </compilation>, expectedOutput:=".A = 1; .B = 1/2/2003; .C = !"). VerifyDiagnostics(). VerifyIL("C2..ctor", <![CDATA[ { // Code size 45 (0x2d) .maxstack 2 IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: ldc.i4.1 IL_0008: stfld "C2.A As Integer" IL_000d: ldarg.0 IL_000e: ldc.i8 0x8c48009070c0000 IL_0017: newobj "Sub Date..ctor(Long)" IL_001c: stfld "C2.B As Date" IL_0021: ldarg.0 IL_0022: ldstr "!" IL_0027: stfld "C2.C As String" IL_002c: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithMeReference_Struct() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure C2 Public A As Integer Public B As Date Public C As String Public Sub New(i As Integer) With Me .A = 1 .B = #1/2/2003# .C = "!" End With End Sub Public Overrides Function ToString() As String Return ".A = " &amp; Me.A &amp; "; .B = " &amp; Me.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) &amp; "; .C = " &amp; Me.C End Function Public Shared Sub Main(args() As String) Console.Write(New C2(1).ToString()) End Sub End Structure </file> </compilation>, expectedOutput:=".A = 1; .B = 1/2/2003; .C = !"). VerifyDiagnostics(). VerifyIL("C2..ctor", <![CDATA[ { // Code size 46 (0x2e) .maxstack 2 IL_0000: ldarg.0 IL_0001: initobj "C2" IL_0007: ldarg.0 IL_0008: ldc.i4.1 IL_0009: stfld "C2.A As Integer" IL_000e: ldarg.0 IL_000f: ldc.i8 0x8c48009070c0000 IL_0018: newobj "Sub Date..ctor(Long)" IL_001d: stfld "C2.B As Date" IL_0022: ldarg.0 IL_0023: ldstr "!" IL_0028: stfld "C2.C As String" IL_002d: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWithWithMeReference_Class_Capture() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C2 Public A As Integer Public B As Date Public C As String Public Sub New() With Me .A = 1 Dim a As Action = Sub() .B = #1/2/2003# .C = "!" End Sub a() End With End Sub Public Overrides Function ToString() As String Return ".A = " &amp; Me.A &amp; "; .B = " &amp; Me.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) &amp; "; .C = " &amp; Me.C End Function Public Shared Sub Main(args() As String) Console.Write(New C2().ToString()) End Sub End Class </file> </compilation>, expectedOutput:=".A = 1; .B = 1/2/2003; .C = !") c.VerifyDiagnostics() c.VerifyIL("C2..ctor", <![CDATA[ { // Code size 31 (0x1f) .maxstack 2 IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: ldc.i4.1 IL_0008: stfld "C2.A As Integer" IL_000d: ldarg.0 IL_000e: ldftn "Sub C2._Lambda$__3-0()" IL_0014: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_0019: callvirt "Sub System.Action.Invoke()" IL_001e: ret } ]]>) c.VerifyIL("C2._Lambda$__3-0", <![CDATA[ { // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i8 0x8c48009070c0000 IL_000a: newobj "Sub Date..ctor(Long)" IL_000f: stfld "C2.B As Date" IL_0014: ldarg.0 IL_0015: ldstr "!" IL_001a: stfld "C2.C As String" IL_001f: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWith_LiftedStructLValue() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure C2 Public _abc As ABC Structure ABC Public A As Integer Public B As Date Public C As String End Structure Public Sub New(i As ABC) With i .A = 1 Dim a As Action = Sub() .B = #1/2/2003# .C = "!" End Sub a() End With Me._abc = i End Sub Public Overrides Function ToString() As String Return ".A = " &amp; Me._abc.A &amp; "; .B = " &amp; Me._abc.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) &amp; "; .C = " &amp; Me._abc.C End Function Public Shared Sub Main(args() As String) Console.Write(New C2(Nothing).ToString()) End Sub End Structure </file> </compilation>, expectedOutput:=".A = 1; .B = 1/2/2003; .C = !") c.VerifyDiagnostics() c.VerifyIL("C2..ctor", <![CDATA[ { // Code size 62 (0x3e) .maxstack 2 .locals init (C2._Closure$__3-0 V_0) //$VB$Closure_0 IL_0000: newobj "Sub C2._Closure$__3-0..ctor()" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.1 IL_0008: stfld "C2._Closure$__3-0.$VB$Local_i As C2.ABC" IL_000d: ldarg.0 IL_000e: initobj "C2" IL_0014: ldloc.0 IL_0015: ldflda "C2._Closure$__3-0.$VB$Local_i As C2.ABC" IL_001a: ldc.i4.1 IL_001b: stfld "C2.ABC.A As Integer" IL_0020: ldloc.0 IL_0021: ldftn "Sub C2._Closure$__3-0._Lambda$__0()" IL_0027: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_002c: callvirt "Sub System.Action.Invoke()" IL_0031: ldarg.0 IL_0032: ldloc.0 IL_0033: ldfld "C2._Closure$__3-0.$VB$Local_i As C2.ABC" IL_0038: stfld "C2._abc As C2.ABC" IL_003d: ret } ]]>) c.VerifyIL("C2._Closure$__3-0._Lambda$__0", <![CDATA[ { // Code size 42 (0x2a) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda "C2._Closure$__3-0.$VB$Local_i As C2.ABC" IL_0006: ldc.i8 0x8c48009070c0000 IL_000f: newobj "Sub Date..ctor(Long)" IL_0014: stfld "C2.ABC.B As Date" IL_0019: ldarg.0 IL_001a: ldflda "C2._Closure$__3-0.$VB$Local_i As C2.ABC" IL_001f: ldstr "!" IL_0024: stfld "C2.ABC.C As String" IL_0029: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWith_LiftedStructLValue_Nested() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure C2 Public _abc As ABC Structure ABC Public A As Integer Public B As Date Public C As String End Structure Public Sub New(i As ABC) Dim b = Function() As ABC Dim x As New ABC With x .A = 1 Dim a As Action = Sub() .B = #1/2/2003# .C = "!" End Sub a() End With Return x End Function Me._abc = b() End Sub Public Overrides Function ToString() As String Return ".A = " &amp; Me._abc.A &amp; "; .B = " &amp; Me._abc.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) &amp; "; .C = " &amp; Me._abc.C End Function Public Shared Sub Main(args() As String) Console.Write(New C2(Nothing).ToString()) End Sub End Structure </file> </compilation>, expectedOutput:=".A = 1; .B = 1/2/2003; .C = !") c.VerifyDiagnostics() c.VerifyIL("C2..ctor", <![CDATA[ { // Code size 57 (0x39) .maxstack 2 .locals init (VB$AnonymousDelegate_0(Of C2.ABC) V_0) //b IL_0000: ldarg.0 IL_0001: initobj "C2" IL_0007: ldsfld "C2._Closure$__.$I3-0 As <generated method>" IL_000c: brfalse.s IL_0015 IL_000e: ldsfld "C2._Closure$__.$I3-0 As <generated method>" IL_0013: br.s IL_002b IL_0015: ldsfld "C2._Closure$__.$I As C2._Closure$__" IL_001a: ldftn "Function C2._Closure$__._Lambda$__3-0() As C2.ABC" IL_0020: newobj "Sub VB$AnonymousDelegate_0(Of C2.ABC)..ctor(Object, System.IntPtr)" IL_0025: dup IL_0026: stsfld "C2._Closure$__.$I3-0 As <generated method>" IL_002b: stloc.0 IL_002c: ldarg.0 IL_002d: ldloc.0 IL_002e: callvirt "Function VB$AnonymousDelegate_0(Of C2.ABC).Invoke() As C2.ABC" IL_0033: stfld "C2._abc As C2.ABC" IL_0038: ret } ]]>) c.VerifyIL("C2._Closure$__._Lambda$__3-0", <![CDATA[ { // Code size 52 (0x34) .maxstack 3 IL_0000: newobj "Sub C2._Closure$__3-0..ctor()" IL_0005: dup IL_0006: ldflda "C2._Closure$__3-0.$VB$Local_x As C2.ABC" IL_000b: initobj "C2.ABC" IL_0011: dup IL_0012: ldflda "C2._Closure$__3-0.$VB$Local_x As C2.ABC" IL_0017: ldc.i4.1 IL_0018: stfld "C2.ABC.A As Integer" IL_001d: dup IL_001e: ldftn "Sub C2._Closure$__3-0._Lambda$__1()" IL_0024: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_0029: callvirt "Sub System.Action.Invoke()" IL_002e: ldfld "C2._Closure$__3-0.$VB$Local_x As C2.ABC" IL_0033: ret } ]]>) c.VerifyIL("C2._Closure$__3-0._Lambda$__1", <![CDATA[ { // Code size 42 (0x2a) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda "C2._Closure$__3-0.$VB$Local_x As C2.ABC" IL_0006: ldc.i8 0x8c48009070c0000 IL_000f: newobj "Sub Date..ctor(Long)" IL_0014: stfld "C2.ABC.B As Date" IL_0019: ldarg.0 IL_001a: ldflda "C2._Closure$__3-0.$VB$Local_x As C2.ABC" IL_001f: ldstr "!" IL_0024: stfld "C2.ABC.C As String" IL_0029: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWith_LiftedStructLValueArrayElement() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure C2 Public _abc As ABC Structure ABC Public A As Integer Public B As Date Public C As String End Structure Private ARR() As ABC Public Sub New(i As ABC) ARR = New ABC(2) {} ARR(0).A = 1 With ARR(ARR(0).A) Dim b = Sub() .A = 2 Dim a As Action = Sub() .B = #6/6/2006# .C = "?" End Sub a() End Sub b() End With Print(ARR(1)) End Sub Public Sub Print(a As ABC) Console.Write("A = " &amp; a.A &amp; "; B = " &amp; a.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) &amp; "; C = " &amp; a.C) End Sub Public Shared Sub Main(args() As String) Dim a As New C2(Nothing) End Sub End Structure </file> </compilation>, expectedOutput:="A = 2; B = 6/6/2006; C = ?") c.VerifyDiagnostics() c.VerifyIL("C2..ctor", <![CDATA[ { // Code size 112 (0x70) .maxstack 4 IL_0000: ldarg.0 IL_0001: initobj "C2" IL_0007: ldarg.0 IL_0008: ldc.i4.3 IL_0009: newarr "C2.ABC" IL_000e: stfld "C2.ARR As C2.ABC()" IL_0013: ldarg.0 IL_0014: ldfld "C2.ARR As C2.ABC()" IL_0019: ldc.i4.0 IL_001a: ldelema "C2.ABC" IL_001f: ldc.i4.1 IL_0020: stfld "C2.ABC.A As Integer" IL_0025: newobj "Sub C2._Closure$__4-0..ctor()" IL_002a: dup IL_002b: ldarg.0 IL_002c: ldfld "C2.ARR As C2.ABC()" IL_0031: stfld "C2._Closure$__4-0.$W2 As C2.ABC()" IL_0036: dup IL_0037: ldarg.0 IL_0038: ldfld "C2.ARR As C2.ABC()" IL_003d: ldc.i4.0 IL_003e: ldelema "C2.ABC" IL_0043: ldfld "C2.ABC.A As Integer" IL_0048: stfld "C2._Closure$__4-0.$W3 As Integer" IL_004d: ldftn "Sub C2._Closure$__4-0._Lambda$__0()" IL_0053: newobj "Sub VB$AnonymousDelegate_0..ctor(Object, System.IntPtr)" IL_0058: callvirt "Sub VB$AnonymousDelegate_0.Invoke()" IL_005d: ldarg.0 IL_005e: ldarg.0 IL_005f: ldfld "C2.ARR As C2.ABC()" IL_0064: ldc.i4.1 IL_0065: ldelem "C2.ABC" IL_006a: call "Sub C2.Print(C2.ABC)" IL_006f: ret } ]]>) c.VerifyIL("C2._Closure$__4-0._Lambda$__0", <![CDATA[ { // Code size 66 (0x42) .maxstack 3 .locals init (System.Action V_0) IL_0000: ldarg.0 IL_0001: ldfld "C2._Closure$__4-0.$W2 As C2.ABC()" IL_0006: ldarg.0 IL_0007: ldfld "C2._Closure$__4-0.$W3 As Integer" IL_000c: ldelema "C2.ABC" IL_0011: ldc.i4.2 IL_0012: stfld "C2.ABC.A As Integer" IL_0017: ldarg.0 IL_0018: ldfld "C2._Closure$__4-0.$I1 As System.Action" IL_001d: brfalse.s IL_0027 IL_001f: ldarg.0 IL_0020: ldfld "C2._Closure$__4-0.$I1 As System.Action" IL_0025: br.s IL_003c IL_0027: ldarg.0 IL_0028: ldarg.0 IL_0029: ldftn "Sub C2._Closure$__4-0._Lambda$__1()" IL_002f: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_0034: dup IL_0035: stloc.0 IL_0036: stfld "C2._Closure$__4-0.$I1 As System.Action" IL_003b: ldloc.0 IL_003c: callvirt "Sub System.Action.Invoke()" IL_0041: ret } ]]>) c.VerifyIL("C2._Closure$__4-0._Lambda$__1", <![CDATA[ { // Code size 64 (0x40) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld "C2._Closure$__4-0.$W2 As C2.ABC()" IL_0006: ldarg.0 IL_0007: ldfld "C2._Closure$__4-0.$W3 As Integer" IL_000c: ldelema "C2.ABC" IL_0011: ldc.i8 0x8c8571349d14000 IL_001a: newobj "Sub Date..ctor(Long)" IL_001f: stfld "C2.ABC.B As Date" IL_0024: ldarg.0 IL_0025: ldfld "C2._Closure$__4-0.$W2 As C2.ABC()" IL_002a: ldarg.0 IL_002b: ldfld "C2._Closure$__4-0.$W3 As Integer" IL_0030: ldelema "C2.ABC" IL_0035: ldstr "?" IL_003a: stfld "C2.ABC.C As String" IL_003f: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWith_LiftedStructLValueArrayElement2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C2 Public _abc As ABC Structure ABC Public A As Integer Public B As Date Public C As String End Structure Private ARR() As ABC Public Sub S_TEST() ARR = New ABC(2) {} ARR(0).A = 1 Dim outer As Action = Sub() With ARR(ARR(0).A) Dim b = Sub() .A = 2 Dim a As Action = Sub() .B = #6/6/2006# .C = "?" End Sub a() End Sub b() End With End Sub outer() Print(ARR(1)) End Sub Public Sub Print(a As ABC) Console.Write("A = " &amp; a.A &amp; "; B = " &amp; a.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) &amp; "; C = " &amp; a.C) End Sub Public Shared Sub Main(args() As String) Dim a As New C2() a.S_TEST() End Sub End Class </file> </compilation>, expectedOutput:="A = 2; B = 6/6/2006; C = ?").VerifyDiagnostics() End Sub <Fact()> Public Sub TestSimpleWith_LiftedStructLValueFieldAccess() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C2 Structure ABC Public A As Integer Public B As Date Public C As String End Structure Private ARR As ABC Public Sub New() Dim sss As String = "?" With Me.ARR Dim b = Sub() .A = 2 Dim a As Action = Sub() .B = #6/6/2006# .C = sss End Sub a() End Sub b() End With Print(Me.ARR) End Sub Public Sub Print(a As ABC) Console.Write("A = " &amp; a.A &amp; "; B = " &amp; a.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) &amp; "; C = " &amp; a.C) End Sub Public Shared Sub Main(args() As String) Dim a As New C2() End Sub End Class </file> </compilation>, expectedOutput:="A = 2; B = 6/6/2006; C = ?") c.VerifyDiagnostics() c.VerifyIL("C2..ctor", <![CDATA[ { // Code size 58 (0x3a) .maxstack 3 IL_0000: newobj "Sub C2._Closure$__2-0..ctor()" IL_0005: ldarg.0 IL_0006: call "Sub Object..ctor()" IL_000b: dup IL_000c: ldarg.0 IL_000d: stfld "C2._Closure$__2-0.$VB$Me As C2" IL_0012: dup IL_0013: ldstr "?" IL_0018: stfld "C2._Closure$__2-0.$VB$Local_sss As String" IL_001d: ldftn "Sub C2._Closure$__2-0._Lambda$__0()" IL_0023: newobj "Sub VB$AnonymousDelegate_0..ctor(Object, System.IntPtr)" IL_0028: callvirt "Sub VB$AnonymousDelegate_0.Invoke()" IL_002d: ldarg.0 IL_002e: ldarg.0 IL_002f: ldfld "C2.ARR As C2.ABC" IL_0034: call "Sub C2.Print(C2.ABC)" IL_0039: ret } ]]>) c.VerifyIL("C2._Closure$__2-0._Lambda$__0", <![CDATA[ { // Code size 60 (0x3c) .maxstack 3 .locals init (System.Action V_0) IL_0000: ldarg.0 IL_0001: ldfld "C2._Closure$__2-0.$VB$Me As C2" IL_0006: ldflda "C2.ARR As C2.ABC" IL_000b: ldc.i4.2 IL_000c: stfld "C2.ABC.A As Integer" IL_0011: ldarg.0 IL_0012: ldfld "C2._Closure$__2-0.$I1 As System.Action" IL_0017: brfalse.s IL_0021 IL_0019: ldarg.0 IL_001a: ldfld "C2._Closure$__2-0.$I1 As System.Action" IL_001f: br.s IL_0036 IL_0021: ldarg.0 IL_0022: ldarg.0 IL_0023: ldftn "Sub C2._Closure$__2-0._Lambda$__1()" IL_0029: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_002e: dup IL_002f: stloc.0 IL_0030: stfld "C2._Closure$__2-0.$I1 As System.Action" IL_0035: ldloc.0 IL_0036: callvirt "Sub System.Action.Invoke()" IL_003b: ret } ]]>) c.VerifyIL("C2._Closure$__2-0._Lambda$__1", <![CDATA[ { // Code size 53 (0x35) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld "C2._Closure$__2-0.$VB$Me As C2" IL_0006: ldflda "C2.ARR As C2.ABC" IL_000b: ldc.i8 0x8c8571349d14000 IL_0014: newobj "Sub Date..ctor(Long)" IL_0019: stfld "C2.ABC.B As Date" IL_001e: ldarg.0 IL_001f: ldfld "C2._Closure$__2-0.$VB$Me As C2" IL_0024: ldflda "C2.ARR As C2.ABC" IL_0029: ldarg.0 IL_002a: ldfld "C2._Closure$__2-0.$VB$Local_sss As String" IL_002f: stfld "C2.ABC.C As String" IL_0034: ret } ]]>) End Sub <Fact()> Public Sub TestSimpleWith_LiftedStructLValueFieldAccess_Shared() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure C2 Structure ABC Public A As Integer Public B As Date Public C As String End Structure Private Shared ARR As ABC Public Sub New(i As Integer) With Me.ARR Dim b = Sub() Dim x = "?" .A = 2 Dim a As Action = Sub() .B = #6/6/2006# .C = x End Sub a() End Sub b() End With Print(C2.ARR) End Sub Public Sub Print(a As ABC) Console.Write("A = " &amp; a.A &amp; "; B = " &amp; a.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) &amp; "; C = " &amp; a.C) End Sub Public Shared Sub Main(args() As String) Dim a As New C2(0) End Sub End Structure </file> </compilation>, expectedOutput:="A = 2; B = 6/6/2006; C = ?") c.VerifyDiagnostics(Diagnostic(ERRID.WRN_SharedMemberThroughInstance, "Me.ARR")) c.VerifyIL("C2..ctor", <![CDATA[ { // Code size 60 (0x3c) .maxstack 2 IL_0000: ldarg.0 IL_0001: initobj "C2" IL_0007: ldsfld "C2._Closure$__.$I3-0 As <generated method>" IL_000c: brfalse.s IL_0015 IL_000e: ldsfld "C2._Closure$__.$I3-0 As <generated method>" IL_0013: br.s IL_002b IL_0015: ldsfld "C2._Closure$__.$I As C2._Closure$__" IL_001a: ldftn "Sub C2._Closure$__._Lambda$__3-0()" IL_0020: newobj "Sub VB$AnonymousDelegate_0..ctor(Object, System.IntPtr)" IL_0025: dup IL_0026: stsfld "C2._Closure$__.$I3-0 As <generated method>" IL_002b: callvirt "Sub VB$AnonymousDelegate_0.Invoke()" IL_0030: ldarg.0 IL_0031: ldsfld "C2.ARR As C2.ABC" IL_0036: call "Sub C2.Print(C2.ABC)" IL_003b: ret } ]]>) c.VerifyIL("C2._Closure$__._Lambda$__3-0", <![CDATA[ { // Code size 44 (0x2c) .maxstack 3 IL_0000: newobj "Sub C2._Closure$__3-0..ctor()" IL_0005: dup IL_0006: ldstr "?" IL_000b: stfld "C2._Closure$__3-0.$VB$Local_x As String" IL_0010: ldsflda "C2.ARR As C2.ABC" IL_0015: ldc.i4.2 IL_0016: stfld "C2.ABC.A As Integer" IL_001b: ldftn "Sub C2._Closure$__3-0._Lambda$__1()" IL_0021: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_0026: callvirt "Sub System.Action.Invoke()" IL_002b: ret } ]]>) c.VerifyIL("C2._Closure$__3-0._Lambda$__1", <![CDATA[ { // Code size 41 (0x29) .maxstack 2 IL_0000: ldsflda "C2.ARR As C2.ABC" IL_0005: ldc.i8 0x8c8571349d14000 IL_000e: newobj "Sub Date..ctor(Long)" IL_0013: stfld "C2.ABC.B As Date" IL_0018: ldsflda "C2.ARR As C2.ABC" IL_001d: ldarg.0 IL_001e: ldfld "C2._Closure$__3-0.$VB$Local_x As String" IL_0023: stfld "C2.ABC.C As String" IL_0028: ret } ]]>) End Sub <Fact()> Public Sub TestWithAndReadOnlyValueTypedFields() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure STRUCT Public C As String Public D As Integer End Structure Class Clazz Public Shared ReadOnly FLD1 As New STRUCT Public Shared FLD2 As New STRUCT Shared Sub New() Console.Write(FLD1.D) Console.Write(" ") Console.Write(FLD2.D) Console.Write(" ") With FLD1 Goo(.D, 1) End With With FLD2 Goo(.D, 1) End With Console.Write(FLD1.D) Console.Write(" ") Console.Write(FLD2.D) Console.Write(" ") End Sub Public Shared Sub Main(args() As String) With FLD1 Goo(.D, 2) End With With FLD2 Goo(.D, 2) End With Console.Write(FLD1.D) Console.Write(" ") Console.Write(FLD2.D) End Sub Public Shared Sub Goo(ByRef x As Integer, val As Integer) x = val End Sub End Class </file> </compilation>, expectedOutput:="0 0 1 1 1 2") End Sub <Fact()> Public Sub TestSimpleWith_ValueTypeLValueInParentheses() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure C2 Structure SSS Public A As Integer Public B As Date Public Sub SetA(_a As Integer) Me.A = _a End Sub End Structure Public Sub New(i As Integer) Dim a As New SSS With (a) .SetA(222) End With Console.Write(a.A) Console.Write(" ") With a .SetA(222) End With Console.Write(a.A) End Sub Public Shared Sub main(args() As String) Dim a As New C2(1) End Sub End Structure </file> </compilation>, expectedOutput:="0 222").VerifyDiagnostics() End Sub <Fact()> Public Sub TestWith_WithDisposableStruct_RValue() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure Struct Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Structure Structure Clazz Sub S() With New Struct .Dispose() End With End Sub End Structure </file> </compilation>). VerifyDiagnostics(). VerifyIL("Clazz.S", <![CDATA[ { // Code size 16 (0x10) .maxstack 1 .locals init (Struct V_0) //$W0 IL_0000: ldloca.s V_0 IL_0002: initobj "Struct" IL_0008: ldloca.s V_0 IL_000a: call "Sub Struct.Dispose()" IL_000f: ret } ]]>) End Sub <Fact()> Public Sub TestWith_WithDisposableStruct_LValue() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure Struct Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Structure Structure Clazz Sub S() Dim s As New Struct With s .Dispose() End With End Sub End Structure </file> </compilation>). VerifyDiagnostics(). VerifyIL("Clazz.S", <![CDATA[ { // Code size 16 (0x10) .maxstack 1 .locals init (Struct V_0) //s IL_0000: ldloca.s V_0 IL_0002: initobj "Struct" IL_0008: ldloca.s V_0 IL_000a: call "Sub Struct.Dispose()" IL_000f: ret } ]]>) End Sub <Fact()> Public Sub TestWith_Arrays() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Structure Clazz Shared Sub Main() With New Integer() {} Dim cnt = .Count Console.Write(cnt) End With End Sub End Structure </file> </compilation>, expectedOutput:="0"). VerifyDiagnostics(). VerifyIL("Clazz.Main", <![CDATA[ { // Code size 19 (0x13) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: newarr "Integer" IL_0006: call "Function System.Linq.Enumerable.Count(Of Integer)(System.Collections.Generic.IEnumerable(Of Integer)) As Integer" IL_000b: call "Sub System.Console.Write(Integer)" IL_0010: ldnull IL_0011: pop IL_0012: ret } ]]>) End Sub <Fact()> Public Sub TestWith_NestedWithWithInferredVarType() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure Struct Public A As String Public B As String End Structure Structure Clazz Public S As Struct Shared Sub TEST() Dim c = New Clazz With c .S = New Struct() .S.A = "" .S.B = .S.A With .S Dim a = .A Dim b = .B Console.Write(a.GetType()) Console.Write("|") Console.Write(b.GetType()) End With End With End Sub Shared Sub Main(args() As String) TEST() End Sub End Structure </file> </compilation>, expectedOutput:="System.String|System.String").VerifyDiagnostics() End Sub <Fact()> Public Sub TestWith_NestedWithWithInferredVarType2() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Structure Struct Public A As String Public B As String End Structure Structure Clazz Public S As Struct Shared Sub TEST() Dim c = New Clazz With c .S = New Struct() .S.A = "" .S.B = .S.A Dim a = New With {.y = New Struct(), .x = Sub() With .y Dim a = .A Dim b = .B End With End Sub} End With End Sub Shared Sub Main(args() As String) TEST() End Sub End Structure </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.ERR_CannotLiftAnonymousType1, ".y").WithArguments("y"), Diagnostic(ERRID.ERR_BlockLocalShadowing1, "a").WithArguments("a")) End Sub <Fact()> Public Sub TestWith_NestedWithWithInferredVarType3() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Structure Struct Public A As String Public B As String End Structure Structure Struct2 Public X As Struct Public Y As String End Structure Structure Clazz Shared Sub TEST() Dim c As Struct2 With c .Y = "" With .X .A = "" End With End With Console.Write(c) With c With .X .B = "" End With End With Console.WriteLine(c) End Sub End Structure </file> </compilation>).VerifyDiagnostics( Diagnostic(ERRID.WRN_DefAsgUseNullRefStr, "c").WithArguments("c")) End Sub <WorkItem(545120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545120")> <Fact()> Public Sub TestWith_NestedWithWithLambdasAndObjectInitializers() CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Structure SS1 Public A As String Public B As String End Structure Structure SS2 Public X As SS1 Public Y As SS1 End Structure Structure Clazz Shared Sub Main(args() As String) Dim t As New Clazz(1) End Sub Public F As SS2 Sub New(i As Integer) F = New SS2() With F Dim a As New SS2() With {.X = Function() As SS1 With .Y .A = "xyz" End With Return .Y End Function.Invoke()} End With End Sub End Structure </file> </compilation>).VerifyDiagnostics() End Sub <Fact()> Public Sub TestWith_NestedWithWithQuery() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Structure Struct Public A As String Public B As String End Structure Class Clazz Structure SS Public FLD As Struct End Structure Public FLD As SS Sub TEST() With MyClass.FLD .FLD.A = "Success" Dim q = From x In "a" Select .FLD.A &amp; "=" &amp; x Console.Write(q.First()) End With End Sub Shared Sub Main(args() As String) Call New Clazz().TEST() End Sub End Class </file> </compilation>, expectedOutput:="Success=a").VerifyDiagnostics() End Sub <ConditionalFact(GetType(DesktopOnly), Reason:=ConditionalSkipReason.TestExecutionNeedsDesktopTypes)> Public Sub TestWith_MyBase() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Class Base Public Structure SS Public FLD As String End Structure Public FLD As SS End Class Class Clazz Inherits Base Public Shadows FLD As Integer Sub TEST() With MyBase.FLD Dim q = From x In "" Select .FLD Console.Write(q.GetType().ToString()) End With End Sub Shared Sub Main(args() As String) Call New Clazz().TEST() End Sub End Class </file> </compilation>, expectedOutput:="System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Char,System.String]") c.VerifyDiagnostics() c.VerifyIL("Clazz.TEST", <![CDATA[ { // Code size 38 (0x26) .maxstack 3 IL_0000: ldstr "" IL_0005: ldarg.0 IL_0006: ldftn "Function Clazz._Lambda$__2-0(Char) As String" IL_000c: newobj "Sub System.Func(Of Char, String)..ctor(Object, System.IntPtr)" IL_0011: call "Function System.Linq.Enumerable.Select(Of Char, String)(System.Collections.Generic.IEnumerable(Of Char), System.Func(Of Char, String)) As System.Collections.Generic.IEnumerable(Of String)" IL_0016: callvirt "Function Object.GetType() As System.Type" IL_001b: callvirt "Function System.Type.ToString() As String" IL_0020: call "Sub System.Console.Write(String)" IL_0025: ret } ]]>) c.VerifyIL("Clazz._Lambda$__2-0", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda "Base.FLD As Base.SS" IL_0006: ldfld "Base.SS.FLD As String" IL_000b: ret } ]]>) End Sub <Fact()> Public Sub TestWith_NestedWithWithQuery2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Structure Struct Public A As String Public B As String End Structure Class Clazz_Base Public Structure SS Public FLD As Struct End Structure Public FLD As SS End Class Class Clazz Inherits Clazz_Base Sub TEST() With MyBase.FLD .FLD.A = "Success" Dim q = From x In "a" Select .FLD.A &amp; "=" &amp; x Console.Write(q.First()) End With End Sub Shared Sub Main(args() As String) Call New Clazz().TEST() End Sub End Class </file> </compilation>, expectedOutput:="Success=a").VerifyDiagnostics() End Sub <Fact()> Public Sub TestWith_NestedWithWithQuery3() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Structure Struct Public A As String Public B As String End Structure Class Clazz_Base Public Structure SS Public FLD As Struct End Structure Public FLD As SS End Class Class Clazz Inherits Clazz_Base Sub TEST() With MyBase.FLD Dim _sub As Action = Sub() .FLD.A = "Success" End Sub _sub() Dim q = From x In "a" Select .FLD.A &amp; "=" &amp; x Console.Write(q.First()) End With End Sub Shared Sub Main(args() As String) Call New Clazz().TEST() End Sub End Class </file> </compilation>, expectedOutput:="Success=a").VerifyDiagnostics() End Sub <Fact()> Public Sub TestWith_NestedWithWithQuery4() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Structure STRUCT Public C As String Public D As Integer End Structure Class Clazz Public Shared Sub Main(args() As String) Dim source(10) As STRUCT Dim result = From x In source Select DirectCast(Function() With x Goo(.D) End With Return x End Function, Func(Of STRUCT))() Console.Write(result.FirstOrDefault.D) End Sub Public Shared Sub Goo(ByRef x As Integer) x = 123 End Sub End Class </file> </compilation>, expectedOutput:="0") c.VerifyDiagnostics() c.VerifyIL("Clazz._Closure$__1-0._Lambda$__1", <![CDATA[ { // Code size 26 (0x1a) .maxstack 1 .locals init (Integer V_0) IL_0000: ldarg.0 IL_0001: ldfld "Clazz._Closure$__1-0.$VB$Local_x As STRUCT" IL_0006: ldfld "STRUCT.D As Integer" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: call "Sub Clazz.Goo(ByRef Integer)" IL_0013: ldarg.0 IL_0014: ldfld "Clazz._Closure$__1-0.$VB$Local_x As STRUCT" IL_0019: ret } ]]>) End Sub <Fact()> Public Sub TestWith_PropertyAccess_Simple() CompileAndVerify( <compilation> <file name="a.vb"> Interface IBar Property F As Integer End Interface Structure Clazz Implements IBar Public Property F As Integer Implements IBar.F Sub S() With Me .F += 1 End With End Sub End Structure </file> </compilation>). VerifyDiagnostics(). VerifyIL("Clazz.S", <![CDATA[ { // Code size 15 (0xf) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: call "Function Clazz.get_F() As Integer" IL_0007: ldc.i4.1 IL_0008: add.ovf IL_0009: call "Sub Clazz.set_F(Integer)" IL_000e: ret } ]]>) End Sub <Fact()> Public Sub TestWith_DictionaryAccess_Simple() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure Clazz Sub TEST() Dim x As New Clazz With x Console.Write(!Success) !A = "aaa" End With End Sub Default Public Property F(s As String) As String Get Return s End Get Set(value As String) End Set End Property Shared Sub Main(args() As String) Call New Clazz().TEST() End Sub End Structure </file> </compilation>, expectedOutput:="Success"). VerifyDiagnostics(). VerifyIL("Clazz.TEST", <![CDATA[ { // Code size 43 (0x2b) .maxstack 3 .locals init (Clazz V_0) //x IL_0000: ldloca.s V_0 IL_0002: initobj "Clazz" IL_0008: ldloca.s V_0 IL_000a: ldstr "Success" IL_000f: call "Function Clazz.get_F(String) As String" IL_0014: call "Sub System.Console.Write(String)" IL_0019: ldloca.s V_0 IL_001b: ldstr "A" IL_0020: ldstr "aaa" IL_0025: call "Sub Clazz.set_F(String, String)" IL_002a: ret } ]]>) End Sub <Fact()> Public Sub TestWith_DictionaryAccess_ArrayAccess_Lambda() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure Clazz Sub TEST(x() As Clazz, i As Integer) With x(i - 5) Console.Write(!Success) Console.Write(" ") Dim _sub As Action = Sub() Console.Write(!Lambda) End Sub _sub() End With End Sub Default Public Property F(s As String) As String Get Return s End Get Set(value As String) End Set End Property Shared Sub Main(args() As String) Call New Clazz().TEST(New Clazz() {New Clazz}, 5) End Sub End Structure </file> </compilation>, expectedOutput:="Success Lambda") c.VerifyDiagnostics() c.VerifyIL("Clazz.TEST", <![CDATA[ { // Code size 82 (0x52) .maxstack 3 .locals init (Clazz._Closure$__1-0 V_0) //$VB$Closure_0 IL_0000: newobj "Sub Clazz._Closure$__1-0..ctor()" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.1 IL_0008: stfld "Clazz._Closure$__1-0.$W2 As Clazz()" IL_000d: ldloc.0 IL_000e: ldarg.2 IL_000f: ldc.i4.5 IL_0010: sub.ovf IL_0011: stfld "Clazz._Closure$__1-0.$W3 As Integer" IL_0016: ldloc.0 IL_0017: ldfld "Clazz._Closure$__1-0.$W2 As Clazz()" IL_001c: ldloc.0 IL_001d: ldfld "Clazz._Closure$__1-0.$W3 As Integer" IL_0022: ldelema "Clazz" IL_0027: ldstr "Success" IL_002c: call "Function Clazz.get_F(String) As String" IL_0031: call "Sub System.Console.Write(String)" IL_0036: ldstr " " IL_003b: call "Sub System.Console.Write(String)" IL_0040: ldloc.0 IL_0041: ldftn "Sub Clazz._Closure$__1-0._Lambda$__0()" IL_0047: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_004c: callvirt "Sub System.Action.Invoke()" IL_0051: ret } ]]>) c.VerifyIL("Clazz._Closure$__1-0._Lambda$__0", <![CDATA[ { // Code size 33 (0x21) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld "Clazz._Closure$__1-0.$W2 As Clazz()" IL_0006: ldarg.0 IL_0007: ldfld "Clazz._Closure$__1-0.$W3 As Integer" IL_000c: ldelema "Clazz" IL_0011: ldstr "Lambda" IL_0016: call "Function Clazz.get_F(String) As String" IL_001b: call "Sub System.Console.Write(String)" IL_0020: ret } ]]>) End Sub <Fact()> Public Sub TestWith_MemberAccess_ArrayAccess_Lambda() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure Clazz Sub TEST(x() As Clazz, i As Integer) With x(i - 5) Console.Write(.F("Success")) Console.Write(" ") Dim _sub As Action = Sub() Console.Write(.F("Lambda")) End Sub _sub() End With End Sub Default Public Property F(s As String) As String Get Return s End Get Set(value As String) End Set End Property Shared Sub Main(args() As String) Call New Clazz().TEST(New Clazz() {New Clazz}, 5) End Sub End Structure </file> </compilation>, expectedOutput:="Success Lambda") c.VerifyDiagnostics() c.VerifyIL("Clazz.TEST", <![CDATA[ { // Code size 82 (0x52) .maxstack 3 .locals init (Clazz._Closure$__1-0 V_0) //$VB$Closure_0 IL_0000: newobj "Sub Clazz._Closure$__1-0..ctor()" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.1 IL_0008: stfld "Clazz._Closure$__1-0.$W2 As Clazz()" IL_000d: ldloc.0 IL_000e: ldarg.2 IL_000f: ldc.i4.5 IL_0010: sub.ovf IL_0011: stfld "Clazz._Closure$__1-0.$W3 As Integer" IL_0016: ldloc.0 IL_0017: ldfld "Clazz._Closure$__1-0.$W2 As Clazz()" IL_001c: ldloc.0 IL_001d: ldfld "Clazz._Closure$__1-0.$W3 As Integer" IL_0022: ldelema "Clazz" IL_0027: ldstr "Success" IL_002c: call "Function Clazz.get_F(String) As String" IL_0031: call "Sub System.Console.Write(String)" IL_0036: ldstr " " IL_003b: call "Sub System.Console.Write(String)" IL_0040: ldloc.0 IL_0041: ldftn "Sub Clazz._Closure$__1-0._Lambda$__0()" IL_0047: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_004c: callvirt "Sub System.Action.Invoke()" IL_0051: ret } ]]>) c.VerifyIL("Clazz._Closure$__1-0._Lambda$__0", <![CDATA[ { // Code size 33 (0x21) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld "Clazz._Closure$__1-0.$W2 As Clazz()" IL_0006: ldarg.0 IL_0007: ldfld "Clazz._Closure$__1-0.$W3 As Integer" IL_000c: ldelema "Clazz" IL_0011: ldstr "Lambda" IL_0016: call "Function Clazz.get_F(String) As String" IL_001b: call "Sub System.Console.Write(String)" IL_0020: ret } ]]>) End Sub <Fact()> Public Sub TestWith_DictionaryAccess_NestedWithWithQuery() Dim c = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Linq Structure Clazz Public Str As String Public Sub New(_str As String) Me.Str = _str End Sub Sub TEST(x() As Clazz, i As Integer) With x(i - 5) With !One With !Two With !Three Console.Write(!Success.Str) Console.Write(" || ") Dim q = From z In "*" Select U = !Query.Str Console.Write(q.FirstOrDefault) End With End With End With End With End Sub Default Public Property F(s As String) As Clazz Get Return New Clazz(Me.Str &amp; " > " &amp; s) End Get Set(value As Clazz) End Set End Property Shared Sub Main(args() As String) Dim p = New Clazz(0) {} p(0) = New Clazz("##") Call New Clazz().TEST(p, 5) End Sub End Structure </file> </compilation>, expectedOutput:="## > One > Two > Three > Success || ## > One > Two > Three > Query") c.VerifyDiagnostics() c.VerifyIL("Clazz.TEST", <![CDATA[ { // Code size 142 (0x8e) .maxstack 3 .locals init (Clazz V_0, //$W0 Clazz V_1, //$W1 Clazz._Closure$__3-0 V_2) //$VB$Closure_2 IL_0000: ldarg.1 IL_0001: ldarg.2 IL_0002: ldc.i4.5 IL_0003: sub.ovf IL_0004: ldelema "Clazz" IL_0009: ldstr "One" IL_000e: call "Function Clazz.get_F(String) As Clazz" IL_0013: stloc.0 IL_0014: ldloca.s V_0 IL_0016: ldstr "Two" IL_001b: call "Function Clazz.get_F(String) As Clazz" IL_0020: stloc.1 IL_0021: newobj "Sub Clazz._Closure$__3-0..ctor()" IL_0026: stloc.2 IL_0027: ldloc.2 IL_0028: ldloca.s V_1 IL_002a: ldstr "Three" IL_002f: call "Function Clazz.get_F(String) As Clazz" IL_0034: stfld "Clazz._Closure$__3-0.$W2 As Clazz" IL_0039: ldloc.2 IL_003a: ldflda "Clazz._Closure$__3-0.$W2 As Clazz" IL_003f: ldstr "Success" IL_0044: call "Function Clazz.get_F(String) As Clazz" IL_0049: ldfld "Clazz.Str As String" IL_004e: call "Sub System.Console.Write(String)" IL_0053: ldstr " || " IL_0058: call "Sub System.Console.Write(String)" IL_005d: ldstr "*" IL_0062: ldloc.2 IL_0063: ldftn "Function Clazz._Closure$__3-0._Lambda$__0(Char) As String" IL_0069: newobj "Sub System.Func(Of Char, String)..ctor(Object, System.IntPtr)" IL_006e: call "Function System.Linq.Enumerable.Select(Of Char, String)(System.Collections.Generic.IEnumerable(Of Char), System.Func(Of Char, String)) As System.Collections.Generic.IEnumerable(Of String)" IL_0073: call "Function System.Linq.Enumerable.FirstOrDefault(Of String)(System.Collections.Generic.IEnumerable(Of String)) As String" IL_0078: call "Sub System.Console.Write(String)" IL_007d: ldloca.s V_1 IL_007f: initobj "Clazz" IL_0085: ldloca.s V_0 IL_0087: initobj "Clazz" IL_008d: ret } ]]>) c.VerifyIL("Clazz._Closure$__3-0._Lambda$__0", <![CDATA[ { // Code size 22 (0x16) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda "Clazz._Closure$__3-0.$W2 As Clazz" IL_0006: ldstr "Query" IL_000b: call "Function Clazz.get_F(String) As Clazz" IL_0010: ldfld "Clazz.Str As String" IL_0015: ret } ]]>) End Sub <Fact()> Public Sub TestWith_ByRefExtensionMethodOfLValuePlaceholder() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Runtime.CompilerServices Class C1 Public Field As Integer Public Sub New(p As Integer) Field = p End Sub End Class Module Program Sub Main(args As String()) With New C1(23) Console.WriteLine(.Field) .Goo() Console.WriteLine(.Field) End With End Sub &lt;Extension()&gt; Public Sub Goo(ByRef x As C1) x = New C1(42) Console.WriteLine(x.Field) End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>, expectedOutput:=<![CDATA[ 23 42 23 ]]>). VerifyDiagnostics() End Sub <Fact(), WorkItem(2640, "https://github.com/dotnet/roslyn/issues/2640")> Public Sub WithUnusedArrayElement() CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Private Structure MyStructure Public x As Single End Structure Sub Main() Dim unusedArrayInWith(0) As MyStructure With unusedArrayInWith(GetIndex()) System.Console.WriteLine("Hello, World") End With End Sub Function GetIndex() as Integer System.Console.WriteLine("GetIndex") Return 0 End Function End Module </file> </compilation>, options:=TestOptions.ReleaseExe, expectedOutput:=<![CDATA[ GetIndex Hello, World ]]>) End Sub <Fact()> <WorkItem(16968, "https://github.com/dotnet/roslyn/issues/16968")> Public Sub WithExpressionIsAccessedFromLambdaExecutedAfterTheBlock() CompileAndVerify( <compilation> <file name="a.vb"> Module Module1 Private f As EventOwner Sub Main() f = New EventOwner() With f AddHandler .Baz, Sub() .Bar = "called" End Sub End With f.RaiseBaz() System.Console.WriteLine(f.Bar) End Sub End Module Class EventOwner Public Property Bar As String Public Event Baz As System.Action Public Sub RaiseBaz() RaiseEvent Baz() End Sub End Class </file> </compilation>, expectedOutput:="called") End Sub End Class End Namespace
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/EditorFeatures/CSharpTest/InvertConditional/InvertConditionalTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.InvertConditional; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InvertConditional { public partial class InvertConditionalTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpInvertConditionalCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertConditional)] public async Task InvertConditional1() { await TestInRegularAndScriptAsync( @"class C { void M(bool x, int a, int b) { var c = x [||]? a : b; } }", @"class C { void M(bool x, int a, int b) { var c = !x ? b : a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertConditional)] public async Task InvertConditional2() { await TestInRegularAndScriptAsync( @"class C { void M(bool x, int a, int b) { var c = !x [||]? a : b; } }", @"class C { void M(bool x, int a, int b) { var c = x ? b : a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertConditional)] public async Task TestTrivia() { await TestInRegularAndScriptAsync( @"class C { void M(bool x, int a, int b) { var c = [||]x ? a : b; } }", @"class C { void M(bool x, int a, int b) { var c = !x ? b : a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertConditional)] public async Task TestTrivia1() { await TestInRegularAndScriptAsync( @"class C { void M(bool x, int a, int b) { var c = [||]x ? a : b; } }", @"class C { void M(bool x, int a, int b) { var c = !x ? b : a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertConditional)] public async Task TestTrivia2() { // We currently do not move trivia along with the true/false parts. We could consider // trying to intelligently do that in the future. It would require moving the comments, // but preserving the whitespace/newlines. await TestInRegularAndScriptAsync( @"class C { void M(bool x, int a, int b) { var c = [||]x ? a /*trivia1*/ : b /*trivia2*/; } }", @"class C { void M(bool x, int a, int b) { var c = !x ? b /*trivia1*/ : a /*trivia2*/; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertConditional)] public async Task TestStartOfConditional() { await TestInRegularAndScriptAsync( @"class C { void M(bool x, int a, int b) { var c = [||]x ? a : b; } }", @"class C { void M(bool x, int a, int b) { var c = !x ? b : a; } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertConditional)] public async Task TestAfterCondition() { await TestInRegularAndScriptAsync( @"class C { void M(bool x, int a, int b) { var c = x ? a [||]: b; } }", @"class C { void M(bool x, int a, int b) { var c = !x ? b : a; } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.InvertConditional; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InvertConditional { public partial class InvertConditionalTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpInvertConditionalCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertConditional)] public async Task InvertConditional1() { await TestInRegularAndScriptAsync( @"class C { void M(bool x, int a, int b) { var c = x [||]? a : b; } }", @"class C { void M(bool x, int a, int b) { var c = !x ? b : a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertConditional)] public async Task InvertConditional2() { await TestInRegularAndScriptAsync( @"class C { void M(bool x, int a, int b) { var c = !x [||]? a : b; } }", @"class C { void M(bool x, int a, int b) { var c = x ? b : a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertConditional)] public async Task TestTrivia() { await TestInRegularAndScriptAsync( @"class C { void M(bool x, int a, int b) { var c = [||]x ? a : b; } }", @"class C { void M(bool x, int a, int b) { var c = !x ? b : a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertConditional)] public async Task TestTrivia1() { await TestInRegularAndScriptAsync( @"class C { void M(bool x, int a, int b) { var c = [||]x ? a : b; } }", @"class C { void M(bool x, int a, int b) { var c = !x ? b : a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertConditional)] public async Task TestTrivia2() { // We currently do not move trivia along with the true/false parts. We could consider // trying to intelligently do that in the future. It would require moving the comments, // but preserving the whitespace/newlines. await TestInRegularAndScriptAsync( @"class C { void M(bool x, int a, int b) { var c = [||]x ? a /*trivia1*/ : b /*trivia2*/; } }", @"class C { void M(bool x, int a, int b) { var c = !x ? b /*trivia1*/ : a /*trivia2*/; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertConditional)] public async Task TestStartOfConditional() { await TestInRegularAndScriptAsync( @"class C { void M(bool x, int a, int b) { var c = [||]x ? a : b; } }", @"class C { void M(bool x, int a, int b) { var c = !x ? b : a; } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertConditional)] public async Task TestAfterCondition() { await TestInRegularAndScriptAsync( @"class C { void M(bool x, int a, int b) { var c = x ? a [||]: b; } }", @"class C { void M(bool x, int a, int b) { var c = !x ? b : a; } }"); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/VSTypeScriptInlineRenameLocationSet.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal sealed class VSTypeScriptInlineRenameLocationSet : IInlineRenameLocationSet { private readonly IVSTypeScriptInlineRenameLocationSet _set; public VSTypeScriptInlineRenameLocationSet(IVSTypeScriptInlineRenameLocationSet set) { Contract.ThrowIfNull(set); _set = set; Locations = set.Locations?.Select(x => new InlineRenameLocation(x.Document, x.TextSpan)).ToList(); } public IList<InlineRenameLocation> Locations { get; } public async Task<IInlineRenameReplacementInfo> GetReplacementsAsync(string replacementText, OptionSet optionSet, CancellationToken cancellationToken) { var info = await _set.GetReplacementsAsync(replacementText, optionSet, cancellationToken).ConfigureAwait(false); if (info != null) { return new VSTypeScriptInlineRenameReplacementInfo(info); } else { return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal sealed class VSTypeScriptInlineRenameLocationSet : IInlineRenameLocationSet { private readonly IVSTypeScriptInlineRenameLocationSet _set; public VSTypeScriptInlineRenameLocationSet(IVSTypeScriptInlineRenameLocationSet set) { Contract.ThrowIfNull(set); _set = set; Locations = set.Locations?.Select(x => new InlineRenameLocation(x.Document, x.TextSpan)).ToList(); } public IList<InlineRenameLocation> Locations { get; } public async Task<IInlineRenameReplacementInfo> GetReplacementsAsync(string replacementText, OptionSet optionSet, CancellationToken cancellationToken) { var info = await _set.GetReplacementsAsync(replacementText, optionSet, cancellationToken).ConfigureAwait(false); if (info != null) { return new VSTypeScriptInlineRenameReplacementInfo(info); } else { return null; } } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Analyzers/CSharp/Tests/UseExpressionBody/UseExpressionBodyForPropertiesAnalyzerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { using VerifyCS = CSharpCodeFixVerifier< UseExpressionBodyDiagnosticAnalyzer, UseExpressionBodyCodeFixProvider>; public class UseExpressionBodyForPropertiesAnalyzerTests { private static async Task TestWithUseExpressionBody(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, }, MarkupOptions = MarkupOptions.None, }.RunAsync(); } private static async Task TestWithUseBlockBody(string code, string fixedCode) { await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, }, MarkupOptions = MarkupOptions.None, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody1() { var code = @" class C { int Bar() { return 0; } {|IDE0025:int Goo { get { return Bar(); } }|} }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo => Bar(); }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithSetter() { var code = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } set { } } }"; await TestWithUseExpressionBody(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithAttribute() { var code = @" using System; class AAttribute : Attribute {} class C { int Bar() { return 0; } int Goo { [A] get { return Bar(); } } }"; await TestWithUseExpressionBody(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingOnSetter1() { var code = @" class C { void Bar() { } int Goo { set { Bar(); } } }"; await TestWithUseExpressionBody(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody3() { var code = @" using System; class C { {|IDE0025:int Goo { get { throw new NotImplementedException(); } }|} }"; var fixedCode = @" using System; class C { int Goo => throw new NotImplementedException(); }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody4() { var code = @" using System; class C { {|IDE0025:int Goo { get { throw new NotImplementedException(); // comment } }|} }"; var fixedCode = @" using System; class C { int Goo => throw new NotImplementedException(); // comment }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody1() { var code = @" class C { int Bar() { return 0; } {|IDE0025:int Goo => Bar();|} }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } } }"; await TestWithUseBlockBody(code, fixedCode); } [WorkItem(20363, "https://github.com/dotnet/roslyn/issues/20363")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyForAccessorEventWhenAccessorWantExpression1() { var code = @" class C { int Bar() { return 0; } {|IDE0025:int Goo => Bar();|} }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get => Bar(); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenPossible }, }, MarkupOptions = MarkupOptions.None, NumberOfFixAllIterations = 2, NumberOfIncrementalIterations = 2, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody3() { var code = @" using System; class C { {|IDE0025:int Goo => throw new NotImplementedException();|} }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } }"; await TestWithUseBlockBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody4() { var code = @" using System; class C { {|IDE0025:int Goo => throw new NotImplementedException();|} // comment }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); // comment } } }"; await TestWithUseBlockBody(code, fixedCode); } [WorkItem(16386, "https://github.com/dotnet/roslyn/issues/16386")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBodyKeepTrailingTrivia() { var code = @" class C { private string _prop = ""HELLO THERE!""; {|IDE0025:public string Prop { get { return _prop; } }|} public string OtherThing => ""Pickles""; }"; var fixedCode = @" class C { private string _prop = ""HELLO THERE!""; public string Prop => _prop; public string OtherThing => ""Pickles""; }"; await TestWithUseExpressionBody(code, fixedCode); } [WorkItem(19235, "https://github.com/dotnet/roslyn/issues/19235")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestDirectivesInBlockBody1() { var code = @" class C { int Bar() { return 0; } int Baz() { return 0; } {|IDE0025:int Goo { get { #if true return Bar(); #else return Baz(); #endif } }|} }"; var fixedCode = @" class C { int Bar() { return 0; } int Baz() { return 0; } int Goo => #if true Bar(); #else return Baz(); #endif }"; await TestWithUseExpressionBody(code, fixedCode); } [WorkItem(19235, "https://github.com/dotnet/roslyn/issues/19235")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestDirectivesInBlockBody2() { var code = @" class C { int Bar() { return 0; } int Baz() { return 0; } {|IDE0025:int Goo { get { #if false return Bar(); #else return Baz(); #endif } }|} }"; var fixedCode = @" class C { int Bar() { return 0; } int Baz() { return 0; } int Goo => #if false return Bar(); #else Baz(); #endif }"; await TestWithUseExpressionBody(code, fixedCode); } [WorkItem(19235, "https://github.com/dotnet/roslyn/issues/19235")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithDirectivesInExpressionBody1() { var code = @" class C { int Bar() { return 0; } int Baz() { return 0; } int Goo => #if true Bar(); #else Baz(); #endif }"; await TestWithUseBlockBody(code, code); } [WorkItem(19235, "https://github.com/dotnet/roslyn/issues/19235")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithDirectivesInExpressionBody2() { var code = @" class C { int Bar() { return 0; } int Baz() { return 0; } int Goo => #if false Bar(); #else Baz(); #endif }"; await TestWithUseBlockBody(code, code); } [WorkItem(19193, "https://github.com/dotnet/roslyn/issues/19193")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMoveTriviaFromExpressionToReturnStatement() { // TODO: This test is unrelated to properties. It should be moved to UseExpressionBodyForMethodsAnalyzerTests. var code = @" class C { {|IDE0022:int Goo(int i) => //comment i * i;|} }"; var fixedCode = @" class C { int Goo(int i) { //comment return i * i; } }"; await TestWithUseBlockBody(code, fixedCode); } [WorkItem(20362, "https://github.com/dotnet/roslyn/issues/20362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfHasThrowExpressionPriorToCSharp7() { var code = @" using System; class C { {|IDE0025:int Goo => {|CS8059:throw new NotImplementedException()|};|} }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); } [WorkItem(20362, "https://github.com/dotnet/roslyn/issues/20362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfHasThrowExpressionPriorToCSharp7_FixAll() { var code = @" using System; class C { {|IDE0025:int Goo => {|CS8059:throw new NotImplementedException()|};|} {|IDE0025:int Bar => {|CS8059:throw new NotImplementedException()|};|} }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } int Bar { get { throw new NotImplementedException(); } } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { using VerifyCS = CSharpCodeFixVerifier< UseExpressionBodyDiagnosticAnalyzer, UseExpressionBodyCodeFixProvider>; public class UseExpressionBodyForPropertiesAnalyzerTests { private static async Task TestWithUseExpressionBody(string code, string fixedCode, LanguageVersion version = LanguageVersion.CSharp8) { await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, LanguageVersion = version, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.WhenPossible }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, }, MarkupOptions = MarkupOptions.None, }.RunAsync(); } private static async Task TestWithUseBlockBody(string code, string fixedCode) { await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.Never }, }, MarkupOptions = MarkupOptions.None, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody1() { var code = @" class C { int Bar() { return 0; } {|IDE0025:int Goo { get { return Bar(); } }|} }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo => Bar(); }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithSetter() { var code = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } set { } } }"; await TestWithUseExpressionBody(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithAttribute() { var code = @" using System; class AAttribute : Attribute {} class C { int Bar() { return 0; } int Goo { [A] get { return Bar(); } } }"; await TestWithUseExpressionBody(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingOnSetter1() { var code = @" class C { void Bar() { } int Goo { set { Bar(); } } }"; await TestWithUseExpressionBody(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody3() { var code = @" using System; class C { {|IDE0025:int Goo { get { throw new NotImplementedException(); } }|} }"; var fixedCode = @" using System; class C { int Goo => throw new NotImplementedException(); }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody4() { var code = @" using System; class C { {|IDE0025:int Goo { get { throw new NotImplementedException(); // comment } }|} }"; var fixedCode = @" using System; class C { int Goo => throw new NotImplementedException(); // comment }"; await TestWithUseExpressionBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody1() { var code = @" class C { int Bar() { return 0; } {|IDE0025:int Goo => Bar();|} }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get { return Bar(); } } }"; await TestWithUseBlockBody(code, fixedCode); } [WorkItem(20363, "https://github.com/dotnet/roslyn/issues/20363")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyForAccessorEventWhenAccessorWantExpression1() { var code = @" class C { int Bar() { return 0; } {|IDE0025:int Goo => Bar();|} }"; var fixedCode = @" class C { int Bar() { return 0; } int Goo { get => Bar(); } }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ExpressionBodyPreference.Never }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ExpressionBodyPreference.WhenPossible }, }, MarkupOptions = MarkupOptions.None, NumberOfFixAllIterations = 2, NumberOfIncrementalIterations = 2, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody3() { var code = @" using System; class C { {|IDE0025:int Goo => throw new NotImplementedException();|} }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } }"; await TestWithUseBlockBody(code, fixedCode); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody4() { var code = @" using System; class C { {|IDE0025:int Goo => throw new NotImplementedException();|} // comment }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); // comment } } }"; await TestWithUseBlockBody(code, fixedCode); } [WorkItem(16386, "https://github.com/dotnet/roslyn/issues/16386")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBodyKeepTrailingTrivia() { var code = @" class C { private string _prop = ""HELLO THERE!""; {|IDE0025:public string Prop { get { return _prop; } }|} public string OtherThing => ""Pickles""; }"; var fixedCode = @" class C { private string _prop = ""HELLO THERE!""; public string Prop => _prop; public string OtherThing => ""Pickles""; }"; await TestWithUseExpressionBody(code, fixedCode); } [WorkItem(19235, "https://github.com/dotnet/roslyn/issues/19235")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestDirectivesInBlockBody1() { var code = @" class C { int Bar() { return 0; } int Baz() { return 0; } {|IDE0025:int Goo { get { #if true return Bar(); #else return Baz(); #endif } }|} }"; var fixedCode = @" class C { int Bar() { return 0; } int Baz() { return 0; } int Goo => #if true Bar(); #else return Baz(); #endif }"; await TestWithUseExpressionBody(code, fixedCode); } [WorkItem(19235, "https://github.com/dotnet/roslyn/issues/19235")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestDirectivesInBlockBody2() { var code = @" class C { int Bar() { return 0; } int Baz() { return 0; } {|IDE0025:int Goo { get { #if false return Bar(); #else return Baz(); #endif } }|} }"; var fixedCode = @" class C { int Bar() { return 0; } int Baz() { return 0; } int Goo => #if false return Bar(); #else Baz(); #endif }"; await TestWithUseExpressionBody(code, fixedCode); } [WorkItem(19235, "https://github.com/dotnet/roslyn/issues/19235")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithDirectivesInExpressionBody1() { var code = @" class C { int Bar() { return 0; } int Baz() { return 0; } int Goo => #if true Bar(); #else Baz(); #endif }"; await TestWithUseBlockBody(code, code); } [WorkItem(19235, "https://github.com/dotnet/roslyn/issues/19235")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithDirectivesInExpressionBody2() { var code = @" class C { int Bar() { return 0; } int Baz() { return 0; } int Goo => #if false Bar(); #else Baz(); #endif }"; await TestWithUseBlockBody(code, code); } [WorkItem(19193, "https://github.com/dotnet/roslyn/issues/19193")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMoveTriviaFromExpressionToReturnStatement() { // TODO: This test is unrelated to properties. It should be moved to UseExpressionBodyForMethodsAnalyzerTests. var code = @" class C { {|IDE0022:int Goo(int i) => //comment i * i;|} }"; var fixedCode = @" class C { int Goo(int i) { //comment return i * i; } }"; await TestWithUseBlockBody(code, fixedCode); } [WorkItem(20362, "https://github.com/dotnet/roslyn/issues/20362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfHasThrowExpressionPriorToCSharp7() { var code = @" using System; class C { {|IDE0025:int Goo => {|CS8059:throw new NotImplementedException()|};|} }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); } [WorkItem(20362, "https://github.com/dotnet/roslyn/issues/20362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferToConvertToBlockEvenIfExpressionBodyPreferredIfHasThrowExpressionPriorToCSharp7_FixAll() { var code = @" using System; class C { {|IDE0025:int Goo => {|CS8059:throw new NotImplementedException()|};|} {|IDE0025:int Bar => {|CS8059:throw new NotImplementedException()|};|} }"; var fixedCode = @" using System; class C { int Goo { get { throw new NotImplementedException(); } } int Bar { get { throw new NotImplementedException(); } } }"; await TestWithUseExpressionBody(code, fixedCode, LanguageVersion.CSharp6); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/Core/Portable/Emit/AnonymousTypeValue.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Cci; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Emit { [DebuggerDisplay("{Name, nq}")] internal struct AnonymousTypeValue { public readonly string Name; public readonly int UniqueIndex; public readonly ITypeDefinition Type; public AnonymousTypeValue(string name, int uniqueIndex, ITypeDefinition type) { Debug.Assert(!string.IsNullOrEmpty(name)); Debug.Assert(uniqueIndex >= 0); this.Name = name; this.UniqueIndex = uniqueIndex; this.Type = type; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.Cci; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Emit { [DebuggerDisplay("{Name, nq}")] internal struct AnonymousTypeValue { public readonly string Name; public readonly int UniqueIndex; public readonly ITypeDefinition Type; public AnonymousTypeValue(string name, int uniqueIndex, ITypeDefinition type) { Debug.Assert(!string.IsNullOrEmpty(name)); Debug.Assert(uniqueIndex >= 0); this.Name = name; this.UniqueIndex = uniqueIndex; this.Type = type; } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/CSharp/Test/Syntax/Parsing/ParsingErrorRecoveryTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ParsingErrorRecoveryTests : CSharpTestBase { private CompilationUnitSyntax ParseTree(string text, CSharpParseOptions options = null) { return SyntaxFactory.ParseCompilationUnit(text, options: options); } [Theory] [InlineData("public")] [InlineData("internal")] [InlineData("protected")] [InlineData("private")] public void AccessibilityModifierErrorRecovery(string accessibility) { var file = ParseTree($@" class C {{ void M() {{ // bad visibility modifier {accessibility} void localFunc() {{}} }} void M2() {{ typing {accessibility} void localFunc() {{}} }} void M3() {{ // Ambiguous between local func with bad modifier and missing closing // brace on previous method. Parsing currently assumes the former, // assuming the tokens are parseable as a local func. {accessibility} void M4() {{}} }}"); Assert.NotNull(file); file.GetDiagnostics().Verify( // (7,9): error CS0106: The modifier '{accessibility}' is not valid for this item // {accessibility} void localFunc() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, accessibility).WithArguments(accessibility).WithLocation(7, 9), // (11,15): error CS1002: ; expected // typing Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(11, 15), // (12,9): error CS0106: The modifier '{accessibility}' is not valid for this item // {accessibility} void localFunc() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, accessibility).WithArguments(accessibility).WithLocation(12, 9), // (19,5): error CS0106: The modifier '{accessibility}' is not valid for this item // {accessibility} void M4() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, accessibility).WithArguments(accessibility).WithLocation(19, 5), // (20,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(20, 2) ); } [Fact] public void TestGlobalAttributeGarbageAfterLocation() { var text = "[assembly: $"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[2].Code); } [Fact] public void TestGlobalAttributeUsingAfterLocation() { var text = "[assembly: using n;"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_UsingAfterElements, file.Errors()[2].Code); } [Fact] public void TestGlobalAttributeExternAfterLocation() { var text = "[assembly: extern alias a;"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_ExternAfterElements, file.Errors()[2].Code); } [Fact] public void TestGlobalAttributeNamespaceAfterLocation() { var text = "[assembly: namespace n { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestGlobalAttributeClassAfterLocation() { var text = "[assembly: class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestGlobalAttributeAttributeAfterLocation() { var text = "[assembly: [assembly: attr]"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestGlobalAttributeEOFAfterLocation() { var text = "[assembly: "; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestGlobalAttributeGarbageAfterAttribute() { var text = "[assembly: a $"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestGlobalAttributeGarbageAfterParameterStart() { var text = "[assembly: a( $"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[2].Code); } [Fact] public void TestGlobalAttributeGarbageAfterParameter() { var text = "[assembly: a(b $"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[2].Code); } [Fact] public void TestGlobalAttributeMissingCommaBetweenParameters() { var text = "[assembly: a(b c)"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestGlobalAttributeWithGarbageBetweenParameters() { var text = "[assembly: a(b $ c)"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[2].Code); } [Fact] public void TestGlobalAttributeWithGarbageBetweenAttributes() { var text = "[assembly: a $ b"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(3, file.Errors().Length); file.Errors().Verify( // error CS1056: Unexpected character '$' Diagnostic(ErrorCode.ERR_UnexpectedCharacter).WithArguments("$"), // error CS1003: Syntax error, ',' expected Diagnostic(ErrorCode.ERR_SyntaxError).WithArguments(",", ""), // error CS1003: Syntax error, ']' expected Diagnostic(ErrorCode.ERR_SyntaxError).WithArguments("]", "") ); } [Fact] public void TestGlobalAttributeWithUsingAfterParameterStart() { var text = "[assembly: a( using n;"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_UsingAfterElements, file.Errors()[2].Code); } [Fact] public void TestGlobalAttributeWithExternAfterParameterStart() { var text = "[assembly: a( extern alias n;"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_ExternAfterElements, file.Errors()[2].Code); } [Fact] public void TestGlobalAttributeWithNamespaceAfterParameterStart() { var text = "[assembly: a( namespace n { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestGlobalAttributeWithClassAfterParameterStart() { var text = "[assembly: a( class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestGarbageBeforeNamespace() { var text = "$ namespace n { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterNamespace() { var text = "namespace n { } $"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void MultipleSubsequentMisplacedCharactersSingleError1() { var text = "namespace n { } ,,,,,,,,"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_EOFExpected, file.Errors()[0].Code); } [Fact] public void MultipleSubsequentMisplacedCharactersSingleError2() { var text = ",,,, namespace n { } ,,,,"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_EOFExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_EOFExpected, file.Errors()[1].Code); } [Fact] public void TestGarbageInsideNamespace() { var text = "namespace n { $ }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestIncompleteGlobalMembers() { var text = @" asas] extern alias A; asas using System; sadasdasd] [assembly: goo] class C { } [a]fod; [b"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); } [Fact] public void TestAttributeWithGarbageAfterStart() { var text = "[ $"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.IncompleteMember, file.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[2].Code); } [Fact] public void TestAttributeWithGarbageAfterName() { var text = "[a $"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.IncompleteMember, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestAttributeWithClassAfterBracket() { var text = "[ class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestAttributeWithClassAfterName() { var text = "[a class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestAttributeWithClassAfterParameterStart() { var text = "[a( class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestAttributeWithClassAfterParameter() { var text = "[a(b class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestAttributeWithClassAfterParameterAndComma() { var text = "[a(b, class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[2].Code); } [Fact] public void TestAttributeWithCommaAfterParameterStart() { var text = "[a(, class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[3].Code); } [Fact] public void TestAttributeWithCommasAfterParameterStart() { var text = "[a(,, class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(5, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[3].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[4].Code); } [Fact] public void TestAttributeWithMissingFirstParameter() { var text = "[a(, b class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[2].Code); } [Fact] public void TestNamespaceWithGarbage() { var text = "namespace n { $ }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestNamespaceWithUnexpectedKeyword() { var text = "namespace n { int }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_NamespaceUnexpected, file.Errors()[0].Code); } [Fact] public void TestNamespaceWithUnexpectedBracing() { var text = "namespace n { { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_EOFExpected, file.Errors()[0].Code); } [Fact] public void TestGlobalNamespaceWithUnexpectedBracingAtEnd() { var text = "namespace n { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_EOFExpected, file.Errors()[0].Code); } [Fact] public void TestGlobalNamespaceWithUnexpectedBracingAtStart() { var text = "} namespace n { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_EOFExpected, file.Errors()[0].Code); } [Fact] public void TestGlobalNamespaceWithOpenBraceBeforeNamespace() { var text = "{ namespace n { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); } [Fact] public void TestPartialNamespace() { var text = "partial namespace n { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(0, file.Errors().Length); } [Fact] public void TestClassAfterStartOfBaseTypeList() { var text = "class c : class b { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); } [Fact] public void TestClassAfterBaseType() { var text = "class c : t class b { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); } [Fact] public void TestClassAfterBaseTypeAndComma() { var text = "class c : t, class b { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); } [Fact] public void TestClassAfterBaseTypesWithMissingComma() { var text = "class c : x y class b { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); } [Fact] public void TestGarbageAfterStartOfBaseTypeList() { var text = "class c : $ { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterBaseType() { var text = "class c : t $ { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterBaseTypeAndComma() { var text = "class c : t, $ { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterBaseTypesWithMissingComma() { var text = "class c : x y $ { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestConstraintAfterStartOfBaseTypeList() { var text = "class c<t> : where t : b { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); } [Fact] public void TestConstraintAfterBaseType() { var text = "class c<t> : x where t : b { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(0, file.Errors().Length); } [Fact] public void TestConstraintAfterBaseTypeComma() { var text = "class c<t> : x, where t : b { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); } [Fact] public void TestConstraintAfterBaseTypes() { var text = "class c<t> : x, y where t : b { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(0, file.Errors().Length); } [Fact] public void TestConstraintAfterBaseTypesWithMissingComma() { var text = "class c<t> : x y where t : b { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestOpenBraceAfterStartOfBaseTypeList() { var text = "class c<t> : { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); } [Fact] public void TestOpenBraceAfterBaseType() { var text = "class c<t> : x { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(0, file.Errors().Length); } [Fact] public void TestOpenBraceAfterBaseTypeComma() { var text = "class c<t> : x, { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); } [Fact] public void TestOpenBraceAfterBaseTypes() { var text = "class c<t> : x, y { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(0, file.Errors().Length); } [Fact] public void TestBaseTypesWithMissingComma() { var text = "class c<t> : x y { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestOpenBraceAfterConstraintStart() { var text = "class c<t> where { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[2].Code); } [Fact] public void TestOpenBraceAfterConstraintName() { var text = "class c<t> where t { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[1].Code); } [Fact] public void TestOpenBraceAfterConstraintNameAndColon() { var text = "class c<t> where t : { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); } [Fact] public void TestOpenBraceAfterConstraintNameAndTypeAndComma() { var text = "class c<t> where t : x, { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); } [Fact] public void TestConstraintAfterConstraintStart() { var text = "class c<t> where where t : a { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[2].Code); } [Fact] public void TestConstraintAfterConstraintName() { var text = "class c<t> where t where t : a { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[1].Code); } [Fact] public void TestConstraintAfterConstraintNameAndColon() { var text = "class c<t> where t : where t : a { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); } [Fact] public void TestConstraintAfterConstraintNameColonTypeAndComma() { var text = "class c<t> where t : a, where t : a { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterConstraintStart() { var text = "class c<t> where $ { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[3].Code); } [Fact] public void TestGarbageAfterConstraintName() { var text = "class c<t> where t $ { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[2].Code); } [Fact] public void TestGarbageAfterConstraintNameAndColon() { var text = "class c<t> where t : $ { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterConstraintNameColonAndType() { var text = "class c<t> where t : x $ { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterConstraintNameColonTypeAndComma() { var text = "class c<t> where t : x, $ { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterGenericClassNameStart() { var text = "class c<$> { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterGenericClassNameType() { var text = "class c<t $> { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterGenericClassNameTypeAndComma() { var text = "class c<t, $> { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestOpenBraceAfterGenericClassNameStart() { var text = "class c< { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestOpenBraceAfterGenericClassNameAndType() { var text = "class c<t { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestClassAfterGenericClassNameStart() { var text = "class c< class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[3].Code); } [Fact] public void TestClassAfterGenericClassNameAndType() { var text = "class c<t class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); } [Fact] public void TestClassAfterGenericClassNameTypeAndComma() { var text = "class c<t, class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[3].Code); } [Fact] public void TestBaseTypeAfterGenericClassNameStart() { var text = "class c< : x { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestBaseTypeAfterGenericClassNameAndType() { var text = "class c<t : x { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestBaseTypeAfterGenericClassNameTypeAndComma() { var text = "class c<t, : x { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestConstraintAfterGenericClassNameStart() { var text = "class c< where t : x { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestConstraintAfterGenericClassNameAndType() { var text = "class c<t where t : x { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestConstraintAfterGenericClassNameTypeAndComma() { var text = "class c<t, where t : x { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestFieldAfterFieldStart() { var text = "class c { int int y; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.IncompleteMember, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[1].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidMemberDecl, file.Errors()[0].Code); } [Fact] public void TestFieldAfterFieldTypeAndName() { var text = "class c { int x int y; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[1].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[0].Code); } [Fact] public void TestFieldAfterFieldTypeNameAndComma() { var text = "class c { int x, int y; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterFieldStart() { var text = "class c { int $ int y; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.IncompleteMember, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidMemberDecl, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_InvalidMemberDecl, file.Errors()[2].Code); } [Fact] public void TestGarbageAfterFieldTypeAndName() { var text = "class c { int x $ int y; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterFieldTypeNameAndComma() { var text = "class c { int x, $ int y; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestEndBraceAfterFieldStart() { var text = "class c { int }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.IncompleteMember, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidMemberDecl, file.Errors()[0].Code); } [Fact] public void TestEndBraceAfterFieldName() { var text = "class c { int x }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[0].Code); } [Fact] public void TestEndBraceAfterFieldNameAndComma() { var text = "class c { int x, }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestEndBraceAfterMethodParameterStart() { var text = "class c { int m( }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestEndBraceAfterMethodParameterType() { var text = "class c { int m(x }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestEndBraceAfterMethodParameterName() { var text = "class c { int m(x y}"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestEndBraceAfterMethodParameterTypeNameAndComma() { var text = "class c { int m(x y, }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[3].Code); } [Fact] public void TestEndBraceAfterMethodParameters() { var text = "class c { int m() }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterMethodParameterStart() { var text = "class c { int m( $ ); }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterMethodParameterType() { var text = "class c { int m( x $ ); }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterMethodParameterTypeAndName() { var text = "class c { int m( x y $ ); }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterMethodParameterTypeNameAndComma() { var text = "class c { int m( x y, $ ); }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[2].Code); } [Fact] public void TestMethodAfterMethodParameterStart() { var text = "class c { int m( public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestMethodAfterMethodParameterType() { var text = "class c { int m(x public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestMethodAfterMethodParameterTypeAndName() { var text = "class c { int m(x y public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestMethodAfterMethodParameterTypeNameAndComma() { var text = "class c { int m(x y, public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[3].Code); } [Fact] public void TestMethodAfterMethodParameterList() { var text = "class c { int m(x y) public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[0].Code); } [Fact] public void TestMethodBodyAfterMethodParameterListStart() { var text = "class c { int m( { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); } [Fact] public void TestSemicolonAfterMethodParameterListStart() { var text = "class c { int m( ; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); } [Fact] public void TestConstructorBodyAfterConstructorParameterListStart() { var text = "class c { c( { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.ConstructorDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); } [Fact] public void TestSemicolonAfterDelegateParameterListStart() { var text = "delegate void d( ;"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var agg = (DelegateDeclarationSyntax)file.Members[0]; Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); } [Fact] public void TestEndBraceAfterIndexerParameterStart() { var text = "class c { int this[ }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); CreateCompilation(text).VerifyDiagnostics( // (1,21): error CS1003: Syntax error, ']' expected // class c { int this[ } Diagnostic(ErrorCode.ERR_SyntaxError, "}").WithArguments("]", "}").WithLocation(1, 21), // (1,21): error CS1514: { expected // class c { int this[ } Diagnostic(ErrorCode.ERR_LbraceExpected, "}").WithLocation(1, 21), // (1,22): error CS1513: } expected // class c { int this[ } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 22), // (1,15): error CS0548: 'c.this': property or indexer must have at least one accessor // class c { int this[ } Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("c.this").WithLocation(1, 15), // (1,19): error CS1551: Indexers must have at least one parameter // class c { int this[ } Diagnostic(ErrorCode.ERR_IndexerNeedsParam, "[").WithLocation(1, 19)); } [Fact] public void TestEndBraceAfterIndexerParameterType() { var text = "class c { int this[x }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[3].Code); } [Fact] public void TestEndBraceAfterIndexerParameterName() { var text = "class c { int this[x y }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); } [Fact] public void TestEndBraceAfterIndexerParameterTypeNameAndComma() { var text = "class c { int this[x y, }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(5, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[3].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[4].Code); } [Fact] public void TestEndBraceAfterIndexerParameters() { var text = "class c { int this[x y] }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterIndexerParameterStart() { var text = "class c { int this[ $ ] { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); CreateCompilation(text).VerifyDiagnostics( // (1,21): error CS1056: Unexpected character '$' // class c { int this[ $ ] { } } Diagnostic(ErrorCode.ERR_UnexpectedCharacter, "").WithArguments("$").WithLocation(1, 21), // (1,15): error CS0548: 'c.this': property or indexer must have at least one accessor // class c { int this[ $ ] { } } Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("c.this").WithLocation(1, 15), // (1,23): error CS1551: Indexers must have at least one parameter // class c { int this[ $ ] { } } Diagnostic(ErrorCode.ERR_IndexerNeedsParam, "]").WithLocation(1, 23)); } [Fact] public void TestGarbageAfterIndexerParameterType() { var text = "class c { int this[ x $ ] { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterIndexerParameterTypeAndName() { var text = "class c { int this[ x y $ ] { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterIndexerParameterTypeNameAndComma() { var text = "class c { int this[ x y, $ ] { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[2].Code); } [Fact] public void TestMethodAfterIndexerParameterStart() { var text = "class c { int this[ public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); CreateCompilation(text).VerifyDiagnostics( // (1,21): error CS1003: Syntax error, ']' expected // class c { int this[ public void m() { } } Diagnostic(ErrorCode.ERR_SyntaxError, "public").WithArguments("]", "public").WithLocation(1, 21), // (1,21): error CS1514: { expected // class c { int this[ public void m() { } } Diagnostic(ErrorCode.ERR_LbraceExpected, "public").WithLocation(1, 21), // (1,21): error CS1513: } expected // class c { int this[ public void m() { } } Diagnostic(ErrorCode.ERR_RbraceExpected, "public").WithLocation(1, 21), // (1,15): error CS0548: 'c.this': property or indexer must have at least one accessor // class c { int this[ public void m() { } } Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("c.this").WithLocation(1, 15), // (1,19): error CS1551: Indexers must have at least one parameter // class c { int this[ public void m() { } } Diagnostic(ErrorCode.ERR_IndexerNeedsParam, "[").WithLocation(1, 19)); } [Fact] public void TestMethodAfterIndexerParameterType() { var text = "class c { int this[x public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[3].Code); } [Fact] public void TestMethodAfterIndexerParameterTypeAndName() { var text = "class c { int this[x y public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); } [Fact] public void TestMethodAfterIndexerParameterTypeNameAndComma() { var text = "class c { int this[x y, public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(5, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[3].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[4].Code); } [Fact] public void TestMethodAfterIndexerParameterList() { var text = "class c { int this[x y] public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); } [Fact] public void TestEOFAfterDelegateStart() { var text = "delegate"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(5, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[3].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[4].Code); } [Fact] public void TestEOFAfterDelegateType() { var text = "delegate d"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[3].Code); } [Fact] public void TestEOFAfterDelegateName() { var text = "delegate void d"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestEOFAfterDelegateParameterStart() { var text = "delegate void d("; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestEOFAfterDelegateParameterType() { var text = "delegate void d(t"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestEOFAfterDelegateParameterTypeName() { var text = "delegate void d(t n"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestEOFAfterDelegateParameterList() { var text = "delegate void d(t n)"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[0].Code); } [Fact] public void TestEOFAfterDelegateParameterTypeNameAndComma() { var text = "delegate void d(t n, "; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[3].Code); } [Fact] public void TestClassAfterDelegateStart() { var text = "delegate class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(5, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[3].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[4].Code); } [Fact] public void TestClassAfterDelegateType() { var text = "delegate d class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[3].Code); } [Fact] public void TestClassAfterDelegateName() { var text = "delegate void d class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestClassAfterDelegateParameterStart() { var text = "delegate void d( class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestClassAfterDelegateParameterType() { var text = "delegate void d(t class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestClassAfterDelegateParameterTypeName() { var text = "delegate void d(t n class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestClassAfterDelegateParameterList() { var text = "delegate void d(t n) class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[0].Code); } [Fact] public void TestClassAfterDelegateParameterTypeNameAndComma() { var text = "delegate void d(t n, class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[3].Code); } [Fact] public void TestGarbageAfterDelegateParameterStart() { var text = "delegate void d($);"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterDelegateParameterType() { var text = "delegate void d(t $);"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterDelegateParameterTypeAndName() { var text = "delegate void d(t n $);"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterDelegateParameterTypeNameAndComma() { var text = "delegate void d(t n, $);"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[2].Code); } [Fact] public void TestGarbageAfterEnumStart() { var text = "enum e { $ }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterEnumName() { var text = "enum e { n $ }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBeforeEnumName() { var text = "enum e { $ n }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAferEnumNameAndComma() { var text = "enum e { n, $ }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAferEnumNameCommaAndName() { var text = "enum e { n, n $ }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBetweenEnumNames() { var text = "enum e { n, $ n }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBetweenEnumNamesWithMissingComma() { var text = "enum e { n $ n }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestGarbageAferEnumNameAndEquals() { var text = "enum e { n = $ }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestEOFAfterEnumStart() { var text = "enum e { "; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestEOFAfterEnumName() { var text = "enum e { n "; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestEOFAfterEnumNameAndComma() { var text = "enum e { n, "; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestClassAfterEnumStart() { var text = "enum e { class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestClassAfterEnumName() { var text = "enum e { n class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestClassAfterEnumNameAndComma() { var text = "enum e { n, class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterFixedFieldRankStart() { var text = "class c { fixed int x[$]; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_ValueExpected, file.Errors()[1].Code); } [Fact] public void TestGarbageBeforeFixedFieldRankSize() { var text = "class c { fixed int x[$ 10]; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterFixedFieldRankSize() { var text = "class c { fixed int x[10 $]; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal(ErrorCode.ERR_SyntaxError, (ErrorCode)file.Errors()[0].Code); //expected comma Assert.Equal(ErrorCode.ERR_UnexpectedCharacter, (ErrorCode)file.Errors()[1].Code); //didn't expect '$' Assert.Equal(ErrorCode.ERR_ValueExpected, (ErrorCode)file.Errors()[2].Code); //expected value after (missing) comma } [Fact] public void TestGarbageAfterFieldTypeRankStart() { var text = "class c { int[$] x; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterFieldTypeRankComma() { var text = "class c { int[,$] x; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBeforeFieldTypeRankComma() { var text = "class c { int[$,] x; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestEndBraceAfterFieldRankStart() { var text = "class c { int[ }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(SyntaxKind.IncompleteMember, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestEndBraceAfterFieldRankComma() { var text = "class c { int[, }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(SyntaxKind.IncompleteMember, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestMethodAfterFieldRankStart() { var text = "class c { int[ public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.IncompleteMember, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestMethodAfterFieldRankComma() { var text = "class c { int[, public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.IncompleteMember, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestStatementAfterLocalDeclarationStart() { var text = "class c { void m() { int if (x) y(); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterLocalRankStart() { var text = "class c { void m() { int [ if (x) y(); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestStatementAfterLocalRankComma() { var text = "class c { void m() { int [, if (x) y(); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestStatementAfterLocalDeclarationWithMissingSemicolon() { var text = "class c { void m() { int a if (x) y(); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[0].Code); } [Fact] public void TestStatementAfterLocalDeclarationWithCommaAndMissingSemicolon() { var text = "class c { void m() { int a, if (x) y(); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterLocalDeclarationEquals() { var text = "class c { void m() { int a = if (x) y(); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterLocalDeclarationArrayInitializerStart() { var text = "class c { void m() { int a = { if (x) y(); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterLocalDeclarationArrayInitializerExpression() { var text = "class c { void m() { int a = { e if (x) y(); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterLocalDeclarationArrayInitializerExpressionAndComma() { var text = "class c { void m() { int a = { e, if (x) y(); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterLocalDeclarationArrayInitializerStart() { var text = "class c { void m() { int a = { $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterLocalDeclarationArrayInitializerExpression() { var text = "class c { void m() { int a = { e $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBeforeLocalDeclarationArrayInitializerExpression() { var text = "class c { void m() { int a = { $ e }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterLocalDeclarationArrayInitializerExpressionAndComma() { var text = "class c { void m() { int a = { e, $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterLocalDeclarationArrayInitializerExpressions() { var text = "class c { void m() { int a = { e, e $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBetweenLocalDeclarationArrayInitializerExpressions() { var text = "class c { void m() { int a = { e, $ e }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBetweenLocalDeclarationArrayInitializerExpressionsWithMissingComma() { var text = "class c { void m() { int a = { e $ e }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterMethodCallStart() { var text = "class c { void m() { m($); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterMethodArgument() { var text = "class c { void m() { m(a $); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBeforeMethodArgument() { var text = "class c { void m() { m($ a); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBeforeMethodArgumentAndComma() { var text = "class c { void m() { m(a, $); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestSemiColonAfterMethodCallStart() { var text = "class c { void m() { m(; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); } [Fact] public void TestSemiColonAfterMethodCallArgument() { var text = "class c { void m() { m(a; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); } [Fact] public void TestSemiColonAfterMethodCallArgumentAndComma() { var text = "class c { void m() { m(a,; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); } [Fact] public void TestClosingBraceAfterMethodCallArgumentAndCommaWithWhitespace() { var text = "class c { void m() { m(a,\t\t\n\t\t\t} }"; var file = this.ParseTree(text); var md = (file.Members[0] as TypeDeclarationSyntax).Members[0] as MethodDeclarationSyntax; var ie = (md.Body.Statements[0] as ExpressionStatementSyntax).Expression as InvocationExpressionSyntax; // whitespace trivia is part of the following '}', not the invocation expression Assert.Equal("", ie.ArgumentList.CloseParenToken.ToFullString()); Assert.Equal("\t\t\t} ", md.Body.CloseBraceToken.ToFullString()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestStatementAfterMethodCallStart() { var text = "class c { void m() { m( if(e) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterMethodCallArgument() { var text = "class c { void m() { m(a if(e) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterMethodCallArgumentAndComma() { var text = "class c { void m() { m(a, if(e) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestCloseBraceAfterMethodCallStart() { var text = "class c { void m() { m( } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestCloseBraceAfterMethodCallArgument() { var text = "class c { void m() { m(a } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestCloseBraceAfterMethodCallArgumentAndComma() { var text = "class c { void m() { m(a, } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestGarbageAfterIndexerStart() { var text = "class c { void m() { ++a[$]; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterIndexerArgument() { var text = "class c { void m() { ++a[e $]; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBeforeIndexerArgument() { var text = "class c { void m() { ++a[$ e]; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBeforeIndexerArgumentAndComma() { var text = "class c { void m() { ++a[e, $]; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestSemiColonAfterIndexerStart() { var text = "class c { void m() { ++a[; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestSemiColonAfterIndexerArgument() { var text = "class c { void m() { ++a[e; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestSemiColonAfterIndexerArgumentAndComma() { var text = "class c { void m() { ++a[e,; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestStatementAfterIndexerStart() { var text = "class c { void m() { ++a[ if(e) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterIndexerArgument() { var text = "class c { void m() { ++a[e if(e) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterIndexerArgumentAndComma() { var text = "class c { void m() { ++a[e, if(e) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestCloseBraceAfterIndexerStart() { var text = "class c { void m() { ++a[ } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestCloseBraceAfterIndexerArgument() { var text = "class c { void m() { ++a[e } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestCloseBraceAfterIndexerArgumentAndComma() { var text = "class c { void m() { ++a[e, } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestOpenBraceAfterFixedStatementStart() { var text = "class c { void m() { fixed(t v { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.FixedStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); } [Fact] public void TestSemiColonAfterFixedStatementStart() { var text = "class c { void m() { fixed(t v; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.FixedStatement, ms.Body.Statements[0].Kind()); var diags = file.ErrorsAndWarnings(); Assert.Equal(1, diags.Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, diags[0].Code); CreateCompilation(text).VerifyDiagnostics( // (1,31): error CS1026: ) expected // class c { void m() { fixed(t v; } } Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(1, 31), // (1,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // class c { void m() { fixed(t v; } } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "fixed(t v;").WithLocation(1, 22), // (1,28): error CS0246: The type or namespace name 't' could not be found (are you missing a using directive or an assembly reference?) // class c { void m() { fixed(t v; } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "t").WithArguments("t").WithLocation(1, 28), // (1,30): error CS0209: The type of a local declared in a fixed statement must be a pointer type // class c { void m() { fixed(t v; } } Diagnostic(ErrorCode.ERR_BadFixedInitType, "v").WithLocation(1, 30), // (1,30): error CS0210: You must provide an initializer in a fixed or using statement declaration // class c { void m() { fixed(t v; } } Diagnostic(ErrorCode.ERR_FixedMustInit, "v").WithLocation(1, 30), // (1,31): warning CS0642: Possible mistaken empty statement // class c { void m() { fixed(t v; } } Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";").WithLocation(1, 31)); } [Fact] public void TestSemiColonAfterFixedStatementType() { var text = "class c { void m() { fixed(t ) { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.FixedStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); } [Fact] public void TestCatchAfterTryBlockStart() { var text = "class c { void m() { try { catch { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.TryStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestFinallyAfterTryBlockStart() { var text = "class c { void m() { try { finally { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.TryStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestFinallyAfterCatchStart() { var text = "class c { void m() { try { } catch finally { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.TryStatement, ms.Body.Statements[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); } [Fact] public void TestCatchAfterCatchStart() { var text = "class c { void m() { try { } catch catch { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.TryStatement, ms.Body.Statements[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); } [Fact] public void TestFinallyAfterCatchParameterStart() { var text = "class c { void m() { try { } catch (t finally { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.TryStatement, ms.Body.Statements[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); } [Fact] public void TestCatchAfterCatchParameterStart() { var text = "class c { void m() { try { } catch (t catch { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.TryStatement, ms.Body.Statements[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); } [Fact] public void TestCloseBraceAfterCatchStart() { var text = "class c { void m() { try { } catch } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.TryStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[0].Code); } [Fact] public void TestCloseBraceAfterCatchParameterStart() { var text = "class c { void m() { try { } catch(t } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.TryStatement, ms.Body.Statements[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); } [Fact] public void TestSemiColonAfterDoWhileExpressionIndexer() { // this shows that ';' is an exit condition for the expression var text = "class c { void m() { do { } while(e[; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.DoStatement, ms.Body.Statements[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); } [Fact] public void TestCloseParenAfterDoWhileExpressionIndexerStart() { // this shows that ')' is an exit condition for the expression var text = "class c { void m() { do { } while(e[); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.DoStatement, ms.Body.Statements[0].Kind()); file.Errors().Verify( // error CS1003: Syntax error, ']' expected Diagnostic(ErrorCode.ERR_SyntaxError).WithArguments("]", ")").WithLocation(1, 1), // error CS1026: ) expected Diagnostic(ErrorCode.ERR_CloseParenExpected).WithLocation(1, 1) ); } [Fact] public void TestCloseParenAfterForStatementInitializerStart() { // this shows that ';' is an exit condition for the initializer expression var text = "class c { void m() { for (a[;;) { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ForStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestOpenBraceAfterForStatementInitializerStart() { // this shows that '{' is an exit condition for the initializer expression var text = "class c { void m() { for (a[ { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ForStatement, ms.Body.Statements[0].Kind()); Assert.Equal(5, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[3].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[4].Code); } [Fact] public void TestCloseBraceAfterForStatementInitializerStart() { // this shows that '}' is an exit condition for the initializer expression var text = "class c { void m() { for (a[ } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ForStatement, ms.Body.Statements[0].Kind()); Assert.Equal(7, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[3].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[4].Code); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[5].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[6].Code); } [Fact] public void TestCloseParenAfterForStatementConditionStart() { var text = "class c { void m() { for (;a[;) { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ForStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestOpenBraceAfterForStatementConditionStart() { var text = "class c { void m() { for (;a[ { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ForStatement, ms.Body.Statements[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[2].Code); } [Fact] public void TestCloseBraceAfterForStatementConditionStart() { var text = "class c { void m() { for (;a[ } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ForStatement, ms.Body.Statements[0].Kind()); Assert.Equal(5, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[3].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[4].Code); } [Fact] public void TestCloseParenAfterForStatementIncrementerStart() { var text = "class c { void m() { for (;;++a[) { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ForStatement, ms.Body.Statements[0].Kind()); file.Errors().Verify( // error CS1003: Syntax error, ']' expected Diagnostic(ErrorCode.ERR_SyntaxError).WithArguments("]", ")").WithLocation(1, 1), // error CS1026: ) expected Diagnostic(ErrorCode.ERR_CloseParenExpected).WithLocation(1, 1) ); } [Fact] public void TestOpenBraceAfterForStatementIncrementerStart() { var text = "class c { void m() { for (;;++a[ { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ForStatement, ms.Body.Statements[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); } [Fact] public void TestCloseBraceAfterForStatementIncrementerStart() { var text = "class c { void m() { for (;;++a[ } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ForStatement, ms.Body.Statements[0].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[3].Code); } [Fact] public void TestCloseBraceAfterAnonymousTypeStart() { // empty anonymous type is perfectly legal var text = "class c { void m() { var x = new {}; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(0, file.Errors().Length); } [Fact] public void TestSemicolonAfterAnonymousTypeStart() { var text = "class c { void m() { var x = new {; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.Kind()); Assert.NotEqual(default, ds.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestSemicolonAfterAnonymousTypeMemberStart() { var text = "class c { void m() { var x = new {a; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestSemicolonAfterAnonymousTypeMemberEquals() { var text = "class c { void m() { var x = new {a =; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); } [Fact] public void TestSemicolonAfterAnonymousTypeMember() { var text = "class c { void m() { var x = new {a = b; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestSemicolonAfterAnonymousTypeMemberComma() { var text = "class c { void m() { var x = new {a = b, ; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestStatementAfterAnonymousTypeStart() { var text = "class c { void m() { var x = new { while (x) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterAnonymousTypeMemberStart() { var text = "class c { void m() { var x = new { a while (x) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterAnonymousTypeMemberEquals() { var text = "class c { void m() { var x = new { a = while (x) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestStatementAfterAnonymousTypeMember() { var text = "class c { void m() { var x = new { a = b while (x) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterAnonymousTypeMemberComma() { var text = "class c { void m() { var x = new { a = b, while (x) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterAnonymousTypeStart() { var text = "class c { void m() { var x = new { $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBeforeAnonymousTypeMemberStart() { var text = "class c { void m() { var x = new { $ a }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterAnonymousTypeMemberStart() { var text = "class c { void m() { var x = new { a $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterAnonymousTypeMemberEquals() { var text = "class c { void m() { var x = new { a = $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterAnonymousTypeMember() { var text = "class c { void m() { var x = new { a = b $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterAnonymousTypeMemberComma() { var text = "class c { void m() { var x = new { a = b, $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestCloseBraceAfterObjectInitializerStart() { // empty object initializer is perfectly legal var text = "class c { void m() { var x = new C {}; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(0, file.Errors().Length); } [Fact] public void TestSemicolonAfterObjectInitializerStart() { var text = "class c { void m() { var x = new C {; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestSemicolonAfterObjectInitializerMemberStart() { var text = "class c { void m() { var x = new C { a; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestSemicolonAfterObjectInitializerMemberEquals() { var text = "class c { void m() { var x = new C { a =; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); } [Fact] public void TestSemicolonAfterObjectInitializerMember() { var text = "class c { void m() { var x = new C { a = b; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestSemicolonAfterObjectInitializerMemberComma() { var text = "class c { void m() { var x = new C { a = b, ; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterObjectInitializerStart() { var text = "class c { void m() { var x = new C { while (x) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterObjectInitializerMemberStart() { var text = "class c { void m() { var x = new C { a while (x) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterObjectInitializerMemberEquals() { var text = "class c { void m() { var x = new C { a = while (x) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestStatementAfterObjectInitializerMember() { var text = "class c { void m() { var x = new C { a = b while (x) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterObjectInitializerMemberComma() { var text = "class c { void m() { var x = new C { a = b, while (x) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestGarbageAfterObjectInitializerStart() { var text = "class c { void m() { var x = new C { $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBeforeObjectInitializerMemberStart() { var text = "class c { void m() { var x = new C { $ a }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterObjectInitializerMemberStart() { var text = "class c { void m() { var x = new C { a $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterObjectInitializerMemberEquals() { var text = "class c { void m() { var x = new C { a = $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterObjectInitializerMember() { var text = "class c { void m() { var x = new C { a = b $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterObjectInitializerMemberComma() { var text = "class c { void m() { var x = new C { a = b, $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestSemicolonAfterLambdaParameter() { var text = "class c { void m() { var x = (Y y, ; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.TupleExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); file.Errors().Verify( // error CS1525: Invalid expression term ';' Diagnostic(ErrorCode.ERR_InvalidExprTerm).WithArguments(";").WithLocation(1, 1), // error CS1026: ) expected Diagnostic(ErrorCode.ERR_CloseParenExpected).WithLocation(1, 1) ); } [Fact] public void TestSemicolonAfterUntypedLambdaParameter() { var text = "class c { void m() { var x = (y, ; } }"; var file = this.ParseTree(text, options: TestOptions.Regular); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.TupleExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); } [Fact] public void TestSemicolonAfterUntypedLambdaParameterWithCSharp6() { var text = "class c { void m() { var x = (y, ; } }"; var file = this.ParseTree(text, TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.TupleExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(new[] { (int)ErrorCode.ERR_FeatureNotAvailableInVersion6, (int)ErrorCode.ERR_InvalidExprTerm, (int)ErrorCode.ERR_CloseParenExpected }, file.Errors().Select(e => e.Code)); } [Fact] public void TestStatementAfterLambdaParameter() { var text = "class c { void m() { var x = (Y y, while (c) { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.TupleExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); file.Errors().Verify( // error CS1525: Invalid expression term 'while' Diagnostic(ErrorCode.ERR_InvalidExprTerm).WithArguments("while").WithLocation(1, 1), // error CS1026: ) expected Diagnostic(ErrorCode.ERR_CloseParenExpected).WithLocation(1, 1), // error CS1002: ; expected Diagnostic(ErrorCode.ERR_SemicolonExpected).WithLocation(1, 1) ); } [Fact] public void TestStatementAfterUntypedLambdaParameter() { var text = "class c { void m() { var x = (y, while (c) { } } }"; var file = this.ParseTree(text, options: TestOptions.Regular); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.TupleExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestStatementAfterUntypedLambdaParameterWithCSharp6() { var text = "class c { void m() { var x = (y, while (c) { } } }"; var file = this.ParseTree(text, options: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal("var x = (y, ", ds.ToFullString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.TupleExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(new[] { (int)ErrorCode.ERR_FeatureNotAvailableInVersion6, (int)ErrorCode.ERR_InvalidExprTerm, (int)ErrorCode.ERR_CloseParenExpected, (int)ErrorCode.ERR_SemicolonExpected }, file.Errors().Select(e => e.Code)); } [Fact] public void TestPropertyWithNoAccessors() { // this is syntactically valid (even though it will produce a binding error) var text = "class c { int p { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, agg.Members[0].Kind()); var pd = (PropertyDeclarationSyntax)agg.Members[0]; Assert.NotNull(pd.AccessorList); Assert.NotEqual(default, pd.AccessorList.OpenBraceToken); Assert.False(pd.AccessorList.OpenBraceToken.IsMissing); Assert.NotEqual(default, pd.AccessorList.CloseBraceToken); Assert.False(pd.AccessorList.CloseBraceToken.IsMissing); Assert.Equal(0, pd.AccessorList.Accessors.Count); Assert.Equal(0, file.Errors().Length); } [Fact] public void TestMethodAfterPropertyStart() { // this is syntactically valid (even though it will produce a binding error) var text = "class c { int p { int M() {} }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); var pd = (PropertyDeclarationSyntax)agg.Members[0]; Assert.NotNull(pd.AccessorList); Assert.NotEqual(default, pd.AccessorList.OpenBraceToken); Assert.False(pd.AccessorList.OpenBraceToken.IsMissing); Assert.NotEqual(default, pd.AccessorList.CloseBraceToken); Assert.True(pd.AccessorList.CloseBraceToken.IsMissing); Assert.Equal(0, pd.AccessorList.Accessors.Count); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestMethodAfterPropertyGet() { var text = "class c { int p { get int M() {} }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); var pd = (PropertyDeclarationSyntax)agg.Members[0]; Assert.NotNull(pd.AccessorList); Assert.NotEqual(default, pd.AccessorList.OpenBraceToken); Assert.False(pd.AccessorList.OpenBraceToken.IsMissing); Assert.NotEqual(default, pd.AccessorList.CloseBraceToken); Assert.True(pd.AccessorList.CloseBraceToken.IsMissing); Assert.Equal(1, pd.AccessorList.Accessors.Count); var acc = pd.AccessorList.Accessors[0]; Assert.Equal(SyntaxKind.GetAccessorDeclaration, acc.Kind()); Assert.NotEqual(default, acc.Keyword); Assert.False(acc.Keyword.IsMissing); Assert.Equal(SyntaxKind.GetKeyword, acc.Keyword.Kind()); Assert.Null(acc.Body); Assert.NotEqual(default, acc.SemicolonToken); Assert.True(acc.SemicolonToken.IsMissing); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SemiOrLBraceOrArrowExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); } [Fact] public void TestClassAfterPropertyGetBrace() { var text = "class c { int p { get { class d {} }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, agg.Members[1].Kind()); var pd = (PropertyDeclarationSyntax)agg.Members[0]; Assert.NotNull(pd.AccessorList); Assert.NotEqual(default, pd.AccessorList.OpenBraceToken); Assert.False(pd.AccessorList.OpenBraceToken.IsMissing); Assert.NotEqual(default, pd.AccessorList.CloseBraceToken); Assert.True(pd.AccessorList.CloseBraceToken.IsMissing); Assert.Equal(1, pd.AccessorList.Accessors.Count); var acc = pd.AccessorList.Accessors[0]; Assert.Equal(SyntaxKind.GetAccessorDeclaration, acc.Kind()); Assert.NotEqual(default, acc.Keyword); Assert.False(acc.Keyword.IsMissing); Assert.Equal(SyntaxKind.GetKeyword, acc.Keyword.Kind()); Assert.NotNull(acc.Body); Assert.NotEqual(default, acc.Body.OpenBraceToken); Assert.False(acc.Body.OpenBraceToken.IsMissing); Assert.Equal(0, acc.Body.Statements.Count); Assert.NotEqual(default, acc.Body.CloseBraceToken); Assert.True(acc.Body.CloseBraceToken.IsMissing); Assert.Equal(SyntaxKind.None, acc.SemicolonToken.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); } [Fact] public void TestModifiedMemberAfterPropertyGetBrace() { var text = "class c { int p { get { public class d {} }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, agg.Members[1].Kind()); var pd = (PropertyDeclarationSyntax)agg.Members[0]; Assert.NotNull(pd.AccessorList); Assert.NotEqual(default, pd.AccessorList.OpenBraceToken); Assert.False(pd.AccessorList.OpenBraceToken.IsMissing); Assert.NotEqual(default, pd.AccessorList.CloseBraceToken); Assert.True(pd.AccessorList.CloseBraceToken.IsMissing); Assert.Equal(1, pd.AccessorList.Accessors.Count); var acc = pd.AccessorList.Accessors[0]; Assert.Equal(SyntaxKind.GetAccessorDeclaration, acc.Kind()); Assert.NotEqual(default, acc.Keyword); Assert.False(acc.Keyword.IsMissing); Assert.Equal(SyntaxKind.GetKeyword, acc.Keyword.Kind()); Assert.NotNull(acc.Body); Assert.NotEqual(default, acc.Body.OpenBraceToken); Assert.False(acc.Body.OpenBraceToken.IsMissing); Assert.Equal(0, acc.Body.Statements.Count); Assert.NotEqual(default, acc.Body.CloseBraceToken); Assert.True(acc.Body.CloseBraceToken.IsMissing); Assert.Equal(SyntaxKind.None, acc.SemicolonToken.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); } [Fact] public void TestPropertyAccessorMissingOpenBrace() { var text = "class c { int p { get return 0; } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); var classDecl = (TypeDeclarationSyntax)file.Members[0]; var propertyDecl = (PropertyDeclarationSyntax)classDecl.Members[0]; var accessorDecls = propertyDecl.AccessorList.Accessors; Assert.Equal(1, accessorDecls.Count); var getDecl = accessorDecls[0]; Assert.Equal(SyntaxKind.GetKeyword, getDecl.Keyword.Kind()); var getBodyDecl = getDecl.Body; Assert.NotNull(getBodyDecl); Assert.True(getBodyDecl.OpenBraceToken.IsMissing); var getBodyStmts = getBodyDecl.Statements; Assert.Equal(1, getBodyStmts.Count); Assert.Equal(SyntaxKind.ReturnKeyword, getBodyStmts[0].GetFirstToken().Kind()); Assert.False(getBodyStmts[0].ContainsDiagnostics); Assert.Equal(1, file.Errors().Length); Assert.Equal(ErrorCode.ERR_SemiOrLBraceOrArrowExpected, (ErrorCode)file.Errors()[0].Code); } [Fact] public void TestPropertyAccessorsWithoutBodiesOrSemicolons() { var text = "class c { int p { get set } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); var classDecl = (TypeDeclarationSyntax)file.Members[0]; var propertyDecl = (PropertyDeclarationSyntax)classDecl.Members[0]; var accessorDecls = propertyDecl.AccessorList.Accessors; Assert.Equal(2, accessorDecls.Count); var getDecl = accessorDecls[0]; Assert.Equal(SyntaxKind.GetKeyword, getDecl.Keyword.Kind()); Assert.Null(getDecl.Body); Assert.True(getDecl.SemicolonToken.IsMissing); var setDecl = accessorDecls[1]; Assert.Equal(SyntaxKind.SetKeyword, setDecl.Keyword.Kind()); Assert.Null(setDecl.Body); Assert.True(setDecl.SemicolonToken.IsMissing); Assert.Equal(2, file.Errors().Length); Assert.Equal(ErrorCode.ERR_SemiOrLBraceOrArrowExpected, (ErrorCode)file.Errors()[0].Code); Assert.Equal(ErrorCode.ERR_SemiOrLBraceOrArrowExpected, (ErrorCode)file.Errors()[1].Code); } [Fact] public void TestSemicolonAfterOrderingStart() { var text = "class c { void m() { var q = from x in y orderby; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var md = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(md.Body); Assert.NotEqual(default, md.Body.OpenBraceToken); Assert.False(md.Body.OpenBraceToken.IsMissing); Assert.NotEqual(default, md.Body.CloseBraceToken); Assert.False(md.Body.CloseBraceToken.IsMissing); Assert.Equal(1, md.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, md.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)md.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.QueryExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); var qx = (QueryExpressionSyntax)ds.Declaration.Variables[0].Initializer.Value; Assert.Equal(1, qx.Body.Clauses.Count); Assert.Equal(SyntaxKind.FromClause, qx.FromClause.Kind()); Assert.Equal(SyntaxKind.OrderByClause, qx.Body.Clauses[0].Kind()); var oc = (OrderByClauseSyntax)qx.Body.Clauses[0]; Assert.NotEqual(default, oc.OrderByKeyword); Assert.False(oc.OrderByKeyword.IsMissing); Assert.Equal(1, oc.Orderings.Count); Assert.NotNull(oc.Orderings[0].Expression); Assert.Equal(SyntaxKind.IdentifierName, oc.Orderings[0].Expression.Kind()); var nm = (IdentifierNameSyntax)oc.Orderings[0].Expression; Assert.True(nm.IsMissing); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_ExpectedSelectOrGroup, file.Errors()[1].Code); } [Fact] public void TestSemicolonAfterOrderingExpression() { var text = "class c { void m() { var q = from x in y orderby e; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var md = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(md.Body); Assert.NotEqual(default, md.Body.OpenBraceToken); Assert.False(md.Body.OpenBraceToken.IsMissing); Assert.NotEqual(default, md.Body.CloseBraceToken); Assert.False(md.Body.CloseBraceToken.IsMissing); Assert.Equal(1, md.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, md.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)md.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.QueryExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); var qx = (QueryExpressionSyntax)ds.Declaration.Variables[0].Initializer.Value; Assert.Equal(1, qx.Body.Clauses.Count); Assert.Equal(SyntaxKind.FromClause, qx.FromClause.Kind()); Assert.Equal(SyntaxKind.OrderByClause, qx.Body.Clauses[0].Kind()); var oc = (OrderByClauseSyntax)qx.Body.Clauses[0]; Assert.NotEqual(default, oc.OrderByKeyword); Assert.False(oc.OrderByKeyword.IsMissing); Assert.Equal(1, oc.Orderings.Count); Assert.NotNull(oc.Orderings[0].Expression); Assert.Equal(SyntaxKind.IdentifierName, oc.Orderings[0].Expression.Kind()); var nm = (IdentifierNameSyntax)oc.Orderings[0].Expression; Assert.False(nm.IsMissing); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_ExpectedSelectOrGroup, file.Errors()[0].Code); } [Fact] public void TestSemicolonAfterOrderingExpressionAndComma() { var text = "class c { void m() { var q = from x in y orderby e, ; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var md = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(md.Body); Assert.NotEqual(default, md.Body.OpenBraceToken); Assert.False(md.Body.OpenBraceToken.IsMissing); Assert.NotEqual(default, md.Body.CloseBraceToken); Assert.False(md.Body.CloseBraceToken.IsMissing); Assert.Equal(1, md.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, md.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)md.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.QueryExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); var qx = (QueryExpressionSyntax)ds.Declaration.Variables[0].Initializer.Value; Assert.Equal(1, qx.Body.Clauses.Count); Assert.Equal(SyntaxKind.FromClause, qx.FromClause.Kind()); Assert.Equal(SyntaxKind.OrderByClause, qx.Body.Clauses[0].Kind()); var oc = (OrderByClauseSyntax)qx.Body.Clauses[0]; Assert.NotEqual(default, oc.OrderByKeyword); Assert.False(oc.OrderByKeyword.IsMissing); Assert.Equal(2, oc.Orderings.Count); Assert.NotNull(oc.Orderings[0].Expression); Assert.Equal(SyntaxKind.IdentifierName, oc.Orderings[0].Expression.Kind()); var nm = (IdentifierNameSyntax)oc.Orderings[0].Expression; Assert.False(nm.IsMissing); Assert.NotNull(oc.Orderings[1].Expression); Assert.Equal(SyntaxKind.IdentifierName, oc.Orderings[0].Expression.Kind()); nm = (IdentifierNameSyntax)oc.Orderings[1].Expression; Assert.True(nm.IsMissing); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_ExpectedSelectOrGroup, file.Errors()[1].Code); } [Fact] public void TestMemberAfterOrderingStart() { var text = "class c { void m() { var q = from x in y orderby public int Goo; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[1].Kind()); var md = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(md.Body); Assert.NotEqual(default, md.Body.OpenBraceToken); Assert.False(md.Body.OpenBraceToken.IsMissing); Assert.NotEqual(default, md.Body.CloseBraceToken); Assert.True(md.Body.CloseBraceToken.IsMissing); Assert.Equal(1, md.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, md.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)md.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.QueryExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); var qx = (QueryExpressionSyntax)ds.Declaration.Variables[0].Initializer.Value; Assert.Equal(1, qx.Body.Clauses.Count); Assert.Equal(SyntaxKind.FromClause, qx.FromClause.Kind()); Assert.Equal(SyntaxKind.OrderByClause, qx.Body.Clauses[0].Kind()); var oc = (OrderByClauseSyntax)qx.Body.Clauses[0]; Assert.NotEqual(default, oc.OrderByKeyword); Assert.False(oc.OrderByKeyword.IsMissing); Assert.Equal(1, oc.Orderings.Count); Assert.NotNull(oc.Orderings[0].Expression); Assert.Equal(SyntaxKind.IdentifierName, oc.Orderings[0].Expression.Kind()); var nm = (IdentifierNameSyntax)oc.Orderings[0].Expression; Assert.True(nm.IsMissing); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_ExpectedSelectOrGroup, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[3].Code); } [Fact] public void TestMemberAfterOrderingExpression() { var text = "class c { void m() { var q = from x in y orderby e public int Goo; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[1].Kind()); var md = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(md.Body); Assert.NotEqual(default, md.Body.OpenBraceToken); Assert.False(md.Body.OpenBraceToken.IsMissing); Assert.NotEqual(default, md.Body.CloseBraceToken); Assert.True(md.Body.CloseBraceToken.IsMissing); Assert.Equal(1, md.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, md.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)md.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.QueryExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); var qx = (QueryExpressionSyntax)ds.Declaration.Variables[0].Initializer.Value; Assert.Equal(1, qx.Body.Clauses.Count); Assert.Equal(SyntaxKind.FromClause, qx.FromClause.Kind()); Assert.Equal(SyntaxKind.OrderByClause, qx.Body.Clauses[0].Kind()); var oc = (OrderByClauseSyntax)qx.Body.Clauses[0]; Assert.NotEqual(default, oc.OrderByKeyword); Assert.False(oc.OrderByKeyword.IsMissing); Assert.Equal(1, oc.Orderings.Count); Assert.NotNull(oc.Orderings[0].Expression); Assert.Equal(SyntaxKind.IdentifierName, oc.Orderings[0].Expression.Kind()); var nm = (IdentifierNameSyntax)oc.Orderings[0].Expression; Assert.False(nm.IsMissing); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_ExpectedSelectOrGroup, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); } [Fact] public void TestMemberAfterOrderingExpressionAndComma() { var text = "class c { void m() { var q = from x in y orderby e, public int Goo; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[1].Kind()); var md = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(md.Body); Assert.NotEqual(default, md.Body.OpenBraceToken); Assert.False(md.Body.OpenBraceToken.IsMissing); Assert.NotEqual(default, md.Body.CloseBraceToken); Assert.True(md.Body.CloseBraceToken.IsMissing); Assert.Equal(1, md.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, md.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)md.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.QueryExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); var qx = (QueryExpressionSyntax)ds.Declaration.Variables[0].Initializer.Value; Assert.Equal(1, qx.Body.Clauses.Count); Assert.Equal(SyntaxKind.FromClause, qx.FromClause.Kind()); Assert.Equal(SyntaxKind.OrderByClause, qx.Body.Clauses[0].Kind()); var oc = (OrderByClauseSyntax)qx.Body.Clauses[0]; Assert.NotEqual(default, oc.OrderByKeyword); Assert.False(oc.OrderByKeyword.IsMissing); Assert.Equal(2, oc.Orderings.Count); Assert.NotNull(oc.Orderings[0].Expression); Assert.Equal(SyntaxKind.IdentifierName, oc.Orderings[0].Expression.Kind()); var nm = (IdentifierNameSyntax)oc.Orderings[0].Expression; Assert.False(nm.IsMissing); Assert.NotNull(oc.Orderings[1].Expression); Assert.Equal(SyntaxKind.IdentifierName, oc.Orderings[0].Expression.Kind()); nm = (IdentifierNameSyntax)oc.Orderings[1].Expression; Assert.True(nm.IsMissing); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_ExpectedSelectOrGroup, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[3].Code); } [Fact] public void PartialInVariableDecl() { var text = "class C1 { void M1() { int x = 1, partial class y = 2; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var item1 = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal("C1", item1.Identifier.ToString()); Assert.False(item1.OpenBraceToken.IsMissing); Assert.Equal(2, item1.Members.Count); Assert.False(item1.CloseBraceToken.IsMissing); var subitem1 = (MethodDeclarationSyntax)item1.Members[0]; Assert.Equal(SyntaxKind.MethodDeclaration, subitem1.Kind()); Assert.NotNull(subitem1.Body); Assert.False(subitem1.Body.OpenBraceToken.IsMissing); Assert.True(subitem1.Body.CloseBraceToken.IsMissing); Assert.Equal(1, subitem1.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, subitem1.Body.Statements[0].Kind()); var decl = (LocalDeclarationStatementSyntax)subitem1.Body.Statements[0]; Assert.True(decl.SemicolonToken.IsMissing); Assert.Equal(2, decl.Declaration.Variables.Count); Assert.Equal("x", decl.Declaration.Variables[0].Identifier.ToString()); Assert.True(decl.Declaration.Variables[1].Identifier.IsMissing); Assert.Equal(3, subitem1.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, subitem1.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, subitem1.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, subitem1.Errors()[2].Code); var subitem2 = (TypeDeclarationSyntax)item1.Members[1]; Assert.Equal(SyntaxKind.ClassDeclaration, item1.Members[1].Kind()); Assert.Equal("y", subitem2.Identifier.ToString()); Assert.Equal(SyntaxKind.PartialKeyword, subitem2.Modifiers[0].ContextualKind()); Assert.True(subitem2.OpenBraceToken.IsMissing); Assert.True(subitem2.CloseBraceToken.IsMissing); Assert.Equal(3, subitem2.Errors().Length); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, subitem2.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, subitem2.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_InvalidMemberDecl, subitem2.Errors()[2].Code); } [WorkItem(905394, "DevDiv/Personal")] [Fact] public void TestThisKeywordInIncompleteLambdaArgumentList() { var text = @"public class Test { public void Goo() { var x = ((x, this } }"; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.True(file.ContainsDiagnostics); } [WorkItem(906986, "DevDiv/Personal")] [Fact] public void TestIncompleteAttribute() { var text = @" [type: F"; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.True(file.ContainsDiagnostics); } [WorkItem(908952, "DevDiv/Personal")] [Fact] public void TestNegAttributeOnTypeParameter() { var text = @" public class B { void M() { I<[Test] int> I1=new I<[Test] int>(); } } "; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.True(file.ContainsDiagnostics); } [WorkItem(918947, "DevDiv/Personal")] [Fact] public void TestAtKeywordAsLocalOrParameter() { var text = @" class A { public void M() { int @int = 0; if (@int == 1) { @int = 0; } MM(@int); } public void MM(int n) { } } "; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.False(file.ContainsDiagnostics); } [WorkItem(918947, "DevDiv/Personal")] [Fact] public void TestAtKeywordAsTypeNames() { var text = @"namespace @namespace { class C1 { } class @class : C1 { } } "; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.False(file.ContainsDiagnostics); } [WorkItem(919418, "DevDiv/Personal")] [Fact] public void TestNegDefaultAsLambdaParameter() { var text = @"class C { delegate T Func<T>(); delegate T Func<A0, T>(A0 a0); delegate T Func<A0, A1, T>(A0 a0, A1 a1); delegate T Func<A0, A1, A2, A3, T>(A0 a0, A1 a1, A2 a2, A3 a3); static void X() { // Func<int,int> f1 = (int @in) => 1; // ok: @Keyword as parameter name Func<int,int> f2 = (int where, int from) => 1; // ok: contextual keyword as parameter name Func<int,int> f3 = (int default) => 1; // err: Keyword as parameter name } } "; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.True(file.ContainsDiagnostics); } [Fact] public void TestEmptyUsingDirective() { var text = @"using;"; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); var usings = file.Usings; Assert.Equal(1, usings.Count); Assert.True(usings[0].Name.IsMissing); } [Fact] public void TestNumericLiteralInUsingDirective() { var text = @"using 10;"; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); var usings = file.Usings; Assert.Equal(1, usings.Count); Assert.True(usings[0].Name.IsMissing); } [Fact] public void TestNamespaceDeclarationInUsingDirective() { var text = @"using namespace Goo"; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpectedKW, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); var usings = file.Usings; Assert.Equal(1, usings.Count); Assert.True(usings[0].Name.IsMissing); var members = file.Members; Assert.Equal(1, members.Count); var namespaceDeclaration = members[0]; Assert.Equal(SyntaxKind.NamespaceDeclaration, namespaceDeclaration.Kind()); Assert.False(((NamespaceDeclarationSyntax)namespaceDeclaration).Name.IsMissing); } [Fact] public void TestFileScopedNamespaceDeclarationInUsingDirective() { var text = @"using namespace Goo;"; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); file.GetDiagnostics().Verify( // (1,7): error CS1041: Identifier expected; 'namespace' is a keyword // using namespace Goo; Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "namespace").WithArguments("", "namespace").WithLocation(1, 7)); var usings = file.Usings; Assert.Equal(1, usings.Count); Assert.True(usings[0].Name.IsMissing); var members = file.Members; Assert.Equal(1, members.Count); var namespaceDeclaration = members[0]; Assert.Equal(SyntaxKind.FileScopedNamespaceDeclaration, namespaceDeclaration.Kind()); Assert.False(((FileScopedNamespaceDeclarationSyntax)namespaceDeclaration).Name.IsMissing); } [Fact] public void TestContextualKeywordAsFromVariable() { var text = @" class C { int x = from equals in new[] { 1, 2, 3 } select 1; }"; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); } [WorkItem(537210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537210")] [Fact] public void RegressException4UseValueInAccessor() { var text = @"public class MyClass { public int MyProp { set { int value = 0; } // CS0136 } D x; int this[int n] { get { return 0; } set { x = (value) => { value++; }; } // CS0136 } public delegate void D(int n); public event D MyEvent { add { object value = null; } // CS0136 remove { } } }"; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); // Assert.True(file.ContainsDiagnostics); // CS0136 is not parser error } [WorkItem(931315, "DevDiv/Personal")] [Fact] public void RegressException4InvalidOperator() { var text = @"class A { public static int operator &&(A a) // CS1019 { return 0; } } "; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.True(file.ContainsDiagnostics); } [WorkItem(931316, "DevDiv/Personal")] [Fact] public void RegressNoError4NoOperator() { var text = @"class A { public static A operator (A a) // CS1019 { return a; } } "; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.True(file.ContainsDiagnostics); } [WorkItem(537214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537214")] [Fact] public void RegressWarning4UseContextKeyword() { var text = @"class TestClass { int partial { get; set; } static int Main() { TestClass tc = new TestClass(); tc.partial = 0; return 0; } } "; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.False(file.ContainsDiagnostics); } [WorkItem(537150, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537150")] [Fact] public void ParseStartOfAccessor() { var text = @"class Program { int this[string s] { g } } "; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_GetOrSetExpected, file.Errors()[0].Code); } [WorkItem(536050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536050")] [Fact] public void ParseMethodWithConstructorInitializer() { //someone has a typo in the name of their ctor - parse it as a ctor, and accept the initializer var text = @" class C { CTypo() : base() { //body } } "; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.Equal(0, file.Errors().Length); // CONSIDER: Dev10 actually gives 'CS1002: ; expected', because it thinks you were trying to // specify a method without a body. This is a little silly, since we already know the method // isn't abstract. It might be reasonable to say that an open brace was expected though. var classDecl = file.ChildNodesAndTokens()[0]; Assert.Equal(SyntaxKind.ClassDeclaration, classDecl.Kind()); var methodDecl = classDecl.ChildNodesAndTokens()[3]; Assert.Equal(SyntaxKind.ConstructorDeclaration, methodDecl.Kind()); //not MethodDeclaration Assert.False(methodDecl.ContainsDiagnostics); var methodBody = methodDecl.ChildNodesAndTokens()[3]; Assert.Equal(SyntaxKind.Block, methodBody.Kind()); Assert.False(methodBody.ContainsDiagnostics); } [WorkItem(537157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537157")] [Fact] public void MissingInternalNode() { var text = @"[1]"; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); var incompleteMemberDecl = file.ChildNodesAndTokens()[0]; Assert.Equal(SyntaxKind.IncompleteMember, incompleteMemberDecl.Kind()); Assert.False(incompleteMemberDecl.IsMissing); var attributeDecl = incompleteMemberDecl.ChildNodesAndTokens()[0]; Assert.Equal(SyntaxKind.AttributeList, attributeDecl.Kind()); Assert.False(attributeDecl.IsMissing); var openBracketToken = attributeDecl.ChildNodesAndTokens()[0]; Assert.Equal(SyntaxKind.OpenBracketToken, openBracketToken.Kind()); Assert.False(openBracketToken.IsMissing); var attribute = attributeDecl.ChildNodesAndTokens()[1]; Assert.Equal(SyntaxKind.Attribute, attribute.Kind()); Assert.True(attribute.IsMissing); var identifierName = attribute.ChildNodesAndTokens()[0]; Assert.Equal(SyntaxKind.IdentifierName, identifierName.Kind()); Assert.True(identifierName.IsMissing); var identifierToken = identifierName.ChildNodesAndTokens()[0]; Assert.Equal(SyntaxKind.IdentifierToken, identifierToken.Kind()); Assert.True(identifierToken.IsMissing); } [WorkItem(538469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538469")] [Fact] public void FromKeyword() { var text = @" using System.Collections.Generic; using System.Linq; public class QueryExpressionTest { public static int Main() { int[] expr1 = new int[] { 1, 2, 3, }; IEnumerable<int> query01 = from value in expr1 select value; IEnumerable<int> query02 = from yield in expr1 select yield; IEnumerable<int> query03 = from select in expr1 select select; return 0; } }"; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); //expecting item name - found "select" keyword Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[1].Code); //expecting expression - found "select" keyword Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); //we inserted a missing semicolon in a place we didn't expect } [WorkItem(538971, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538971")] [Fact] public void UnclosedGenericInExplicitInterfaceName() { var text = @" interface I<T> { void Goo(); } class C : I<int> { void I<.Goo() { } } "; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); //expecting a type (argument) Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); //expecting close angle bracket } [WorkItem(540788, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540788")] [Fact] public void IncompleteForEachStatement() { var text = @" public class Test { public static void Main(string[] args) { foreach"; var srcTree = this.ParseTree(text); Assert.Equal(text, srcTree.ToFullString()); Assert.Equal("foreach", srcTree.GetLastToken().ToString()); // Get the Foreach Node var foreachNode = srcTree.GetLastToken().Parent; // Verify 3 empty nodes are created by the parser for error recovery. Assert.Equal(3, foreachNode.ChildNodes().ToList().Count); } [WorkItem(542236, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542236")] [Fact] public void InsertOpenBraceBeforeCodes() { var text = @"{ this.I = i; }; }"; SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(text, TestOptions.Regular9); Assert.Equal(text, syntaxTree.GetCompilationUnitRoot().ToFullString()); // The issue (9391) was exhibited while enumerating the diagnostics Assert.True(syntaxTree.GetDiagnostics().Select(d => ((IFormattable)d).ToString(null, EnsureEnglishUICulture.PreferredOrNull)).SequenceEqual(new[] { "(4,1): error CS1022: Type or namespace definition, or end-of-file expected", })); } [WorkItem(542352, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542352")] [Fact] public void IncompleteTopLevelOperator() { var text = @" fg implicit// class C { } "; SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, syntaxTree.GetCompilationUnitRoot().ToFullString()); // 9553: Several of the locations were incorrect and one was negative Assert.True(syntaxTree.GetDiagnostics().Select(d => ((IFormattable)d).ToString(null, EnsureEnglishUICulture.PreferredOrNull)).SequenceEqual(new[] { // Error on the return type, because in C# syntax it goes after the operator and implicit/explicit keywords "(2,1): error CS1553: Declaration is not valid; use '+ operator <dest-type> (...' instead", // Error on "implicit" because there should be an operator keyword "(2,4): error CS1003: Syntax error, 'operator' expected", // Error on "implicit" because there should be an operator symbol "(2,4): error CS1037: Overloadable operator expected", // Missing parameter list and body "(2,12): error CS1003: Syntax error, '(' expected", "(2,12): error CS1026: ) expected", "(2,12): error CS1002: ; expected", })); } [WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] [Fact] public void IncompleteVariableDeclarationAboveDotMemberAccess() { var text = @" class C { void Main() { C Console.WriteLine(); } } "; SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, syntaxTree.GetCompilationUnitRoot().ToFullString()); Assert.True(syntaxTree.GetDiagnostics().Select(d => ((IFormattable)d).ToString(null, EnsureEnglishUICulture.PreferredOrNull)).SequenceEqual(new[] { "(6,10): error CS1001: Identifier expected", "(6,10): error CS1002: ; expected", })); } [WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] [Fact] public void IncompleteVariableDeclarationAbovePointerMemberAccess() { var text = @" class C { void Main() { C Console->WriteLine(); } } "; SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, syntaxTree.GetCompilationUnitRoot().ToFullString()); Assert.True(syntaxTree.GetDiagnostics().Select(d => ((IFormattable)d).ToString(null, EnsureEnglishUICulture.PreferredOrNull)).SequenceEqual(new[] { "(6,10): error CS1001: Identifier expected", "(6,10): error CS1002: ; expected", })); } [WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] [Fact] public void IncompleteVariableDeclarationAboveBinaryExpression() { var text = @" class C { void Main() { C A + B; } } "; SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, syntaxTree.GetCompilationUnitRoot().ToFullString()); Assert.True(syntaxTree.GetDiagnostics().Select(d => ((IFormattable)d).ToString(null, EnsureEnglishUICulture.PreferredOrNull)).SequenceEqual(new[] { "(6,10): error CS1001: Identifier expected", "(6,10): error CS1002: ; expected", })); } [WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] [Fact] public void IncompleteVariableDeclarationAboveMemberAccess_MultiLine() { var text = @" class C { void Main() { C Console.WriteLine(); } } "; SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, syntaxTree.GetCompilationUnitRoot().ToFullString()); Assert.True(syntaxTree.GetDiagnostics().Select(d => ((IFormattable)d).ToString(null, EnsureEnglishUICulture.PreferredOrNull)).SequenceEqual(new[] { "(6,10): error CS1001: Identifier expected", "(6,10): error CS1002: ; expected", })); } [WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] [Fact] public void IncompleteVariableDeclarationBeforeMemberAccessOnSameLine() { var text = @" class C { void Main() { C Console.WriteLine(); } } "; SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, syntaxTree.GetCompilationUnitRoot().ToFullString()); Assert.True(syntaxTree.GetDiagnostics().Select(d => ((IFormattable)d).ToString(null, EnsureEnglishUICulture.PreferredOrNull)).SequenceEqual(new[] { "(6,18): error CS1003: Syntax error, ',' expected", "(6,19): error CS1002: ; expected", })); } [WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] [Fact] public void EqualsIsNotAmbiguous() { var text = @" class C { void Main() { C A = B; } } "; SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, syntaxTree.GetCompilationUnitRoot().ToFullString()); Assert.Empty(syntaxTree.GetDiagnostics()); } [WorkItem(547120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547120")] [Fact] public void ColonColonInExplicitInterfaceMember() { var text = @" _ _::this "; SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, syntaxTree.GetCompilationUnitRoot().ToFullString()); syntaxTree.GetDiagnostics().Verify( // (2,4): error CS1003: Syntax error, '.' expected // _ _::this Diagnostic(ErrorCode.ERR_SyntaxError, "::").WithArguments(".", "::"), // (2,10): error CS1003: Syntax error, '[' expected // _ _::this Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("[", ""), // (2,10): error CS1003: Syntax error, ']' expected // _ _::this Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("]", ""), // (2,10): error CS1514: { expected // _ _::this Diagnostic(ErrorCode.ERR_LbraceExpected, ""), // (2,10): error CS1513: } expected // _ _::this Diagnostic(ErrorCode.ERR_RbraceExpected, "")); CreateCompilation(text).VerifyDiagnostics( // (2,4): error CS1003: Syntax error, '.' expected // _ _::this Diagnostic(ErrorCode.ERR_SyntaxError, "::").WithArguments(".", "::").WithLocation(2, 4), // (2,10): error CS1003: Syntax error, '[' expected // _ _::this Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("[", "").WithLocation(2, 10), // (2,10): error CS1003: Syntax error, ']' expected // _ _::this Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("]", "").WithLocation(2, 10), // (2,10): error CS1514: { expected // _ _::this Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(2, 10), // (2,10): error CS1513: } expected // _ _::this Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(2, 10), // (2,3): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // _ _::this Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(2, 3), // (2,1): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // _ _::this Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(2, 1), // error CS1551: Indexers must have at least one parameter Diagnostic(ErrorCode.ERR_IndexerNeedsParam).WithLocation(1, 1), // (2,3): error CS0538: '_' in explicit interface declaration is not an interface // _ _::this Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "_").WithArguments("_").WithLocation(2, 3), // (2,6): error CS0548: '<invalid-global-code>.this': property or indexer must have at least one accessor // _ _::this Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("<invalid-global-code>.this").WithLocation(2, 6)); } [WorkItem(649806, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649806")] [Fact] public void Repro649806() { var source = "a b:: /**/\r\n"; var tree = SyntaxFactory.ParseSyntaxTree(source); var diags = tree.GetDiagnostics(); diags.ToArray(); Assert.Equal(1, diags.Count(d => d.Code == (int)ErrorCode.ERR_AliasQualAsExpression)); } [WorkItem(674564, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674564")] [Fact] public void Repro674564() { var source = @" class C { int P { set . } } }"; var tree = SyntaxFactory.ParseSyntaxTree(source); var diags = tree.GetDiagnostics(); diags.ToArray(); diags.Verify( // We see this diagnostic because the accessor has no open brace. // (4,17): error CS1043: { or ; expected // int P { set . } } Diagnostic(ErrorCode.ERR_SemiOrLBraceOrArrowExpected, "."), // We see this diagnostic because we're trying to skip bad tokens in the block and // the "expected" token (i.e. the one we report when we see something that's not a // statement) is close brace. // CONSIDER: This diagnostic isn't great. // (4,17): error CS1513: } expected // int P { set . } } Diagnostic(ErrorCode.ERR_RbraceExpected, ".")); } [WorkItem(680733, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/680733")] [Fact] public void Repro680733a() { var source = @" class Test { public async Task<in{> Bar() { return 1; } } "; AssertEqualRoundtrip(source); } [WorkItem(680733, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/680733")] [Fact] public void Repro680733b() { var source = @" using System; class Test { public async Task<[Obsolete]in{> Bar() { return 1; } } "; AssertEqualRoundtrip(source); } [WorkItem(680739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/680739")] [Fact] public void Repro680739() { var source = @"a b<c..<using.d"; AssertEqualRoundtrip(source); } [WorkItem(675600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/675600")] [Fact] public void TestBracesToOperatorDoubleGreaterThan() { AssertEqualRoundtrip( @"/// <see cref=""operator}}""/> class C {}"); AssertEqualRoundtrip( @"/// <see cref=""operator{{""/> class C {}"); AssertEqualRoundtrip( @"/// <see cref=""operator}=""/> class C {}"); AssertEqualRoundtrip( @"/// <see cref=""operator}}=""/> class C {}"); } private void AssertEqualRoundtrip(string source) { var tree = SyntaxFactory.ParseSyntaxTree(source); var toString = tree.GetRoot().ToFullString(); Assert.Equal(source, toString); } [WorkItem(684816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684816")] [Fact] public void GenericPropertyWithMissingIdentifier() { var source = @" class C : I { int I./*missing*/< { "; var tree = SyntaxFactory.ParseSyntaxTree(source); var toString = tree.GetRoot().ToFullString(); Assert.Equal(source, toString); tree.GetDiagnostics().Verify( // (4,22): error CS1001: Identifier expected // int I./*missing*/< { Diagnostic(ErrorCode.ERR_IdentifierExpected, "<"), // (4,22): error CS7002: Unexpected use of a generic name // int I./*missing*/< { Diagnostic(ErrorCode.ERR_UnexpectedGenericName, "<"), // (4,24): error CS1003: Syntax error, '>' expected // int I./*missing*/< { Diagnostic(ErrorCode.ERR_SyntaxError, "{").WithArguments(">", "{"), // (4,25): error CS1513: } expected // int I./*missing*/< { Diagnostic(ErrorCode.ERR_RbraceExpected, ""), // (4,25): error CS1513: } expected // int I./*missing*/< { Diagnostic(ErrorCode.ERR_RbraceExpected, "")); } [WorkItem(684816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684816")] [Fact] public void GenericEventWithMissingIdentifier() { var source = @" class C : I { event D I./*missing*/< { "; var tree = SyntaxFactory.ParseSyntaxTree(source); var toString = tree.GetRoot().ToFullString(); Assert.Equal(source, toString); tree.GetDiagnostics().Verify( // (4,26): error CS1001: Identifier expected // event D I./*missing*/< { Diagnostic(ErrorCode.ERR_IdentifierExpected, "<"), // (4,26): error CS1001: Identifier expected // event D I./*missing*/< { Diagnostic(ErrorCode.ERR_IdentifierExpected, "<"), // (4,28): error CS1003: Syntax error, '>' expected // event D I./*missing*/< { Diagnostic(ErrorCode.ERR_SyntaxError, "{").WithArguments(">", "{"), // (4,26): error CS7002: Unexpected use of a generic name // event D I./*missing*/< { Diagnostic(ErrorCode.ERR_UnexpectedGenericName, "<"), // (4,29): error CS1513: } expected // event D I./*missing*/< { Diagnostic(ErrorCode.ERR_RbraceExpected, ""), // (4,29): error CS1513: } expected // event D I./*missing*/< { Diagnostic(ErrorCode.ERR_RbraceExpected, "")); } [WorkItem(684816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684816")] [Fact] public void ExplicitImplementationEventWithColonColon() { var source = @" class C : I { event D I:: "; var tree = SyntaxFactory.ParseSyntaxTree(source); var toString = tree.GetRoot().ToFullString(); Assert.Equal(source, toString); tree.GetDiagnostics().Verify( // (4,14): error CS0071: An explicit interface implementation of an event must use event accessor syntax // event D I:: Diagnostic(ErrorCode.ERR_ExplicitEventFieldImpl, "::"), // (4,14): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // event D I:: Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::"), // (4,16): error CS1513: } expected // event D I:: Diagnostic(ErrorCode.ERR_RbraceExpected, "")); } [WorkItem(684816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684816")] [Fact] public void EventNamedThis() { var source = @" class C { event System.Action this "; var tree = SyntaxFactory.ParseSyntaxTree(source); var toString = tree.GetRoot().ToFullString(); Assert.Equal(source, toString); tree.GetDiagnostics().Verify( // (4,25): error CS1001: Identifier expected // event System.Action this Diagnostic(ErrorCode.ERR_IdentifierExpected, "this"), // (4,29): error CS1514: { expected // event System.Action this Diagnostic(ErrorCode.ERR_LbraceExpected, ""), // (4,29): error CS1513: } expected // event System.Action this Diagnostic(ErrorCode.ERR_RbraceExpected, ""), // (4,29): error CS1513: } expected // event System.Action this Diagnostic(ErrorCode.ERR_RbraceExpected, "")); } [WorkItem(697022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/697022")] [Fact] public void GenericEnumWithMissingIdentifiers() { var source = @"enum <//aaaa enum "; var tree = SyntaxFactory.ParseSyntaxTree(source); var toString = tree.GetRoot().ToFullString(); Assert.Equal(source, toString); tree.GetDiagnostics().ToArray(); } [WorkItem(703809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/703809")] [Fact] public void ReplaceOmittedArrayRankWithMissingIdentifier() { var source = @"fixed a,b {//aaaa static "; var tree = SyntaxFactory.ParseSyntaxTree(source); var toString = tree.GetRoot().ToFullString(); Assert.Equal(source, toString); tree.GetDiagnostics().ToArray(); } [WorkItem(716245, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716245")] [Fact] public void ManySkippedTokens() { const int numTokens = 500000; // Prohibitively slow without fix. var source = new string(',', numTokens); var tree = SyntaxFactory.ParseSyntaxTree(source); var eofToken = ((CompilationUnitSyntax)tree.GetRoot()).EndOfFileToken; Assert.Equal(numTokens, eofToken.FullWidth); Assert.Equal(numTokens, eofToken.LeadingTrivia.Count); // Confirm that we built a list. } [WorkItem(947819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947819")] [Fact] public void MissingOpenBraceForClass() { var source = @"namespace n { class c } "; var root = SyntaxFactory.ParseSyntaxTree(source).GetRoot(); Assert.Equal(source, root.ToFullString()); // Verify incomplete class decls don't eat tokens of surrounding nodes var classDecl = root.DescendantNodes().OfType<ClassDeclarationSyntax>().Single(); Assert.False(classDecl.Identifier.IsMissing); Assert.True(classDecl.OpenBraceToken.IsMissing); Assert.True(classDecl.CloseBraceToken.IsMissing); var ns = root.DescendantNodes().OfType<NamespaceDeclarationSyntax>().Single(); Assert.False(ns.OpenBraceToken.IsMissing); Assert.False(ns.CloseBraceToken.IsMissing); } [WorkItem(947819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947819")] [Fact] public void MissingOpenBraceForClassFileScopedNamespace() { var source = @"namespace n; class c "; var root = SyntaxFactory.ParseSyntaxTree(source).GetRoot(); Assert.Equal(source, root.ToFullString()); // Verify incomplete class decls don't eat tokens of surrounding nodes var classDecl = root.DescendantNodes().OfType<ClassDeclarationSyntax>().Single(); Assert.False(classDecl.Identifier.IsMissing); Assert.True(classDecl.OpenBraceToken.IsMissing); Assert.True(classDecl.CloseBraceToken.IsMissing); var ns = root.DescendantNodes().OfType<FileScopedNamespaceDeclarationSyntax>().Single(); Assert.False(ns.SemicolonToken.IsMissing); } [WorkItem(947819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947819")] [Fact] public void MissingOpenBraceForStruct() { var source = @"namespace n { struct c : I } "; var root = SyntaxFactory.ParseSyntaxTree(source).GetRoot(); Assert.Equal(source, root.ToFullString()); // Verify incomplete struct decls don't eat tokens of surrounding nodes var structDecl = root.DescendantNodes().OfType<StructDeclarationSyntax>().Single(); Assert.True(structDecl.OpenBraceToken.IsMissing); Assert.True(structDecl.CloseBraceToken.IsMissing); var ns = root.DescendantNodes().OfType<NamespaceDeclarationSyntax>().Single(); Assert.False(ns.OpenBraceToken.IsMissing); Assert.False(ns.CloseBraceToken.IsMissing); } [WorkItem(947819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947819")] [Fact] public void MissingNameForStruct() { var source = @"namespace n { struct : I { } } "; var root = SyntaxFactory.ParseSyntaxTree(source).GetRoot(); Assert.Equal(source, root.ToFullString()); // Verify incomplete struct decls don't eat tokens of surrounding nodes var structDecl = root.DescendantNodes().OfType<StructDeclarationSyntax>().Single(); Assert.True(structDecl.Identifier.IsMissing); Assert.False(structDecl.OpenBraceToken.IsMissing); Assert.False(structDecl.CloseBraceToken.IsMissing); var ns = root.DescendantNodes().OfType<NamespaceDeclarationSyntax>().Single(); Assert.False(ns.OpenBraceToken.IsMissing); Assert.False(ns.CloseBraceToken.IsMissing); } [WorkItem(947819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947819")] [Fact] public void MissingNameForClass() { var source = @"namespace n { class { } } "; var root = SyntaxFactory.ParseSyntaxTree(source).GetRoot(); Assert.Equal(source, root.ToFullString()); // Verify incomplete class decls don't eat tokens of surrounding nodes var classDecl = root.DescendantNodes().OfType<ClassDeclarationSyntax>().Single(); Assert.True(classDecl.Identifier.IsMissing); Assert.False(classDecl.OpenBraceToken.IsMissing); Assert.False(classDecl.CloseBraceToken.IsMissing); var ns = root.DescendantNodes().OfType<NamespaceDeclarationSyntax>().Single(); Assert.False(ns.OpenBraceToken.IsMissing); Assert.False(ns.CloseBraceToken.IsMissing); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ParsingErrorRecoveryTests : CSharpTestBase { private CompilationUnitSyntax ParseTree(string text, CSharpParseOptions options = null) { return SyntaxFactory.ParseCompilationUnit(text, options: options); } [Theory] [InlineData("public")] [InlineData("internal")] [InlineData("protected")] [InlineData("private")] public void AccessibilityModifierErrorRecovery(string accessibility) { var file = ParseTree($@" class C {{ void M() {{ // bad visibility modifier {accessibility} void localFunc() {{}} }} void M2() {{ typing {accessibility} void localFunc() {{}} }} void M3() {{ // Ambiguous between local func with bad modifier and missing closing // brace on previous method. Parsing currently assumes the former, // assuming the tokens are parseable as a local func. {accessibility} void M4() {{}} }}"); Assert.NotNull(file); file.GetDiagnostics().Verify( // (7,9): error CS0106: The modifier '{accessibility}' is not valid for this item // {accessibility} void localFunc() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, accessibility).WithArguments(accessibility).WithLocation(7, 9), // (11,15): error CS1002: ; expected // typing Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(11, 15), // (12,9): error CS0106: The modifier '{accessibility}' is not valid for this item // {accessibility} void localFunc() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, accessibility).WithArguments(accessibility).WithLocation(12, 9), // (19,5): error CS0106: The modifier '{accessibility}' is not valid for this item // {accessibility} void M4() {} Diagnostic(ErrorCode.ERR_BadMemberFlag, accessibility).WithArguments(accessibility).WithLocation(19, 5), // (20,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(20, 2) ); } [Fact] public void TestGlobalAttributeGarbageAfterLocation() { var text = "[assembly: $"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[2].Code); } [Fact] public void TestGlobalAttributeUsingAfterLocation() { var text = "[assembly: using n;"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_UsingAfterElements, file.Errors()[2].Code); } [Fact] public void TestGlobalAttributeExternAfterLocation() { var text = "[assembly: extern alias a;"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_ExternAfterElements, file.Errors()[2].Code); } [Fact] public void TestGlobalAttributeNamespaceAfterLocation() { var text = "[assembly: namespace n { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestGlobalAttributeClassAfterLocation() { var text = "[assembly: class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestGlobalAttributeAttributeAfterLocation() { var text = "[assembly: [assembly: attr]"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestGlobalAttributeEOFAfterLocation() { var text = "[assembly: "; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestGlobalAttributeGarbageAfterAttribute() { var text = "[assembly: a $"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestGlobalAttributeGarbageAfterParameterStart() { var text = "[assembly: a( $"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[2].Code); } [Fact] public void TestGlobalAttributeGarbageAfterParameter() { var text = "[assembly: a(b $"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[2].Code); } [Fact] public void TestGlobalAttributeMissingCommaBetweenParameters() { var text = "[assembly: a(b c)"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestGlobalAttributeWithGarbageBetweenParameters() { var text = "[assembly: a(b $ c)"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[2].Code); } [Fact] public void TestGlobalAttributeWithGarbageBetweenAttributes() { var text = "[assembly: a $ b"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(3, file.Errors().Length); file.Errors().Verify( // error CS1056: Unexpected character '$' Diagnostic(ErrorCode.ERR_UnexpectedCharacter).WithArguments("$"), // error CS1003: Syntax error, ',' expected Diagnostic(ErrorCode.ERR_SyntaxError).WithArguments(",", ""), // error CS1003: Syntax error, ']' expected Diagnostic(ErrorCode.ERR_SyntaxError).WithArguments("]", "") ); } [Fact] public void TestGlobalAttributeWithUsingAfterParameterStart() { var text = "[assembly: a( using n;"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_UsingAfterElements, file.Errors()[2].Code); } [Fact] public void TestGlobalAttributeWithExternAfterParameterStart() { var text = "[assembly: a( extern alias n;"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(0, file.Members.Count); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_ExternAfterElements, file.Errors()[2].Code); } [Fact] public void TestGlobalAttributeWithNamespaceAfterParameterStart() { var text = "[assembly: a( namespace n { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestGlobalAttributeWithClassAfterParameterStart() { var text = "[assembly: a( class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestGarbageBeforeNamespace() { var text = "$ namespace n { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterNamespace() { var text = "namespace n { } $"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void MultipleSubsequentMisplacedCharactersSingleError1() { var text = "namespace n { } ,,,,,,,,"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_EOFExpected, file.Errors()[0].Code); } [Fact] public void MultipleSubsequentMisplacedCharactersSingleError2() { var text = ",,,, namespace n { } ,,,,"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_EOFExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_EOFExpected, file.Errors()[1].Code); } [Fact] public void TestGarbageInsideNamespace() { var text = "namespace n { $ }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestIncompleteGlobalMembers() { var text = @" asas] extern alias A; asas using System; sadasdasd] [assembly: goo] class C { } [a]fod; [b"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); } [Fact] public void TestAttributeWithGarbageAfterStart() { var text = "[ $"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.IncompleteMember, file.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[2].Code); } [Fact] public void TestAttributeWithGarbageAfterName() { var text = "[a $"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.IncompleteMember, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestAttributeWithClassAfterBracket() { var text = "[ class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestAttributeWithClassAfterName() { var text = "[a class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestAttributeWithClassAfterParameterStart() { var text = "[a( class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestAttributeWithClassAfterParameter() { var text = "[a(b class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestAttributeWithClassAfterParameterAndComma() { var text = "[a(b, class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[2].Code); } [Fact] public void TestAttributeWithCommaAfterParameterStart() { var text = "[a(, class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[3].Code); } [Fact] public void TestAttributeWithCommasAfterParameterStart() { var text = "[a(,, class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(5, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[3].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[4].Code); } [Fact] public void TestAttributeWithMissingFirstParameter() { var text = "[a(, b class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[2].Code); } [Fact] public void TestNamespaceWithGarbage() { var text = "namespace n { $ }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestNamespaceWithUnexpectedKeyword() { var text = "namespace n { int }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_NamespaceUnexpected, file.Errors()[0].Code); } [Fact] public void TestNamespaceWithUnexpectedBracing() { var text = "namespace n { { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_EOFExpected, file.Errors()[0].Code); } [Fact] public void TestGlobalNamespaceWithUnexpectedBracingAtEnd() { var text = "namespace n { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_EOFExpected, file.Errors()[0].Code); } [Fact] public void TestGlobalNamespaceWithUnexpectedBracingAtStart() { var text = "} namespace n { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_EOFExpected, file.Errors()[0].Code); } [Fact] public void TestGlobalNamespaceWithOpenBraceBeforeNamespace() { var text = "{ namespace n { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); } [Fact] public void TestPartialNamespace() { var text = "partial namespace n { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); Assert.Equal(0, file.Errors().Length); } [Fact] public void TestClassAfterStartOfBaseTypeList() { var text = "class c : class b { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); } [Fact] public void TestClassAfterBaseType() { var text = "class c : t class b { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); } [Fact] public void TestClassAfterBaseTypeAndComma() { var text = "class c : t, class b { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); } [Fact] public void TestClassAfterBaseTypesWithMissingComma() { var text = "class c : x y class b { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); } [Fact] public void TestGarbageAfterStartOfBaseTypeList() { var text = "class c : $ { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterBaseType() { var text = "class c : t $ { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterBaseTypeAndComma() { var text = "class c : t, $ { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterBaseTypesWithMissingComma() { var text = "class c : x y $ { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestConstraintAfterStartOfBaseTypeList() { var text = "class c<t> : where t : b { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); } [Fact] public void TestConstraintAfterBaseType() { var text = "class c<t> : x where t : b { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(0, file.Errors().Length); } [Fact] public void TestConstraintAfterBaseTypeComma() { var text = "class c<t> : x, where t : b { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); } [Fact] public void TestConstraintAfterBaseTypes() { var text = "class c<t> : x, y where t : b { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(0, file.Errors().Length); } [Fact] public void TestConstraintAfterBaseTypesWithMissingComma() { var text = "class c<t> : x y where t : b { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestOpenBraceAfterStartOfBaseTypeList() { var text = "class c<t> : { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); } [Fact] public void TestOpenBraceAfterBaseType() { var text = "class c<t> : x { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(0, file.Errors().Length); } [Fact] public void TestOpenBraceAfterBaseTypeComma() { var text = "class c<t> : x, { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); } [Fact] public void TestOpenBraceAfterBaseTypes() { var text = "class c<t> : x, y { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(0, file.Errors().Length); } [Fact] public void TestBaseTypesWithMissingComma() { var text = "class c<t> : x y { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestOpenBraceAfterConstraintStart() { var text = "class c<t> where { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[2].Code); } [Fact] public void TestOpenBraceAfterConstraintName() { var text = "class c<t> where t { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[1].Code); } [Fact] public void TestOpenBraceAfterConstraintNameAndColon() { var text = "class c<t> where t : { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); } [Fact] public void TestOpenBraceAfterConstraintNameAndTypeAndComma() { var text = "class c<t> where t : x, { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); } [Fact] public void TestConstraintAfterConstraintStart() { var text = "class c<t> where where t : a { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[2].Code); } [Fact] public void TestConstraintAfterConstraintName() { var text = "class c<t> where t where t : a { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[1].Code); } [Fact] public void TestConstraintAfterConstraintNameAndColon() { var text = "class c<t> where t : where t : a { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); } [Fact] public void TestConstraintAfterConstraintNameColonTypeAndComma() { var text = "class c<t> where t : a, where t : a { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterConstraintStart() { var text = "class c<t> where $ { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[3].Code); } [Fact] public void TestGarbageAfterConstraintName() { var text = "class c<t> where t $ { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[2].Code); } [Fact] public void TestGarbageAfterConstraintNameAndColon() { var text = "class c<t> where t : $ { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterConstraintNameColonAndType() { var text = "class c<t> where t : x $ { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterConstraintNameColonTypeAndComma() { var text = "class c<t> where t : x, $ { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterGenericClassNameStart() { var text = "class c<$> { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterGenericClassNameType() { var text = "class c<t $> { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterGenericClassNameTypeAndComma() { var text = "class c<t, $> { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestOpenBraceAfterGenericClassNameStart() { var text = "class c< { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestOpenBraceAfterGenericClassNameAndType() { var text = "class c<t { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestClassAfterGenericClassNameStart() { var text = "class c< class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[3].Code); } [Fact] public void TestClassAfterGenericClassNameAndType() { var text = "class c<t class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); } [Fact] public void TestClassAfterGenericClassNameTypeAndComma() { var text = "class c<t, class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[3].Code); } [Fact] public void TestBaseTypeAfterGenericClassNameStart() { var text = "class c< : x { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestBaseTypeAfterGenericClassNameAndType() { var text = "class c<t : x { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestBaseTypeAfterGenericClassNameTypeAndComma() { var text = "class c<t, : x { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestConstraintAfterGenericClassNameStart() { var text = "class c< where t : x { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestConstraintAfterGenericClassNameAndType() { var text = "class c<t where t : x { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestConstraintAfterGenericClassNameTypeAndComma() { var text = "class c<t, where t : x { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestFieldAfterFieldStart() { var text = "class c { int int y; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.IncompleteMember, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[1].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidMemberDecl, file.Errors()[0].Code); } [Fact] public void TestFieldAfterFieldTypeAndName() { var text = "class c { int x int y; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[1].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[0].Code); } [Fact] public void TestFieldAfterFieldTypeNameAndComma() { var text = "class c { int x, int y; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterFieldStart() { var text = "class c { int $ int y; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.IncompleteMember, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidMemberDecl, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_InvalidMemberDecl, file.Errors()[2].Code); } [Fact] public void TestGarbageAfterFieldTypeAndName() { var text = "class c { int x $ int y; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterFieldTypeNameAndComma() { var text = "class c { int x, $ int y; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestEndBraceAfterFieldStart() { var text = "class c { int }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.IncompleteMember, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidMemberDecl, file.Errors()[0].Code); } [Fact] public void TestEndBraceAfterFieldName() { var text = "class c { int x }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[0].Code); } [Fact] public void TestEndBraceAfterFieldNameAndComma() { var text = "class c { int x, }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestEndBraceAfterMethodParameterStart() { var text = "class c { int m( }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestEndBraceAfterMethodParameterType() { var text = "class c { int m(x }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestEndBraceAfterMethodParameterName() { var text = "class c { int m(x y}"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestEndBraceAfterMethodParameterTypeNameAndComma() { var text = "class c { int m(x y, }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[3].Code); } [Fact] public void TestEndBraceAfterMethodParameters() { var text = "class c { int m() }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterMethodParameterStart() { var text = "class c { int m( $ ); }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterMethodParameterType() { var text = "class c { int m( x $ ); }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterMethodParameterTypeAndName() { var text = "class c { int m( x y $ ); }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterMethodParameterTypeNameAndComma() { var text = "class c { int m( x y, $ ); }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[2].Code); } [Fact] public void TestMethodAfterMethodParameterStart() { var text = "class c { int m( public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestMethodAfterMethodParameterType() { var text = "class c { int m(x public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestMethodAfterMethodParameterTypeAndName() { var text = "class c { int m(x y public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestMethodAfterMethodParameterTypeNameAndComma() { var text = "class c { int m(x y, public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[3].Code); } [Fact] public void TestMethodAfterMethodParameterList() { var text = "class c { int m(x y) public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[0].Code); } [Fact] public void TestMethodBodyAfterMethodParameterListStart() { var text = "class c { int m( { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); } [Fact] public void TestSemicolonAfterMethodParameterListStart() { var text = "class c { int m( ; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); } [Fact] public void TestConstructorBodyAfterConstructorParameterListStart() { var text = "class c { c( { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.ConstructorDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); } [Fact] public void TestSemicolonAfterDelegateParameterListStart() { var text = "delegate void d( ;"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var agg = (DelegateDeclarationSyntax)file.Members[0]; Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); } [Fact] public void TestEndBraceAfterIndexerParameterStart() { var text = "class c { int this[ }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); CreateCompilation(text).VerifyDiagnostics( // (1,21): error CS1003: Syntax error, ']' expected // class c { int this[ } Diagnostic(ErrorCode.ERR_SyntaxError, "}").WithArguments("]", "}").WithLocation(1, 21), // (1,21): error CS1514: { expected // class c { int this[ } Diagnostic(ErrorCode.ERR_LbraceExpected, "}").WithLocation(1, 21), // (1,22): error CS1513: } expected // class c { int this[ } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 22), // (1,15): error CS0548: 'c.this': property or indexer must have at least one accessor // class c { int this[ } Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("c.this").WithLocation(1, 15), // (1,19): error CS1551: Indexers must have at least one parameter // class c { int this[ } Diagnostic(ErrorCode.ERR_IndexerNeedsParam, "[").WithLocation(1, 19)); } [Fact] public void TestEndBraceAfterIndexerParameterType() { var text = "class c { int this[x }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[3].Code); } [Fact] public void TestEndBraceAfterIndexerParameterName() { var text = "class c { int this[x y }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); } [Fact] public void TestEndBraceAfterIndexerParameterTypeNameAndComma() { var text = "class c { int this[x y, }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(5, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[3].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[4].Code); } [Fact] public void TestEndBraceAfterIndexerParameters() { var text = "class c { int this[x y] }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterIndexerParameterStart() { var text = "class c { int this[ $ ] { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); CreateCompilation(text).VerifyDiagnostics( // (1,21): error CS1056: Unexpected character '$' // class c { int this[ $ ] { } } Diagnostic(ErrorCode.ERR_UnexpectedCharacter, "").WithArguments("$").WithLocation(1, 21), // (1,15): error CS0548: 'c.this': property or indexer must have at least one accessor // class c { int this[ $ ] { } } Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("c.this").WithLocation(1, 15), // (1,23): error CS1551: Indexers must have at least one parameter // class c { int this[ $ ] { } } Diagnostic(ErrorCode.ERR_IndexerNeedsParam, "]").WithLocation(1, 23)); } [Fact] public void TestGarbageAfterIndexerParameterType() { var text = "class c { int this[ x $ ] { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterIndexerParameterTypeAndName() { var text = "class c { int this[ x y $ ] { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterIndexerParameterTypeNameAndComma() { var text = "class c { int this[ x y, $ ] { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[2].Code); } [Fact] public void TestMethodAfterIndexerParameterStart() { var text = "class c { int this[ public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); CreateCompilation(text).VerifyDiagnostics( // (1,21): error CS1003: Syntax error, ']' expected // class c { int this[ public void m() { } } Diagnostic(ErrorCode.ERR_SyntaxError, "public").WithArguments("]", "public").WithLocation(1, 21), // (1,21): error CS1514: { expected // class c { int this[ public void m() { } } Diagnostic(ErrorCode.ERR_LbraceExpected, "public").WithLocation(1, 21), // (1,21): error CS1513: } expected // class c { int this[ public void m() { } } Diagnostic(ErrorCode.ERR_RbraceExpected, "public").WithLocation(1, 21), // (1,15): error CS0548: 'c.this': property or indexer must have at least one accessor // class c { int this[ public void m() { } } Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("c.this").WithLocation(1, 15), // (1,19): error CS1551: Indexers must have at least one parameter // class c { int this[ public void m() { } } Diagnostic(ErrorCode.ERR_IndexerNeedsParam, "[").WithLocation(1, 19)); } [Fact] public void TestMethodAfterIndexerParameterType() { var text = "class c { int this[x public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[3].Code); } [Fact] public void TestMethodAfterIndexerParameterTypeAndName() { var text = "class c { int this[x y public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); } [Fact] public void TestMethodAfterIndexerParameterTypeNameAndComma() { var text = "class c { int this[x y, public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(5, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[3].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[4].Code); } [Fact] public void TestMethodAfterIndexerParameterList() { var text = "class c { int this[x y] public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); } [Fact] public void TestEOFAfterDelegateStart() { var text = "delegate"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(5, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[3].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[4].Code); } [Fact] public void TestEOFAfterDelegateType() { var text = "delegate d"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[3].Code); } [Fact] public void TestEOFAfterDelegateName() { var text = "delegate void d"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestEOFAfterDelegateParameterStart() { var text = "delegate void d("; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestEOFAfterDelegateParameterType() { var text = "delegate void d(t"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestEOFAfterDelegateParameterTypeName() { var text = "delegate void d(t n"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestEOFAfterDelegateParameterList() { var text = "delegate void d(t n)"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[0].Code); } [Fact] public void TestEOFAfterDelegateParameterTypeNameAndComma() { var text = "delegate void d(t n, "; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[3].Code); } [Fact] public void TestClassAfterDelegateStart() { var text = "delegate class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(5, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[3].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[4].Code); } [Fact] public void TestClassAfterDelegateType() { var text = "delegate d class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[3].Code); } [Fact] public void TestClassAfterDelegateName() { var text = "delegate void d class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestClassAfterDelegateParameterStart() { var text = "delegate void d( class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestClassAfterDelegateParameterType() { var text = "delegate void d(t class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestClassAfterDelegateParameterTypeName() { var text = "delegate void d(t n class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestClassAfterDelegateParameterList() { var text = "delegate void d(t n) class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[0].Code); } [Fact] public void TestClassAfterDelegateParameterTypeNameAndComma() { var text = "delegate void d(t n, class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[3].Code); } [Fact] public void TestGarbageAfterDelegateParameterStart() { var text = "delegate void d($);"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterDelegateParameterType() { var text = "delegate void d(t $);"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterDelegateParameterTypeAndName() { var text = "delegate void d(t n $);"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterDelegateParameterTypeNameAndComma() { var text = "delegate void d(t n, $);"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[2].Code); } [Fact] public void TestGarbageAfterEnumStart() { var text = "enum e { $ }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterEnumName() { var text = "enum e { n $ }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBeforeEnumName() { var text = "enum e { $ n }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAferEnumNameAndComma() { var text = "enum e { n, $ }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAferEnumNameCommaAndName() { var text = "enum e { n, n $ }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBetweenEnumNames() { var text = "enum e { n, $ n }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBetweenEnumNamesWithMissingComma() { var text = "enum e { n $ n }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestGarbageAferEnumNameAndEquals() { var text = "enum e { n = $ }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestEOFAfterEnumStart() { var text = "enum e { "; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestEOFAfterEnumName() { var text = "enum e { n "; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestEOFAfterEnumNameAndComma() { var text = "enum e { n, "; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestClassAfterEnumStart() { var text = "enum e { class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestClassAfterEnumName() { var text = "enum e { n class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestClassAfterEnumNameAndComma() { var text = "enum e { n, class c { }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Members.Count); Assert.Equal(SyntaxKind.EnumDeclaration, file.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[1].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterFixedFieldRankStart() { var text = "class c { fixed int x[$]; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_ValueExpected, file.Errors()[1].Code); } [Fact] public void TestGarbageBeforeFixedFieldRankSize() { var text = "class c { fixed int x[$ 10]; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterFixedFieldRankSize() { var text = "class c { fixed int x[10 $]; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal(ErrorCode.ERR_SyntaxError, (ErrorCode)file.Errors()[0].Code); //expected comma Assert.Equal(ErrorCode.ERR_UnexpectedCharacter, (ErrorCode)file.Errors()[1].Code); //didn't expect '$' Assert.Equal(ErrorCode.ERR_ValueExpected, (ErrorCode)file.Errors()[2].Code); //expected value after (missing) comma } [Fact] public void TestGarbageAfterFieldTypeRankStart() { var text = "class c { int[$] x; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterFieldTypeRankComma() { var text = "class c { int[,$] x; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBeforeFieldTypeRankComma() { var text = "class c { int[$,] x; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestEndBraceAfterFieldRankStart() { var text = "class c { int[ }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(SyntaxKind.IncompleteMember, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestEndBraceAfterFieldRankComma() { var text = "class c { int[, }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(SyntaxKind.IncompleteMember, agg.Members[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestMethodAfterFieldRankStart() { var text = "class c { int[ public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.IncompleteMember, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestMethodAfterFieldRankComma() { var text = "class c { int[, public void m() { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.IncompleteMember, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestStatementAfterLocalDeclarationStart() { var text = "class c { void m() { int if (x) y(); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterLocalRankStart() { var text = "class c { void m() { int [ if (x) y(); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestStatementAfterLocalRankComma() { var text = "class c { void m() { int [, if (x) y(); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestStatementAfterLocalDeclarationWithMissingSemicolon() { var text = "class c { void m() { int a if (x) y(); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[0].Code); } [Fact] public void TestStatementAfterLocalDeclarationWithCommaAndMissingSemicolon() { var text = "class c { void m() { int a, if (x) y(); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterLocalDeclarationEquals() { var text = "class c { void m() { int a = if (x) y(); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterLocalDeclarationArrayInitializerStart() { var text = "class c { void m() { int a = { if (x) y(); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterLocalDeclarationArrayInitializerExpression() { var text = "class c { void m() { int a = { e if (x) y(); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterLocalDeclarationArrayInitializerExpressionAndComma() { var text = "class c { void m() { int a = { e, if (x) y(); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterLocalDeclarationArrayInitializerStart() { var text = "class c { void m() { int a = { $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterLocalDeclarationArrayInitializerExpression() { var text = "class c { void m() { int a = { e $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBeforeLocalDeclarationArrayInitializerExpression() { var text = "class c { void m() { int a = { $ e }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterLocalDeclarationArrayInitializerExpressionAndComma() { var text = "class c { void m() { int a = { e, $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterLocalDeclarationArrayInitializerExpressions() { var text = "class c { void m() { int a = { e, e $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBetweenLocalDeclarationArrayInitializerExpressions() { var text = "class c { void m() { int a = { e, $ e }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBetweenLocalDeclarationArrayInitializerExpressionsWithMissingComma() { var text = "class c { void m() { int a = { e $ e }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterMethodCallStart() { var text = "class c { void m() { m($); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterMethodArgument() { var text = "class c { void m() { m(a $); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBeforeMethodArgument() { var text = "class c { void m() { m($ a); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBeforeMethodArgumentAndComma() { var text = "class c { void m() { m(a, $); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestSemiColonAfterMethodCallStart() { var text = "class c { void m() { m(; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); } [Fact] public void TestSemiColonAfterMethodCallArgument() { var text = "class c { void m() { m(a; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); } [Fact] public void TestSemiColonAfterMethodCallArgumentAndComma() { var text = "class c { void m() { m(a,; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); } [Fact] public void TestClosingBraceAfterMethodCallArgumentAndCommaWithWhitespace() { var text = "class c { void m() { m(a,\t\t\n\t\t\t} }"; var file = this.ParseTree(text); var md = (file.Members[0] as TypeDeclarationSyntax).Members[0] as MethodDeclarationSyntax; var ie = (md.Body.Statements[0] as ExpressionStatementSyntax).Expression as InvocationExpressionSyntax; // whitespace trivia is part of the following '}', not the invocation expression Assert.Equal("", ie.ArgumentList.CloseParenToken.ToFullString()); Assert.Equal("\t\t\t} ", md.Body.CloseBraceToken.ToFullString()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestStatementAfterMethodCallStart() { var text = "class c { void m() { m( if(e) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterMethodCallArgument() { var text = "class c { void m() { m(a if(e) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterMethodCallArgumentAndComma() { var text = "class c { void m() { m(a, if(e) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestCloseBraceAfterMethodCallStart() { var text = "class c { void m() { m( } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestCloseBraceAfterMethodCallArgument() { var text = "class c { void m() { m(a } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestCloseBraceAfterMethodCallArgumentAndComma() { var text = "class c { void m() { m(a, } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestGarbageAfterIndexerStart() { var text = "class c { void m() { ++a[$]; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterIndexerArgument() { var text = "class c { void m() { ++a[e $]; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBeforeIndexerArgument() { var text = "class c { void m() { ++a[$ e]; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBeforeIndexerArgumentAndComma() { var text = "class c { void m() { ++a[e, $]; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestSemiColonAfterIndexerStart() { var text = "class c { void m() { ++a[; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestSemiColonAfterIndexerArgument() { var text = "class c { void m() { ++a[e; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestSemiColonAfterIndexerArgumentAndComma() { var text = "class c { void m() { ++a[e,; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); } [Fact] public void TestStatementAfterIndexerStart() { var text = "class c { void m() { ++a[ if(e) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterIndexerArgument() { var text = "class c { void m() { ++a[e if(e) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterIndexerArgumentAndComma() { var text = "class c { void m() { ++a[e, if(e) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.IfStatement, ms.Body.Statements[1].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestCloseBraceAfterIndexerStart() { var text = "class c { void m() { ++a[ } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestCloseBraceAfterIndexerArgument() { var text = "class c { void m() { ++a[e } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestCloseBraceAfterIndexerArgumentAndComma() { var text = "class c { void m() { ++a[e, } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, ms.Body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)ms.Body.Statements[0]; Assert.Equal(SyntaxKind.PreIncrementExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.ElementAccessExpression, ((PrefixUnaryExpressionSyntax)es.Expression).Operand.Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestOpenBraceAfterFixedStatementStart() { var text = "class c { void m() { fixed(t v { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.FixedStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); } [Fact] public void TestSemiColonAfterFixedStatementStart() { var text = "class c { void m() { fixed(t v; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.FixedStatement, ms.Body.Statements[0].Kind()); var diags = file.ErrorsAndWarnings(); Assert.Equal(1, diags.Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, diags[0].Code); CreateCompilation(text).VerifyDiagnostics( // (1,31): error CS1026: ) expected // class c { void m() { fixed(t v; } } Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(1, 31), // (1,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // class c { void m() { fixed(t v; } } Diagnostic(ErrorCode.ERR_UnsafeNeeded, "fixed(t v;").WithLocation(1, 22), // (1,28): error CS0246: The type or namespace name 't' could not be found (are you missing a using directive or an assembly reference?) // class c { void m() { fixed(t v; } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "t").WithArguments("t").WithLocation(1, 28), // (1,30): error CS0209: The type of a local declared in a fixed statement must be a pointer type // class c { void m() { fixed(t v; } } Diagnostic(ErrorCode.ERR_BadFixedInitType, "v").WithLocation(1, 30), // (1,30): error CS0210: You must provide an initializer in a fixed or using statement declaration // class c { void m() { fixed(t v; } } Diagnostic(ErrorCode.ERR_FixedMustInit, "v").WithLocation(1, 30), // (1,31): warning CS0642: Possible mistaken empty statement // class c { void m() { fixed(t v; } } Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";").WithLocation(1, 31)); } [Fact] public void TestSemiColonAfterFixedStatementType() { var text = "class c { void m() { fixed(t ) { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.FixedStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); } [Fact] public void TestCatchAfterTryBlockStart() { var text = "class c { void m() { try { catch { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.TryStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestFinallyAfterTryBlockStart() { var text = "class c { void m() { try { finally { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.TryStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestFinallyAfterCatchStart() { var text = "class c { void m() { try { } catch finally { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.TryStatement, ms.Body.Statements[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); } [Fact] public void TestCatchAfterCatchStart() { var text = "class c { void m() { try { } catch catch { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.TryStatement, ms.Body.Statements[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); } [Fact] public void TestFinallyAfterCatchParameterStart() { var text = "class c { void m() { try { } catch (t finally { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.TryStatement, ms.Body.Statements[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); } [Fact] public void TestCatchAfterCatchParameterStart() { var text = "class c { void m() { try { } catch (t catch { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.TryStatement, ms.Body.Statements[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); } [Fact] public void TestCloseBraceAfterCatchStart() { var text = "class c { void m() { try { } catch } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.TryStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[0].Code); } [Fact] public void TestCloseBraceAfterCatchParameterStart() { var text = "class c { void m() { try { } catch(t } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.TryStatement, ms.Body.Statements[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); } [Fact] public void TestSemiColonAfterDoWhileExpressionIndexer() { // this shows that ';' is an exit condition for the expression var text = "class c { void m() { do { } while(e[; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.DoStatement, ms.Body.Statements[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); } [Fact] public void TestCloseParenAfterDoWhileExpressionIndexerStart() { // this shows that ')' is an exit condition for the expression var text = "class c { void m() { do { } while(e[); } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.DoStatement, ms.Body.Statements[0].Kind()); file.Errors().Verify( // error CS1003: Syntax error, ']' expected Diagnostic(ErrorCode.ERR_SyntaxError).WithArguments("]", ")").WithLocation(1, 1), // error CS1026: ) expected Diagnostic(ErrorCode.ERR_CloseParenExpected).WithLocation(1, 1) ); } [Fact] public void TestCloseParenAfterForStatementInitializerStart() { // this shows that ';' is an exit condition for the initializer expression var text = "class c { void m() { for (a[;;) { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ForStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestOpenBraceAfterForStatementInitializerStart() { // this shows that '{' is an exit condition for the initializer expression var text = "class c { void m() { for (a[ { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ForStatement, ms.Body.Statements[0].Kind()); Assert.Equal(5, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[3].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[4].Code); } [Fact] public void TestCloseBraceAfterForStatementInitializerStart() { // this shows that '}' is an exit condition for the initializer expression var text = "class c { void m() { for (a[ } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ForStatement, ms.Body.Statements[0].Kind()); Assert.Equal(7, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[3].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[4].Code); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[5].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[6].Code); } [Fact] public void TestCloseParenAfterForStatementConditionStart() { var text = "class c { void m() { for (;a[;) { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ForStatement, ms.Body.Statements[0].Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); } [Fact] public void TestOpenBraceAfterForStatementConditionStart() { var text = "class c { void m() { for (;a[ { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ForStatement, ms.Body.Statements[0].Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[2].Code); } [Fact] public void TestCloseBraceAfterForStatementConditionStart() { var text = "class c { void m() { for (;a[ } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ForStatement, ms.Body.Statements[0].Kind()); Assert.Equal(5, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[3].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[4].Code); } [Fact] public void TestCloseParenAfterForStatementIncrementerStart() { var text = "class c { void m() { for (;;++a[) { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ForStatement, ms.Body.Statements[0].Kind()); file.Errors().Verify( // error CS1003: Syntax error, ']' expected Diagnostic(ErrorCode.ERR_SyntaxError).WithArguments("]", ")").WithLocation(1, 1), // error CS1026: ) expected Diagnostic(ErrorCode.ERR_CloseParenExpected).WithLocation(1, 1) ); } [Fact] public void TestOpenBraceAfterForStatementIncrementerStart() { var text = "class c { void m() { for (;;++a[ { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ForStatement, ms.Body.Statements[0].Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); } [Fact] public void TestCloseBraceAfterForStatementIncrementerStart() { var text = "class c { void m() { for (;;++a[ } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.ForStatement, ms.Body.Statements[0].Kind()); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[3].Code); } [Fact] public void TestCloseBraceAfterAnonymousTypeStart() { // empty anonymous type is perfectly legal var text = "class c { void m() { var x = new {}; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(0, file.Errors().Length); } [Fact] public void TestSemicolonAfterAnonymousTypeStart() { var text = "class c { void m() { var x = new {; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.Kind()); Assert.NotEqual(default, ds.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestSemicolonAfterAnonymousTypeMemberStart() { var text = "class c { void m() { var x = new {a; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestSemicolonAfterAnonymousTypeMemberEquals() { var text = "class c { void m() { var x = new {a =; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); } [Fact] public void TestSemicolonAfterAnonymousTypeMember() { var text = "class c { void m() { var x = new {a = b; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestSemicolonAfterAnonymousTypeMemberComma() { var text = "class c { void m() { var x = new {a = b, ; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestStatementAfterAnonymousTypeStart() { var text = "class c { void m() { var x = new { while (x) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterAnonymousTypeMemberStart() { var text = "class c { void m() { var x = new { a while (x) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterAnonymousTypeMemberEquals() { var text = "class c { void m() { var x = new { a = while (x) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestStatementAfterAnonymousTypeMember() { var text = "class c { void m() { var x = new { a = b while (x) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterAnonymousTypeMemberComma() { var text = "class c { void m() { var x = new { a = b, while (x) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterAnonymousTypeStart() { var text = "class c { void m() { var x = new { $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBeforeAnonymousTypeMemberStart() { var text = "class c { void m() { var x = new { $ a }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterAnonymousTypeMemberStart() { var text = "class c { void m() { var x = new { a $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterAnonymousTypeMemberEquals() { var text = "class c { void m() { var x = new { a = $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterAnonymousTypeMember() { var text = "class c { void m() { var x = new { a = b $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterAnonymousTypeMemberComma() { var text = "class c { void m() { var x = new { a = b, $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestCloseBraceAfterObjectInitializerStart() { // empty object initializer is perfectly legal var text = "class c { void m() { var x = new C {}; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(0, file.Errors().Length); } [Fact] public void TestSemicolonAfterObjectInitializerStart() { var text = "class c { void m() { var x = new C {; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestSemicolonAfterObjectInitializerMemberStart() { var text = "class c { void m() { var x = new C { a; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestSemicolonAfterObjectInitializerMemberEquals() { var text = "class c { void m() { var x = new C { a =; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); } [Fact] public void TestSemicolonAfterObjectInitializerMember() { var text = "class c { void m() { var x = new C { a = b; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestSemicolonAfterObjectInitializerMemberComma() { var text = "class c { void m() { var x = new C { a = b, ; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterObjectInitializerStart() { var text = "class c { void m() { var x = new C { while (x) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterObjectInitializerMemberStart() { var text = "class c { void m() { var x = new C { a while (x) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterObjectInitializerMemberEquals() { var text = "class c { void m() { var x = new C { a = while (x) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestStatementAfterObjectInitializerMember() { var text = "class c { void m() { var x = new C { a = b while (x) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); } [Fact] public void TestStatementAfterObjectInitializerMemberComma() { var text = "class c { void m() { var x = new C { a = b, while (x) {} } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestGarbageAfterObjectInitializerStart() { var text = "class c { void m() { var x = new C { $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageBeforeObjectInitializerMemberStart() { var text = "class c { void m() { var x = new C { $ a }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterObjectInitializerMemberStart() { var text = "class c { void m() { var x = new C { a $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterObjectInitializerMemberEquals() { var text = "class c { void m() { var x = new C { a = $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestGarbageAfterObjectInitializerMember() { var text = "class c { void m() { var x = new C { a = b $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[0].Code); } [Fact] public void TestGarbageAfterObjectInitializerMemberComma() { var text = "class c { void m() { var x = new C { a = b, $ }; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ObjectCreationExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_UnexpectedCharacter, file.Errors()[1].Code); } [Fact] public void TestSemicolonAfterLambdaParameter() { var text = "class c { void m() { var x = (Y y, ; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.TupleExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); file.Errors().Verify( // error CS1525: Invalid expression term ';' Diagnostic(ErrorCode.ERR_InvalidExprTerm).WithArguments(";").WithLocation(1, 1), // error CS1026: ) expected Diagnostic(ErrorCode.ERR_CloseParenExpected).WithLocation(1, 1) ); } [Fact] public void TestSemicolonAfterUntypedLambdaParameter() { var text = "class c { void m() { var x = (y, ; } }"; var file = this.ParseTree(text, options: TestOptions.Regular); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.TupleExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); } [Fact] public void TestSemicolonAfterUntypedLambdaParameterWithCSharp6() { var text = "class c { void m() { var x = (y, ; } }"; var file = this.ParseTree(text, TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(1, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.TupleExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(new[] { (int)ErrorCode.ERR_FeatureNotAvailableInVersion6, (int)ErrorCode.ERR_InvalidExprTerm, (int)ErrorCode.ERR_CloseParenExpected }, file.Errors().Select(e => e.Code)); } [Fact] public void TestStatementAfterLambdaParameter() { var text = "class c { void m() { var x = (Y y, while (c) { } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.TupleExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); file.Errors().Verify( // error CS1525: Invalid expression term 'while' Diagnostic(ErrorCode.ERR_InvalidExprTerm).WithArguments("while").WithLocation(1, 1), // error CS1026: ) expected Diagnostic(ErrorCode.ERR_CloseParenExpected).WithLocation(1, 1), // error CS1002: ; expected Diagnostic(ErrorCode.ERR_SemicolonExpected).WithLocation(1, 1) ); } [Fact] public void TestStatementAfterUntypedLambdaParameter() { var text = "class c { void m() { var x = (y, while (c) { } } }"; var file = this.ParseTree(text, options: TestOptions.Regular); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.TupleExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_CloseParenExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); } [Fact] public void TestStatementAfterUntypedLambdaParameterWithCSharp6() { var text = "class c { void m() { var x = (y, while (c) { } } }"; var file = this.ParseTree(text, options: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var ms = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(ms.Body); Assert.Equal(2, ms.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, ms.Body.Statements[0].Kind()); Assert.Equal(SyntaxKind.WhileStatement, ms.Body.Statements[1].Kind()); var ds = (LocalDeclarationStatementSyntax)ms.Body.Statements[0]; Assert.Equal("var x = (y, ", ds.ToFullString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(SyntaxKind.None, ds.Declaration.Variables[0].Initializer.EqualsToken.Kind()); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.TupleExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal(new[] { (int)ErrorCode.ERR_FeatureNotAvailableInVersion6, (int)ErrorCode.ERR_InvalidExprTerm, (int)ErrorCode.ERR_CloseParenExpected, (int)ErrorCode.ERR_SemicolonExpected }, file.Errors().Select(e => e.Code)); } [Fact] public void TestPropertyWithNoAccessors() { // this is syntactically valid (even though it will produce a binding error) var text = "class c { int p { } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, agg.Members[0].Kind()); var pd = (PropertyDeclarationSyntax)agg.Members[0]; Assert.NotNull(pd.AccessorList); Assert.NotEqual(default, pd.AccessorList.OpenBraceToken); Assert.False(pd.AccessorList.OpenBraceToken.IsMissing); Assert.NotEqual(default, pd.AccessorList.CloseBraceToken); Assert.False(pd.AccessorList.CloseBraceToken.IsMissing); Assert.Equal(0, pd.AccessorList.Accessors.Count); Assert.Equal(0, file.Errors().Length); } [Fact] public void TestMethodAfterPropertyStart() { // this is syntactically valid (even though it will produce a binding error) var text = "class c { int p { int M() {} }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); var pd = (PropertyDeclarationSyntax)agg.Members[0]; Assert.NotNull(pd.AccessorList); Assert.NotEqual(default, pd.AccessorList.OpenBraceToken); Assert.False(pd.AccessorList.OpenBraceToken.IsMissing); Assert.NotEqual(default, pd.AccessorList.CloseBraceToken); Assert.True(pd.AccessorList.CloseBraceToken.IsMissing); Assert.Equal(0, pd.AccessorList.Accessors.Count); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); } [Fact] public void TestMethodAfterPropertyGet() { var text = "class c { int p { get int M() {} }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[1].Kind()); var pd = (PropertyDeclarationSyntax)agg.Members[0]; Assert.NotNull(pd.AccessorList); Assert.NotEqual(default, pd.AccessorList.OpenBraceToken); Assert.False(pd.AccessorList.OpenBraceToken.IsMissing); Assert.NotEqual(default, pd.AccessorList.CloseBraceToken); Assert.True(pd.AccessorList.CloseBraceToken.IsMissing); Assert.Equal(1, pd.AccessorList.Accessors.Count); var acc = pd.AccessorList.Accessors[0]; Assert.Equal(SyntaxKind.GetAccessorDeclaration, acc.Kind()); Assert.NotEqual(default, acc.Keyword); Assert.False(acc.Keyword.IsMissing); Assert.Equal(SyntaxKind.GetKeyword, acc.Keyword.Kind()); Assert.Null(acc.Body); Assert.NotEqual(default, acc.SemicolonToken); Assert.True(acc.SemicolonToken.IsMissing); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SemiOrLBraceOrArrowExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); } [Fact] public void TestClassAfterPropertyGetBrace() { var text = "class c { int p { get { class d {} }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, agg.Members[1].Kind()); var pd = (PropertyDeclarationSyntax)agg.Members[0]; Assert.NotNull(pd.AccessorList); Assert.NotEqual(default, pd.AccessorList.OpenBraceToken); Assert.False(pd.AccessorList.OpenBraceToken.IsMissing); Assert.NotEqual(default, pd.AccessorList.CloseBraceToken); Assert.True(pd.AccessorList.CloseBraceToken.IsMissing); Assert.Equal(1, pd.AccessorList.Accessors.Count); var acc = pd.AccessorList.Accessors[0]; Assert.Equal(SyntaxKind.GetAccessorDeclaration, acc.Kind()); Assert.NotEqual(default, acc.Keyword); Assert.False(acc.Keyword.IsMissing); Assert.Equal(SyntaxKind.GetKeyword, acc.Keyword.Kind()); Assert.NotNull(acc.Body); Assert.NotEqual(default, acc.Body.OpenBraceToken); Assert.False(acc.Body.OpenBraceToken.IsMissing); Assert.Equal(0, acc.Body.Statements.Count); Assert.NotEqual(default, acc.Body.CloseBraceToken); Assert.True(acc.Body.CloseBraceToken.IsMissing); Assert.Equal(SyntaxKind.None, acc.SemicolonToken.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); } [Fact] public void TestModifiedMemberAfterPropertyGetBrace() { var text = "class c { int p { get { public class d {} }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.ClassDeclaration, agg.Members[1].Kind()); var pd = (PropertyDeclarationSyntax)agg.Members[0]; Assert.NotNull(pd.AccessorList); Assert.NotEqual(default, pd.AccessorList.OpenBraceToken); Assert.False(pd.AccessorList.OpenBraceToken.IsMissing); Assert.NotEqual(default, pd.AccessorList.CloseBraceToken); Assert.True(pd.AccessorList.CloseBraceToken.IsMissing); Assert.Equal(1, pd.AccessorList.Accessors.Count); var acc = pd.AccessorList.Accessors[0]; Assert.Equal(SyntaxKind.GetAccessorDeclaration, acc.Kind()); Assert.NotEqual(default, acc.Keyword); Assert.False(acc.Keyword.IsMissing); Assert.Equal(SyntaxKind.GetKeyword, acc.Keyword.Kind()); Assert.NotNull(acc.Body); Assert.NotEqual(default, acc.Body.OpenBraceToken); Assert.False(acc.Body.OpenBraceToken.IsMissing); Assert.Equal(0, acc.Body.Statements.Count); Assert.NotEqual(default, acc.Body.CloseBraceToken); Assert.True(acc.Body.CloseBraceToken.IsMissing); Assert.Equal(SyntaxKind.None, acc.SemicolonToken.Kind()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[1].Code); } [Fact] public void TestPropertyAccessorMissingOpenBrace() { var text = "class c { int p { get return 0; } } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); var classDecl = (TypeDeclarationSyntax)file.Members[0]; var propertyDecl = (PropertyDeclarationSyntax)classDecl.Members[0]; var accessorDecls = propertyDecl.AccessorList.Accessors; Assert.Equal(1, accessorDecls.Count); var getDecl = accessorDecls[0]; Assert.Equal(SyntaxKind.GetKeyword, getDecl.Keyword.Kind()); var getBodyDecl = getDecl.Body; Assert.NotNull(getBodyDecl); Assert.True(getBodyDecl.OpenBraceToken.IsMissing); var getBodyStmts = getBodyDecl.Statements; Assert.Equal(1, getBodyStmts.Count); Assert.Equal(SyntaxKind.ReturnKeyword, getBodyStmts[0].GetFirstToken().Kind()); Assert.False(getBodyStmts[0].ContainsDiagnostics); Assert.Equal(1, file.Errors().Length); Assert.Equal(ErrorCode.ERR_SemiOrLBraceOrArrowExpected, (ErrorCode)file.Errors()[0].Code); } [Fact] public void TestPropertyAccessorsWithoutBodiesOrSemicolons() { var text = "class c { int p { get set } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); var classDecl = (TypeDeclarationSyntax)file.Members[0]; var propertyDecl = (PropertyDeclarationSyntax)classDecl.Members[0]; var accessorDecls = propertyDecl.AccessorList.Accessors; Assert.Equal(2, accessorDecls.Count); var getDecl = accessorDecls[0]; Assert.Equal(SyntaxKind.GetKeyword, getDecl.Keyword.Kind()); Assert.Null(getDecl.Body); Assert.True(getDecl.SemicolonToken.IsMissing); var setDecl = accessorDecls[1]; Assert.Equal(SyntaxKind.SetKeyword, setDecl.Keyword.Kind()); Assert.Null(setDecl.Body); Assert.True(setDecl.SemicolonToken.IsMissing); Assert.Equal(2, file.Errors().Length); Assert.Equal(ErrorCode.ERR_SemiOrLBraceOrArrowExpected, (ErrorCode)file.Errors()[0].Code); Assert.Equal(ErrorCode.ERR_SemiOrLBraceOrArrowExpected, (ErrorCode)file.Errors()[1].Code); } [Fact] public void TestSemicolonAfterOrderingStart() { var text = "class c { void m() { var q = from x in y orderby; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var md = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(md.Body); Assert.NotEqual(default, md.Body.OpenBraceToken); Assert.False(md.Body.OpenBraceToken.IsMissing); Assert.NotEqual(default, md.Body.CloseBraceToken); Assert.False(md.Body.CloseBraceToken.IsMissing); Assert.Equal(1, md.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, md.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)md.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.QueryExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); var qx = (QueryExpressionSyntax)ds.Declaration.Variables[0].Initializer.Value; Assert.Equal(1, qx.Body.Clauses.Count); Assert.Equal(SyntaxKind.FromClause, qx.FromClause.Kind()); Assert.Equal(SyntaxKind.OrderByClause, qx.Body.Clauses[0].Kind()); var oc = (OrderByClauseSyntax)qx.Body.Clauses[0]; Assert.NotEqual(default, oc.OrderByKeyword); Assert.False(oc.OrderByKeyword.IsMissing); Assert.Equal(1, oc.Orderings.Count); Assert.NotNull(oc.Orderings[0].Expression); Assert.Equal(SyntaxKind.IdentifierName, oc.Orderings[0].Expression.Kind()); var nm = (IdentifierNameSyntax)oc.Orderings[0].Expression; Assert.True(nm.IsMissing); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_ExpectedSelectOrGroup, file.Errors()[1].Code); } [Fact] public void TestSemicolonAfterOrderingExpression() { var text = "class c { void m() { var q = from x in y orderby e; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var md = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(md.Body); Assert.NotEqual(default, md.Body.OpenBraceToken); Assert.False(md.Body.OpenBraceToken.IsMissing); Assert.NotEqual(default, md.Body.CloseBraceToken); Assert.False(md.Body.CloseBraceToken.IsMissing); Assert.Equal(1, md.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, md.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)md.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.QueryExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); var qx = (QueryExpressionSyntax)ds.Declaration.Variables[0].Initializer.Value; Assert.Equal(1, qx.Body.Clauses.Count); Assert.Equal(SyntaxKind.FromClause, qx.FromClause.Kind()); Assert.Equal(SyntaxKind.OrderByClause, qx.Body.Clauses[0].Kind()); var oc = (OrderByClauseSyntax)qx.Body.Clauses[0]; Assert.NotEqual(default, oc.OrderByKeyword); Assert.False(oc.OrderByKeyword.IsMissing); Assert.Equal(1, oc.Orderings.Count); Assert.NotNull(oc.Orderings[0].Expression); Assert.Equal(SyntaxKind.IdentifierName, oc.Orderings[0].Expression.Kind()); var nm = (IdentifierNameSyntax)oc.Orderings[0].Expression; Assert.False(nm.IsMissing); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_ExpectedSelectOrGroup, file.Errors()[0].Code); } [Fact] public void TestSemicolonAfterOrderingExpressionAndComma() { var text = "class c { void m() { var q = from x in y orderby e, ; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); var md = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(md.Body); Assert.NotEqual(default, md.Body.OpenBraceToken); Assert.False(md.Body.OpenBraceToken.IsMissing); Assert.NotEqual(default, md.Body.CloseBraceToken); Assert.False(md.Body.CloseBraceToken.IsMissing); Assert.Equal(1, md.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, md.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)md.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.QueryExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); var qx = (QueryExpressionSyntax)ds.Declaration.Variables[0].Initializer.Value; Assert.Equal(1, qx.Body.Clauses.Count); Assert.Equal(SyntaxKind.FromClause, qx.FromClause.Kind()); Assert.Equal(SyntaxKind.OrderByClause, qx.Body.Clauses[0].Kind()); var oc = (OrderByClauseSyntax)qx.Body.Clauses[0]; Assert.NotEqual(default, oc.OrderByKeyword); Assert.False(oc.OrderByKeyword.IsMissing); Assert.Equal(2, oc.Orderings.Count); Assert.NotNull(oc.Orderings[0].Expression); Assert.Equal(SyntaxKind.IdentifierName, oc.Orderings[0].Expression.Kind()); var nm = (IdentifierNameSyntax)oc.Orderings[0].Expression; Assert.False(nm.IsMissing); Assert.NotNull(oc.Orderings[1].Expression); Assert.Equal(SyntaxKind.IdentifierName, oc.Orderings[0].Expression.Kind()); nm = (IdentifierNameSyntax)oc.Orderings[1].Expression; Assert.True(nm.IsMissing); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_ExpectedSelectOrGroup, file.Errors()[1].Code); } [Fact] public void TestMemberAfterOrderingStart() { var text = "class c { void m() { var q = from x in y orderby public int Goo; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[1].Kind()); var md = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(md.Body); Assert.NotEqual(default, md.Body.OpenBraceToken); Assert.False(md.Body.OpenBraceToken.IsMissing); Assert.NotEqual(default, md.Body.CloseBraceToken); Assert.True(md.Body.CloseBraceToken.IsMissing); Assert.Equal(1, md.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, md.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)md.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.QueryExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); var qx = (QueryExpressionSyntax)ds.Declaration.Variables[0].Initializer.Value; Assert.Equal(1, qx.Body.Clauses.Count); Assert.Equal(SyntaxKind.FromClause, qx.FromClause.Kind()); Assert.Equal(SyntaxKind.OrderByClause, qx.Body.Clauses[0].Kind()); var oc = (OrderByClauseSyntax)qx.Body.Clauses[0]; Assert.NotEqual(default, oc.OrderByKeyword); Assert.False(oc.OrderByKeyword.IsMissing); Assert.Equal(1, oc.Orderings.Count); Assert.NotNull(oc.Orderings[0].Expression); Assert.Equal(SyntaxKind.IdentifierName, oc.Orderings[0].Expression.Kind()); var nm = (IdentifierNameSyntax)oc.Orderings[0].Expression; Assert.True(nm.IsMissing); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_ExpectedSelectOrGroup, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[3].Code); } [Fact] public void TestMemberAfterOrderingExpression() { var text = "class c { void m() { var q = from x in y orderby e public int Goo; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[1].Kind()); var md = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(md.Body); Assert.NotEqual(default, md.Body.OpenBraceToken); Assert.False(md.Body.OpenBraceToken.IsMissing); Assert.NotEqual(default, md.Body.CloseBraceToken); Assert.True(md.Body.CloseBraceToken.IsMissing); Assert.Equal(1, md.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, md.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)md.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.QueryExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); var qx = (QueryExpressionSyntax)ds.Declaration.Variables[0].Initializer.Value; Assert.Equal(1, qx.Body.Clauses.Count); Assert.Equal(SyntaxKind.FromClause, qx.FromClause.Kind()); Assert.Equal(SyntaxKind.OrderByClause, qx.Body.Clauses[0].Kind()); var oc = (OrderByClauseSyntax)qx.Body.Clauses[0]; Assert.NotEqual(default, oc.OrderByKeyword); Assert.False(oc.OrderByKeyword.IsMissing); Assert.Equal(1, oc.Orderings.Count); Assert.NotNull(oc.Orderings[0].Expression); Assert.Equal(SyntaxKind.IdentifierName, oc.Orderings[0].Expression.Kind()); var nm = (IdentifierNameSyntax)oc.Orderings[0].Expression; Assert.False(nm.IsMissing); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_ExpectedSelectOrGroup, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); } [Fact] public void TestMemberAfterOrderingExpressionAndComma() { var text = "class c { void m() { var q = from x in y orderby e, public int Goo; }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var agg = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, agg.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, agg.Members[0].Kind()); Assert.Equal(SyntaxKind.FieldDeclaration, agg.Members[1].Kind()); var md = (MethodDeclarationSyntax)agg.Members[0]; Assert.NotNull(md.Body); Assert.NotEqual(default, md.Body.OpenBraceToken); Assert.False(md.Body.OpenBraceToken.IsMissing); Assert.NotEqual(default, md.Body.CloseBraceToken); Assert.True(md.Body.CloseBraceToken.IsMissing); Assert.Equal(1, md.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, md.Body.Statements[0].Kind()); var ds = (LocalDeclarationStatementSyntax)md.Body.Statements[0]; Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.QueryExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); var qx = (QueryExpressionSyntax)ds.Declaration.Variables[0].Initializer.Value; Assert.Equal(1, qx.Body.Clauses.Count); Assert.Equal(SyntaxKind.FromClause, qx.FromClause.Kind()); Assert.Equal(SyntaxKind.OrderByClause, qx.Body.Clauses[0].Kind()); var oc = (OrderByClauseSyntax)qx.Body.Clauses[0]; Assert.NotEqual(default, oc.OrderByKeyword); Assert.False(oc.OrderByKeyword.IsMissing); Assert.Equal(2, oc.Orderings.Count); Assert.NotNull(oc.Orderings[0].Expression); Assert.Equal(SyntaxKind.IdentifierName, oc.Orderings[0].Expression.Kind()); var nm = (IdentifierNameSyntax)oc.Orderings[0].Expression; Assert.False(nm.IsMissing); Assert.NotNull(oc.Orderings[1].Expression); Assert.Equal(SyntaxKind.IdentifierName, oc.Orderings[0].Expression.Kind()); nm = (IdentifierNameSyntax)oc.Orderings[1].Expression; Assert.True(nm.IsMissing); Assert.Equal(4, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_ExpectedSelectOrGroup, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[3].Code); } [Fact] public void PartialInVariableDecl() { var text = "class C1 { void M1() { int x = 1, partial class y = 2; } }"; var file = this.ParseTree(text); Assert.NotNull(file); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var item1 = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal("C1", item1.Identifier.ToString()); Assert.False(item1.OpenBraceToken.IsMissing); Assert.Equal(2, item1.Members.Count); Assert.False(item1.CloseBraceToken.IsMissing); var subitem1 = (MethodDeclarationSyntax)item1.Members[0]; Assert.Equal(SyntaxKind.MethodDeclaration, subitem1.Kind()); Assert.NotNull(subitem1.Body); Assert.False(subitem1.Body.OpenBraceToken.IsMissing); Assert.True(subitem1.Body.CloseBraceToken.IsMissing); Assert.Equal(1, subitem1.Body.Statements.Count); Assert.Equal(SyntaxKind.LocalDeclarationStatement, subitem1.Body.Statements[0].Kind()); var decl = (LocalDeclarationStatementSyntax)subitem1.Body.Statements[0]; Assert.True(decl.SemicolonToken.IsMissing); Assert.Equal(2, decl.Declaration.Variables.Count); Assert.Equal("x", decl.Declaration.Variables[0].Identifier.ToString()); Assert.True(decl.Declaration.Variables[1].Identifier.IsMissing); Assert.Equal(3, subitem1.Errors().Length); Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, subitem1.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, subitem1.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, subitem1.Errors()[2].Code); var subitem2 = (TypeDeclarationSyntax)item1.Members[1]; Assert.Equal(SyntaxKind.ClassDeclaration, item1.Members[1].Kind()); Assert.Equal("y", subitem2.Identifier.ToString()); Assert.Equal(SyntaxKind.PartialKeyword, subitem2.Modifiers[0].ContextualKind()); Assert.True(subitem2.OpenBraceToken.IsMissing); Assert.True(subitem2.CloseBraceToken.IsMissing); Assert.Equal(3, subitem2.Errors().Length); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, subitem2.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, subitem2.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_InvalidMemberDecl, subitem2.Errors()[2].Code); } [WorkItem(905394, "DevDiv/Personal")] [Fact] public void TestThisKeywordInIncompleteLambdaArgumentList() { var text = @"public class Test { public void Goo() { var x = ((x, this } }"; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.True(file.ContainsDiagnostics); } [WorkItem(906986, "DevDiv/Personal")] [Fact] public void TestIncompleteAttribute() { var text = @" [type: F"; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.True(file.ContainsDiagnostics); } [WorkItem(908952, "DevDiv/Personal")] [Fact] public void TestNegAttributeOnTypeParameter() { var text = @" public class B { void M() { I<[Test] int> I1=new I<[Test] int>(); } } "; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.True(file.ContainsDiagnostics); } [WorkItem(918947, "DevDiv/Personal")] [Fact] public void TestAtKeywordAsLocalOrParameter() { var text = @" class A { public void M() { int @int = 0; if (@int == 1) { @int = 0; } MM(@int); } public void MM(int n) { } } "; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.False(file.ContainsDiagnostics); } [WorkItem(918947, "DevDiv/Personal")] [Fact] public void TestAtKeywordAsTypeNames() { var text = @"namespace @namespace { class C1 { } class @class : C1 { } } "; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.False(file.ContainsDiagnostics); } [WorkItem(919418, "DevDiv/Personal")] [Fact] public void TestNegDefaultAsLambdaParameter() { var text = @"class C { delegate T Func<T>(); delegate T Func<A0, T>(A0 a0); delegate T Func<A0, A1, T>(A0 a0, A1 a1); delegate T Func<A0, A1, A2, A3, T>(A0 a0, A1 a1, A2 a2, A3 a3); static void X() { // Func<int,int> f1 = (int @in) => 1; // ok: @Keyword as parameter name Func<int,int> f2 = (int where, int from) => 1; // ok: contextual keyword as parameter name Func<int,int> f3 = (int default) => 1; // err: Keyword as parameter name } } "; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.True(file.ContainsDiagnostics); } [Fact] public void TestEmptyUsingDirective() { var text = @"using;"; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); var usings = file.Usings; Assert.Equal(1, usings.Count); Assert.True(usings[0].Name.IsMissing); } [Fact] public void TestNumericLiteralInUsingDirective() { var text = @"using 10;"; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); var usings = file.Usings; Assert.Equal(1, usings.Count); Assert.True(usings[0].Name.IsMissing); } [Fact] public void TestNamespaceDeclarationInUsingDirective() { var text = @"using namespace Goo"; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpectedKW, file.Errors()[0].Code); Assert.Equal((int)ErrorCode.ERR_LbraceExpected, file.Errors()[1].Code); Assert.Equal((int)ErrorCode.ERR_RbraceExpected, file.Errors()[2].Code); var usings = file.Usings; Assert.Equal(1, usings.Count); Assert.True(usings[0].Name.IsMissing); var members = file.Members; Assert.Equal(1, members.Count); var namespaceDeclaration = members[0]; Assert.Equal(SyntaxKind.NamespaceDeclaration, namespaceDeclaration.Kind()); Assert.False(((NamespaceDeclarationSyntax)namespaceDeclaration).Name.IsMissing); } [Fact] public void TestFileScopedNamespaceDeclarationInUsingDirective() { var text = @"using namespace Goo;"; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); file.GetDiagnostics().Verify( // (1,7): error CS1041: Identifier expected; 'namespace' is a keyword // using namespace Goo; Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "namespace").WithArguments("", "namespace").WithLocation(1, 7)); var usings = file.Usings; Assert.Equal(1, usings.Count); Assert.True(usings[0].Name.IsMissing); var members = file.Members; Assert.Equal(1, members.Count); var namespaceDeclaration = members[0]; Assert.Equal(SyntaxKind.FileScopedNamespaceDeclaration, namespaceDeclaration.Kind()); Assert.False(((FileScopedNamespaceDeclarationSyntax)namespaceDeclaration).Name.IsMissing); } [Fact] public void TestContextualKeywordAsFromVariable() { var text = @" class C { int x = from equals in new[] { 1, 2, 3 } select 1; }"; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); } [WorkItem(537210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537210")] [Fact] public void RegressException4UseValueInAccessor() { var text = @"public class MyClass { public int MyProp { set { int value = 0; } // CS0136 } D x; int this[int n] { get { return 0; } set { x = (value) => { value++; }; } // CS0136 } public delegate void D(int n); public event D MyEvent { add { object value = null; } // CS0136 remove { } } }"; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); // Assert.True(file.ContainsDiagnostics); // CS0136 is not parser error } [WorkItem(931315, "DevDiv/Personal")] [Fact] public void RegressException4InvalidOperator() { var text = @"class A { public static int operator &&(A a) // CS1019 { return 0; } } "; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.True(file.ContainsDiagnostics); } [WorkItem(931316, "DevDiv/Personal")] [Fact] public void RegressNoError4NoOperator() { var text = @"class A { public static A operator (A a) // CS1019 { return a; } } "; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.True(file.ContainsDiagnostics); } [WorkItem(537214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537214")] [Fact] public void RegressWarning4UseContextKeyword() { var text = @"class TestClass { int partial { get; set; } static int Main() { TestClass tc = new TestClass(); tc.partial = 0; return 0; } } "; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.False(file.ContainsDiagnostics); } [WorkItem(537150, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537150")] [Fact] public void ParseStartOfAccessor() { var text = @"class Program { int this[string s] { g } } "; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_GetOrSetExpected, file.Errors()[0].Code); } [WorkItem(536050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536050")] [Fact] public void ParseMethodWithConstructorInitializer() { //someone has a typo in the name of their ctor - parse it as a ctor, and accept the initializer var text = @" class C { CTypo() : base() { //body } } "; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.Equal(0, file.Errors().Length); // CONSIDER: Dev10 actually gives 'CS1002: ; expected', because it thinks you were trying to // specify a method without a body. This is a little silly, since we already know the method // isn't abstract. It might be reasonable to say that an open brace was expected though. var classDecl = file.ChildNodesAndTokens()[0]; Assert.Equal(SyntaxKind.ClassDeclaration, classDecl.Kind()); var methodDecl = classDecl.ChildNodesAndTokens()[3]; Assert.Equal(SyntaxKind.ConstructorDeclaration, methodDecl.Kind()); //not MethodDeclaration Assert.False(methodDecl.ContainsDiagnostics); var methodBody = methodDecl.ChildNodesAndTokens()[3]; Assert.Equal(SyntaxKind.Block, methodBody.Kind()); Assert.False(methodBody.ContainsDiagnostics); } [WorkItem(537157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537157")] [Fact] public void MissingInternalNode() { var text = @"[1]"; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); var incompleteMemberDecl = file.ChildNodesAndTokens()[0]; Assert.Equal(SyntaxKind.IncompleteMember, incompleteMemberDecl.Kind()); Assert.False(incompleteMemberDecl.IsMissing); var attributeDecl = incompleteMemberDecl.ChildNodesAndTokens()[0]; Assert.Equal(SyntaxKind.AttributeList, attributeDecl.Kind()); Assert.False(attributeDecl.IsMissing); var openBracketToken = attributeDecl.ChildNodesAndTokens()[0]; Assert.Equal(SyntaxKind.OpenBracketToken, openBracketToken.Kind()); Assert.False(openBracketToken.IsMissing); var attribute = attributeDecl.ChildNodesAndTokens()[1]; Assert.Equal(SyntaxKind.Attribute, attribute.Kind()); Assert.True(attribute.IsMissing); var identifierName = attribute.ChildNodesAndTokens()[0]; Assert.Equal(SyntaxKind.IdentifierName, identifierName.Kind()); Assert.True(identifierName.IsMissing); var identifierToken = identifierName.ChildNodesAndTokens()[0]; Assert.Equal(SyntaxKind.IdentifierToken, identifierToken.Kind()); Assert.True(identifierToken.IsMissing); } [WorkItem(538469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538469")] [Fact] public void FromKeyword() { var text = @" using System.Collections.Generic; using System.Linq; public class QueryExpressionTest { public static int Main() { int[] expr1 = new int[] { 1, 2, 3, }; IEnumerable<int> query01 = from value in expr1 select value; IEnumerable<int> query02 = from yield in expr1 select yield; IEnumerable<int> query03 = from select in expr1 select select; return 0; } }"; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.Equal(3, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_IdentifierExpected, file.Errors()[0].Code); //expecting item name - found "select" keyword Assert.Equal((int)ErrorCode.ERR_InvalidExprTerm, file.Errors()[1].Code); //expecting expression - found "select" keyword Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[2].Code); //we inserted a missing semicolon in a place we didn't expect } [WorkItem(538971, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538971")] [Fact] public void UnclosedGenericInExplicitInterfaceName() { var text = @" interface I<T> { void Goo(); } class C : I<int> { void I<.Goo() { } } "; var file = this.ParseTree(text); Assert.Equal(text, file.ToFullString()); Assert.Equal(2, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_TypeExpected, file.Errors()[0].Code); //expecting a type (argument) Assert.Equal((int)ErrorCode.ERR_SyntaxError, file.Errors()[1].Code); //expecting close angle bracket } [WorkItem(540788, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540788")] [Fact] public void IncompleteForEachStatement() { var text = @" public class Test { public static void Main(string[] args) { foreach"; var srcTree = this.ParseTree(text); Assert.Equal(text, srcTree.ToFullString()); Assert.Equal("foreach", srcTree.GetLastToken().ToString()); // Get the Foreach Node var foreachNode = srcTree.GetLastToken().Parent; // Verify 3 empty nodes are created by the parser for error recovery. Assert.Equal(3, foreachNode.ChildNodes().ToList().Count); } [WorkItem(542236, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542236")] [Fact] public void InsertOpenBraceBeforeCodes() { var text = @"{ this.I = i; }; }"; SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(text, TestOptions.Regular9); Assert.Equal(text, syntaxTree.GetCompilationUnitRoot().ToFullString()); // The issue (9391) was exhibited while enumerating the diagnostics Assert.True(syntaxTree.GetDiagnostics().Select(d => ((IFormattable)d).ToString(null, EnsureEnglishUICulture.PreferredOrNull)).SequenceEqual(new[] { "(4,1): error CS1022: Type or namespace definition, or end-of-file expected", })); } [WorkItem(542352, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542352")] [Fact] public void IncompleteTopLevelOperator() { var text = @" fg implicit// class C { } "; SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, syntaxTree.GetCompilationUnitRoot().ToFullString()); // 9553: Several of the locations were incorrect and one was negative Assert.True(syntaxTree.GetDiagnostics().Select(d => ((IFormattable)d).ToString(null, EnsureEnglishUICulture.PreferredOrNull)).SequenceEqual(new[] { // Error on the return type, because in C# syntax it goes after the operator and implicit/explicit keywords "(2,1): error CS1553: Declaration is not valid; use '+ operator <dest-type> (...' instead", // Error on "implicit" because there should be an operator keyword "(2,4): error CS1003: Syntax error, 'operator' expected", // Error on "implicit" because there should be an operator symbol "(2,4): error CS1037: Overloadable operator expected", // Missing parameter list and body "(2,12): error CS1003: Syntax error, '(' expected", "(2,12): error CS1026: ) expected", "(2,12): error CS1002: ; expected", })); } [WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] [Fact] public void IncompleteVariableDeclarationAboveDotMemberAccess() { var text = @" class C { void Main() { C Console.WriteLine(); } } "; SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, syntaxTree.GetCompilationUnitRoot().ToFullString()); Assert.True(syntaxTree.GetDiagnostics().Select(d => ((IFormattable)d).ToString(null, EnsureEnglishUICulture.PreferredOrNull)).SequenceEqual(new[] { "(6,10): error CS1001: Identifier expected", "(6,10): error CS1002: ; expected", })); } [WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] [Fact] public void IncompleteVariableDeclarationAbovePointerMemberAccess() { var text = @" class C { void Main() { C Console->WriteLine(); } } "; SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, syntaxTree.GetCompilationUnitRoot().ToFullString()); Assert.True(syntaxTree.GetDiagnostics().Select(d => ((IFormattable)d).ToString(null, EnsureEnglishUICulture.PreferredOrNull)).SequenceEqual(new[] { "(6,10): error CS1001: Identifier expected", "(6,10): error CS1002: ; expected", })); } [WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] [Fact] public void IncompleteVariableDeclarationAboveBinaryExpression() { var text = @" class C { void Main() { C A + B; } } "; SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, syntaxTree.GetCompilationUnitRoot().ToFullString()); Assert.True(syntaxTree.GetDiagnostics().Select(d => ((IFormattable)d).ToString(null, EnsureEnglishUICulture.PreferredOrNull)).SequenceEqual(new[] { "(6,10): error CS1001: Identifier expected", "(6,10): error CS1002: ; expected", })); } [WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] [Fact] public void IncompleteVariableDeclarationAboveMemberAccess_MultiLine() { var text = @" class C { void Main() { C Console.WriteLine(); } } "; SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, syntaxTree.GetCompilationUnitRoot().ToFullString()); Assert.True(syntaxTree.GetDiagnostics().Select(d => ((IFormattable)d).ToString(null, EnsureEnglishUICulture.PreferredOrNull)).SequenceEqual(new[] { "(6,10): error CS1001: Identifier expected", "(6,10): error CS1002: ; expected", })); } [WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] [Fact] public void IncompleteVariableDeclarationBeforeMemberAccessOnSameLine() { var text = @" class C { void Main() { C Console.WriteLine(); } } "; SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, syntaxTree.GetCompilationUnitRoot().ToFullString()); Assert.True(syntaxTree.GetDiagnostics().Select(d => ((IFormattable)d).ToString(null, EnsureEnglishUICulture.PreferredOrNull)).SequenceEqual(new[] { "(6,18): error CS1003: Syntax error, ',' expected", "(6,19): error CS1002: ; expected", })); } [WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] [Fact] public void EqualsIsNotAmbiguous() { var text = @" class C { void Main() { C A = B; } } "; SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, syntaxTree.GetCompilationUnitRoot().ToFullString()); Assert.Empty(syntaxTree.GetDiagnostics()); } [WorkItem(547120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547120")] [Fact] public void ColonColonInExplicitInterfaceMember() { var text = @" _ _::this "; SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree(text); Assert.Equal(text, syntaxTree.GetCompilationUnitRoot().ToFullString()); syntaxTree.GetDiagnostics().Verify( // (2,4): error CS1003: Syntax error, '.' expected // _ _::this Diagnostic(ErrorCode.ERR_SyntaxError, "::").WithArguments(".", "::"), // (2,10): error CS1003: Syntax error, '[' expected // _ _::this Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("[", ""), // (2,10): error CS1003: Syntax error, ']' expected // _ _::this Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("]", ""), // (2,10): error CS1514: { expected // _ _::this Diagnostic(ErrorCode.ERR_LbraceExpected, ""), // (2,10): error CS1513: } expected // _ _::this Diagnostic(ErrorCode.ERR_RbraceExpected, "")); CreateCompilation(text).VerifyDiagnostics( // (2,4): error CS1003: Syntax error, '.' expected // _ _::this Diagnostic(ErrorCode.ERR_SyntaxError, "::").WithArguments(".", "::").WithLocation(2, 4), // (2,10): error CS1003: Syntax error, '[' expected // _ _::this Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("[", "").WithLocation(2, 10), // (2,10): error CS1003: Syntax error, ']' expected // _ _::this Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("]", "").WithLocation(2, 10), // (2,10): error CS1514: { expected // _ _::this Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(2, 10), // (2,10): error CS1513: } expected // _ _::this Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(2, 10), // (2,3): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // _ _::this Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(2, 3), // (2,1): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // _ _::this Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(2, 1), // error CS1551: Indexers must have at least one parameter Diagnostic(ErrorCode.ERR_IndexerNeedsParam).WithLocation(1, 1), // (2,3): error CS0538: '_' in explicit interface declaration is not an interface // _ _::this Diagnostic(ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, "_").WithArguments("_").WithLocation(2, 3), // (2,6): error CS0548: '<invalid-global-code>.this': property or indexer must have at least one accessor // _ _::this Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("<invalid-global-code>.this").WithLocation(2, 6)); } [WorkItem(649806, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649806")] [Fact] public void Repro649806() { var source = "a b:: /**/\r\n"; var tree = SyntaxFactory.ParseSyntaxTree(source); var diags = tree.GetDiagnostics(); diags.ToArray(); Assert.Equal(1, diags.Count(d => d.Code == (int)ErrorCode.ERR_AliasQualAsExpression)); } [WorkItem(674564, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674564")] [Fact] public void Repro674564() { var source = @" class C { int P { set . } } }"; var tree = SyntaxFactory.ParseSyntaxTree(source); var diags = tree.GetDiagnostics(); diags.ToArray(); diags.Verify( // We see this diagnostic because the accessor has no open brace. // (4,17): error CS1043: { or ; expected // int P { set . } } Diagnostic(ErrorCode.ERR_SemiOrLBraceOrArrowExpected, "."), // We see this diagnostic because we're trying to skip bad tokens in the block and // the "expected" token (i.e. the one we report when we see something that's not a // statement) is close brace. // CONSIDER: This diagnostic isn't great. // (4,17): error CS1513: } expected // int P { set . } } Diagnostic(ErrorCode.ERR_RbraceExpected, ".")); } [WorkItem(680733, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/680733")] [Fact] public void Repro680733a() { var source = @" class Test { public async Task<in{> Bar() { return 1; } } "; AssertEqualRoundtrip(source); } [WorkItem(680733, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/680733")] [Fact] public void Repro680733b() { var source = @" using System; class Test { public async Task<[Obsolete]in{> Bar() { return 1; } } "; AssertEqualRoundtrip(source); } [WorkItem(680739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/680739")] [Fact] public void Repro680739() { var source = @"a b<c..<using.d"; AssertEqualRoundtrip(source); } [WorkItem(675600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/675600")] [Fact] public void TestBracesToOperatorDoubleGreaterThan() { AssertEqualRoundtrip( @"/// <see cref=""operator}}""/> class C {}"); AssertEqualRoundtrip( @"/// <see cref=""operator{{""/> class C {}"); AssertEqualRoundtrip( @"/// <see cref=""operator}=""/> class C {}"); AssertEqualRoundtrip( @"/// <see cref=""operator}}=""/> class C {}"); } private void AssertEqualRoundtrip(string source) { var tree = SyntaxFactory.ParseSyntaxTree(source); var toString = tree.GetRoot().ToFullString(); Assert.Equal(source, toString); } [WorkItem(684816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684816")] [Fact] public void GenericPropertyWithMissingIdentifier() { var source = @" class C : I { int I./*missing*/< { "; var tree = SyntaxFactory.ParseSyntaxTree(source); var toString = tree.GetRoot().ToFullString(); Assert.Equal(source, toString); tree.GetDiagnostics().Verify( // (4,22): error CS1001: Identifier expected // int I./*missing*/< { Diagnostic(ErrorCode.ERR_IdentifierExpected, "<"), // (4,22): error CS7002: Unexpected use of a generic name // int I./*missing*/< { Diagnostic(ErrorCode.ERR_UnexpectedGenericName, "<"), // (4,24): error CS1003: Syntax error, '>' expected // int I./*missing*/< { Diagnostic(ErrorCode.ERR_SyntaxError, "{").WithArguments(">", "{"), // (4,25): error CS1513: } expected // int I./*missing*/< { Diagnostic(ErrorCode.ERR_RbraceExpected, ""), // (4,25): error CS1513: } expected // int I./*missing*/< { Diagnostic(ErrorCode.ERR_RbraceExpected, "")); } [WorkItem(684816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684816")] [Fact] public void GenericEventWithMissingIdentifier() { var source = @" class C : I { event D I./*missing*/< { "; var tree = SyntaxFactory.ParseSyntaxTree(source); var toString = tree.GetRoot().ToFullString(); Assert.Equal(source, toString); tree.GetDiagnostics().Verify( // (4,26): error CS1001: Identifier expected // event D I./*missing*/< { Diagnostic(ErrorCode.ERR_IdentifierExpected, "<"), // (4,26): error CS1001: Identifier expected // event D I./*missing*/< { Diagnostic(ErrorCode.ERR_IdentifierExpected, "<"), // (4,28): error CS1003: Syntax error, '>' expected // event D I./*missing*/< { Diagnostic(ErrorCode.ERR_SyntaxError, "{").WithArguments(">", "{"), // (4,26): error CS7002: Unexpected use of a generic name // event D I./*missing*/< { Diagnostic(ErrorCode.ERR_UnexpectedGenericName, "<"), // (4,29): error CS1513: } expected // event D I./*missing*/< { Diagnostic(ErrorCode.ERR_RbraceExpected, ""), // (4,29): error CS1513: } expected // event D I./*missing*/< { Diagnostic(ErrorCode.ERR_RbraceExpected, "")); } [WorkItem(684816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684816")] [Fact] public void ExplicitImplementationEventWithColonColon() { var source = @" class C : I { event D I:: "; var tree = SyntaxFactory.ParseSyntaxTree(source); var toString = tree.GetRoot().ToFullString(); Assert.Equal(source, toString); tree.GetDiagnostics().Verify( // (4,14): error CS0071: An explicit interface implementation of an event must use event accessor syntax // event D I:: Diagnostic(ErrorCode.ERR_ExplicitEventFieldImpl, "::"), // (4,14): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // event D I:: Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::"), // (4,16): error CS1513: } expected // event D I:: Diagnostic(ErrorCode.ERR_RbraceExpected, "")); } [WorkItem(684816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684816")] [Fact] public void EventNamedThis() { var source = @" class C { event System.Action this "; var tree = SyntaxFactory.ParseSyntaxTree(source); var toString = tree.GetRoot().ToFullString(); Assert.Equal(source, toString); tree.GetDiagnostics().Verify( // (4,25): error CS1001: Identifier expected // event System.Action this Diagnostic(ErrorCode.ERR_IdentifierExpected, "this"), // (4,29): error CS1514: { expected // event System.Action this Diagnostic(ErrorCode.ERR_LbraceExpected, ""), // (4,29): error CS1513: } expected // event System.Action this Diagnostic(ErrorCode.ERR_RbraceExpected, ""), // (4,29): error CS1513: } expected // event System.Action this Diagnostic(ErrorCode.ERR_RbraceExpected, "")); } [WorkItem(697022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/697022")] [Fact] public void GenericEnumWithMissingIdentifiers() { var source = @"enum <//aaaa enum "; var tree = SyntaxFactory.ParseSyntaxTree(source); var toString = tree.GetRoot().ToFullString(); Assert.Equal(source, toString); tree.GetDiagnostics().ToArray(); } [WorkItem(703809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/703809")] [Fact] public void ReplaceOmittedArrayRankWithMissingIdentifier() { var source = @"fixed a,b {//aaaa static "; var tree = SyntaxFactory.ParseSyntaxTree(source); var toString = tree.GetRoot().ToFullString(); Assert.Equal(source, toString); tree.GetDiagnostics().ToArray(); } [WorkItem(716245, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716245")] [Fact] public void ManySkippedTokens() { const int numTokens = 500000; // Prohibitively slow without fix. var source = new string(',', numTokens); var tree = SyntaxFactory.ParseSyntaxTree(source); var eofToken = ((CompilationUnitSyntax)tree.GetRoot()).EndOfFileToken; Assert.Equal(numTokens, eofToken.FullWidth); Assert.Equal(numTokens, eofToken.LeadingTrivia.Count); // Confirm that we built a list. } [WorkItem(947819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947819")] [Fact] public void MissingOpenBraceForClass() { var source = @"namespace n { class c } "; var root = SyntaxFactory.ParseSyntaxTree(source).GetRoot(); Assert.Equal(source, root.ToFullString()); // Verify incomplete class decls don't eat tokens of surrounding nodes var classDecl = root.DescendantNodes().OfType<ClassDeclarationSyntax>().Single(); Assert.False(classDecl.Identifier.IsMissing); Assert.True(classDecl.OpenBraceToken.IsMissing); Assert.True(classDecl.CloseBraceToken.IsMissing); var ns = root.DescendantNodes().OfType<NamespaceDeclarationSyntax>().Single(); Assert.False(ns.OpenBraceToken.IsMissing); Assert.False(ns.CloseBraceToken.IsMissing); } [WorkItem(947819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947819")] [Fact] public void MissingOpenBraceForClassFileScopedNamespace() { var source = @"namespace n; class c "; var root = SyntaxFactory.ParseSyntaxTree(source).GetRoot(); Assert.Equal(source, root.ToFullString()); // Verify incomplete class decls don't eat tokens of surrounding nodes var classDecl = root.DescendantNodes().OfType<ClassDeclarationSyntax>().Single(); Assert.False(classDecl.Identifier.IsMissing); Assert.True(classDecl.OpenBraceToken.IsMissing); Assert.True(classDecl.CloseBraceToken.IsMissing); var ns = root.DescendantNodes().OfType<FileScopedNamespaceDeclarationSyntax>().Single(); Assert.False(ns.SemicolonToken.IsMissing); } [WorkItem(947819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947819")] [Fact] public void MissingOpenBraceForStruct() { var source = @"namespace n { struct c : I } "; var root = SyntaxFactory.ParseSyntaxTree(source).GetRoot(); Assert.Equal(source, root.ToFullString()); // Verify incomplete struct decls don't eat tokens of surrounding nodes var structDecl = root.DescendantNodes().OfType<StructDeclarationSyntax>().Single(); Assert.True(structDecl.OpenBraceToken.IsMissing); Assert.True(structDecl.CloseBraceToken.IsMissing); var ns = root.DescendantNodes().OfType<NamespaceDeclarationSyntax>().Single(); Assert.False(ns.OpenBraceToken.IsMissing); Assert.False(ns.CloseBraceToken.IsMissing); } [WorkItem(947819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947819")] [Fact] public void MissingNameForStruct() { var source = @"namespace n { struct : I { } } "; var root = SyntaxFactory.ParseSyntaxTree(source).GetRoot(); Assert.Equal(source, root.ToFullString()); // Verify incomplete struct decls don't eat tokens of surrounding nodes var structDecl = root.DescendantNodes().OfType<StructDeclarationSyntax>().Single(); Assert.True(structDecl.Identifier.IsMissing); Assert.False(structDecl.OpenBraceToken.IsMissing); Assert.False(structDecl.CloseBraceToken.IsMissing); var ns = root.DescendantNodes().OfType<NamespaceDeclarationSyntax>().Single(); Assert.False(ns.OpenBraceToken.IsMissing); Assert.False(ns.CloseBraceToken.IsMissing); } [WorkItem(947819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947819")] [Fact] public void MissingNameForClass() { var source = @"namespace n { class { } } "; var root = SyntaxFactory.ParseSyntaxTree(source).GetRoot(); Assert.Equal(source, root.ToFullString()); // Verify incomplete class decls don't eat tokens of surrounding nodes var classDecl = root.DescendantNodes().OfType<ClassDeclarationSyntax>().Single(); Assert.True(classDecl.Identifier.IsMissing); Assert.False(classDecl.OpenBraceToken.IsMissing); Assert.False(classDecl.CloseBraceToken.IsMissing); var ns = root.DescendantNodes().OfType<NamespaceDeclarationSyntax>().Single(); Assert.False(ns.OpenBraceToken.IsMissing); Assert.False(ns.CloseBraceToken.IsMissing); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/Core/CodeAnalysisTest/Collections/ImmutableDictionaryTestBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections.Immutable/tests/ImmutableDictionaryTestBase.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public abstract partial class ImmutableDictionaryTestBase : ImmutablesTestBase { [Fact] public virtual void EmptyTest() { this.EmptyTestHelper(Empty<int, bool>(), 5); } [Fact] public void ContainsTest() { ContainsTestHelper(Empty<int, string>(), 5, "foo"); } [Fact] public void RemoveTest() { RemoveTestHelper(Empty<int, GenericParameterHelper?>(), 5); } [Fact] public void SetItemTest() { var map = this.Empty<string, int>() .SetItem("Microsoft", 100) .SetItem("Corporation", 50); Assert.Equal(2, map.Count); map = map.SetItem("Microsoft", 200); Assert.Equal(2, map.Count); Assert.Equal(200, map["Microsoft"]); // Set it to the same thing again and make sure it's all good. var sameMap = map.SetItem("Microsoft", 200); Assert.True(IsSame(map, sameMap)); } [Fact] public void SetItemsTest() { var template = new Dictionary<string, int> { { "Microsoft", 100 }, { "Corporation", 50 }, }; var map = this.Empty<string, int>().SetItems(template); Assert.Equal(2, map.Count); var changes = new Dictionary<string, int> { { "Microsoft", 150 }, { "Dogs", 90 }, }; map = map.SetItems(changes); Assert.Equal(3, map.Count); Assert.Equal(150, map["Microsoft"]); Assert.Equal(50, map["Corporation"]); Assert.Equal(90, map["Dogs"]); map = map.SetItems( new[] { new KeyValuePair<string, int>("Microsoft", 80), new KeyValuePair<string, int>("Microsoft", 70), }); Assert.Equal(3, map.Count); Assert.Equal(70, map["Microsoft"]); Assert.Equal(50, map["Corporation"]); Assert.Equal(90, map["Dogs"]); map = this.Empty<string, int>().SetItems(new[] { // use an array for code coverage new KeyValuePair<string, int>("a", 1), new KeyValuePair<string, int>("b", 2), new KeyValuePair<string, int>("a", 3), }); Assert.Equal(2, map.Count); Assert.Equal(3, map["a"]); Assert.Equal(2, map["b"]); } [Fact] public void ContainsKeyTest() { ContainsKeyTestHelper(Empty<int, GenericParameterHelper>(), 1, new GenericParameterHelper()); } [Fact] public void IndexGetNonExistingKeyThrowsTest() { Assert.Throws<KeyNotFoundException>(() => this.Empty<int, int>()[3]); } [Fact] public void IndexGetTest() { var map = this.Empty<int, int>().Add(3, 5); Assert.Equal(5, map[3]); } /// <summary> /// Verifies that the GetHashCode method returns the standard one. /// </summary> [Fact] public void GetHashCodeTest() { var dictionary = Empty<string, int>(); Assert.Equal(EqualityComparer<object>.Default.GetHashCode(dictionary), dictionary.GetHashCode()); } [Fact] public void ICollectionOfKVMembers() { var dictionary = (ICollection<KeyValuePair<string, int>>)Empty<string, int>(); Assert.Throws<NotSupportedException>(() => dictionary.Add(new KeyValuePair<string, int>())); Assert.Throws<NotSupportedException>(() => dictionary.Remove(new KeyValuePair<string, int>())); Assert.Throws<NotSupportedException>(() => dictionary.Clear()); Assert.True(dictionary.IsReadOnly); } [Fact] public void ICollectionMembers() { ((ICollection)Empty<string, int>()).CopyTo(Array.Empty<object>(), 0); var dictionary = (ICollection)Empty<string, int>().Add("a", 1); Assert.True(dictionary.IsSynchronized); Assert.NotNull(dictionary.SyncRoot); Assert.Same(dictionary.SyncRoot, dictionary.SyncRoot); var array = new DictionaryEntry[2]; dictionary.CopyTo(array, 1); Assert.Null(array[0].Value); Assert.Equal(new DictionaryEntry("a", 1), (DictionaryEntry)array[1]); } [Fact] public void IDictionaryOfKVMembers() { var dictionary = (IDictionary<string, int>)Empty<string, int>().Add("c", 3); Assert.Throws<NotSupportedException>(() => dictionary.Add("a", 1)); Assert.Throws<NotSupportedException>(() => dictionary.Remove("a")); Assert.Throws<NotSupportedException>(() => dictionary["a"] = 2); Assert.Throws<KeyNotFoundException>(() => dictionary["a"]); Assert.Equal(3, dictionary["c"]); } [Fact] public void IDictionaryMembers() { var dictionary = (IDictionary)Empty<string, int>().Add("c", 3); Assert.Throws<NotSupportedException>(() => dictionary.Add("a", 1)); Assert.Throws<NotSupportedException>(() => dictionary.Remove("a")); Assert.Throws<NotSupportedException>(() => dictionary["a"] = 2); Assert.Throws<NotSupportedException>(() => dictionary.Clear()); Assert.False(dictionary.Contains("a")); Assert.True(dictionary.Contains("c")); Assert.Null(dictionary["a"]); Assert.Equal(3, dictionary["c"]); Assert.True(dictionary.IsFixedSize); Assert.True(dictionary.IsReadOnly); Assert.Equal(new[] { "c" }, dictionary.Keys.Cast<string>().ToArray()); Assert.Equal(new[] { 3 }, dictionary.Values.Cast<int>().ToArray()); } [Fact] public void IDictionaryEnumerator() { var dictionary = (IDictionary)Empty<string, int>().Add("a", 1); var enumerator = dictionary.GetEnumerator(); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Current); Assert.Null(enumerator.Key); Assert.Equal(0, enumerator.Value); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Entry); Assert.True(enumerator.MoveNext()); Assert.Equal(enumerator.Entry, enumerator.Current); Assert.Equal(enumerator.Key, enumerator.Entry.Key); Assert.Equal(enumerator.Value, enumerator.Entry.Value); Assert.Equal("a", enumerator.Key); Assert.Equal(1, enumerator.Value); Assert.False(enumerator.MoveNext()); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Current); Assert.Null(enumerator.Key); Assert.Equal(0, enumerator.Value); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Entry); Assert.False(enumerator.MoveNext()); enumerator.Reset(); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Current); Assert.Null(enumerator.Key); Assert.Equal(0, enumerator.Value); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Entry); Assert.True(enumerator.MoveNext()); Assert.Equal(enumerator.Key, ((DictionaryEntry)enumerator.Current).Key); Assert.Equal(enumerator.Value, ((DictionaryEntry)enumerator.Current).Value); Assert.Equal("a", enumerator.Key); Assert.Equal(1, enumerator.Value); Assert.False(enumerator.MoveNext()); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Current); Assert.Null(enumerator.Key); Assert.Equal(0, enumerator.Value); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Entry); Assert.False(enumerator.MoveNext()); } [Fact] public void TryGetKey() { var dictionary = Empty<int>(StringComparer.OrdinalIgnoreCase) .Add("a", 1); Assert.True(dictionary.TryGetKey("a", out string actualKey)); Assert.Equal("a", actualKey); Assert.True(dictionary.TryGetKey("A", out actualKey)); Assert.Equal("a", actualKey); Assert.False(dictionary.TryGetKey("b", out actualKey)); Assert.Equal("b", actualKey); } protected void EmptyTestHelper<K, V>(IImmutableDictionary<K, V?> empty, K someKey) where K : notnull { Assert.True(IsSame(empty, empty.Clear())); Assert.Equal(0, empty.Count); Assert.Equal(0, empty.Count()); Assert.Equal(0, empty.Keys.Count()); Assert.Equal(0, empty.Values.Count()); Assert.Same(EqualityComparer<V>.Default, GetValueComparer(empty)); Assert.False(empty.ContainsKey(someKey)); Assert.False(empty.Contains(new KeyValuePair<K, V?>(someKey, default(V)))); Assert.Equal(default(V), empty.GetValueOrDefault(someKey)); Assert.False(empty.TryGetValue(someKey, out V? value)); Assert.Equal(default(V), value); } protected void AddExistingKeySameValueTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value1, TValue value2) where TKey : notnull { Assert.NotNull(map); Assert.NotNull(key); Assert.True(GetValueComparer(map).Equals(value1, value2)); map = map.Add(key, value1); Assert.True(IsSame(map, map.Add(key, value2))); Assert.True(IsSame(map, map.AddRange(new[] { new KeyValuePair<TKey, TValue>(key, value2) }))); } /// <summary> /// Verifies that adding a key-value pair where the key already is in the map but with a different value throws. /// </summary> /// <typeparam name="TKey">The type of key in the map.</typeparam> /// <typeparam name="TValue">The type of value in the map.</typeparam> /// <param name="map">The map to manipulate.</param> /// <param name="key">The key to add.</param> /// <param name="value1">The first value to add.</param> /// <param name="value2">The second value to add.</param> /// <remarks> /// Adding a key-value pair to a map where that key already exists, but with a different value, cannot fit the /// semantic of "adding", either by just returning or mutating the value on the existing key. Throwing is the only reasonable response. /// </remarks> protected void AddExistingKeyDifferentValueTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value1, TValue value2) where TKey : notnull { Assert.NotNull(map); Assert.NotNull(key); Assert.False(GetValueComparer(map).Equals(value1, value2)); var map1 = map.Add(key, value1); var map2 = map.Add(key, value2); Assert.Throws<ArgumentException>(null, () => map1.Add(key, value2)); Assert.Throws<ArgumentException>(null, () => map2.Add(key, value1)); } protected static void ContainsKeyTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value) { Assert.False(map.ContainsKey(key)); Assert.True(map.Add(key, value).ContainsKey(key)); } protected static void ContainsTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value) where TKey : notnull { Assert.False(map.Contains(new KeyValuePair<TKey, TValue>(key, value))); Assert.False(map.Contains(key, value)); Assert.True(map.Add(key, value).Contains(new KeyValuePair<TKey, TValue>(key, value))); Assert.True(map.Add(key, value).Contains(key, value)); } protected void RemoveTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue?> map, TKey key) where TKey : notnull { // no-op remove Assert.True(IsSame(map, map.Remove(key))); Assert.True(IsSame(map, map.RemoveRange(Enumerable.Empty<TKey>()))); // substantial remove var addedMap = map.Add(key, default(TValue)); var removedMap = addedMap.Remove(key); Assert.NotSame(addedMap, removedMap); Assert.False(removedMap.ContainsKey(key)); } protected abstract IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>() where TKey : notnull; protected abstract IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer); protected abstract IEqualityComparer<TValue> GetValueComparer<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary) where TKey : notnull; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections.Immutable/tests/ImmutableDictionaryTestBase.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public abstract partial class ImmutableDictionaryTestBase : ImmutablesTestBase { [Fact] public virtual void EmptyTest() { this.EmptyTestHelper(Empty<int, bool>(), 5); } [Fact] public void ContainsTest() { ContainsTestHelper(Empty<int, string>(), 5, "foo"); } [Fact] public void RemoveTest() { RemoveTestHelper(Empty<int, GenericParameterHelper?>(), 5); } [Fact] public void SetItemTest() { var map = this.Empty<string, int>() .SetItem("Microsoft", 100) .SetItem("Corporation", 50); Assert.Equal(2, map.Count); map = map.SetItem("Microsoft", 200); Assert.Equal(2, map.Count); Assert.Equal(200, map["Microsoft"]); // Set it to the same thing again and make sure it's all good. var sameMap = map.SetItem("Microsoft", 200); Assert.True(IsSame(map, sameMap)); } [Fact] public void SetItemsTest() { var template = new Dictionary<string, int> { { "Microsoft", 100 }, { "Corporation", 50 }, }; var map = this.Empty<string, int>().SetItems(template); Assert.Equal(2, map.Count); var changes = new Dictionary<string, int> { { "Microsoft", 150 }, { "Dogs", 90 }, }; map = map.SetItems(changes); Assert.Equal(3, map.Count); Assert.Equal(150, map["Microsoft"]); Assert.Equal(50, map["Corporation"]); Assert.Equal(90, map["Dogs"]); map = map.SetItems( new[] { new KeyValuePair<string, int>("Microsoft", 80), new KeyValuePair<string, int>("Microsoft", 70), }); Assert.Equal(3, map.Count); Assert.Equal(70, map["Microsoft"]); Assert.Equal(50, map["Corporation"]); Assert.Equal(90, map["Dogs"]); map = this.Empty<string, int>().SetItems(new[] { // use an array for code coverage new KeyValuePair<string, int>("a", 1), new KeyValuePair<string, int>("b", 2), new KeyValuePair<string, int>("a", 3), }); Assert.Equal(2, map.Count); Assert.Equal(3, map["a"]); Assert.Equal(2, map["b"]); } [Fact] public void ContainsKeyTest() { ContainsKeyTestHelper(Empty<int, GenericParameterHelper>(), 1, new GenericParameterHelper()); } [Fact] public void IndexGetNonExistingKeyThrowsTest() { Assert.Throws<KeyNotFoundException>(() => this.Empty<int, int>()[3]); } [Fact] public void IndexGetTest() { var map = this.Empty<int, int>().Add(3, 5); Assert.Equal(5, map[3]); } /// <summary> /// Verifies that the GetHashCode method returns the standard one. /// </summary> [Fact] public void GetHashCodeTest() { var dictionary = Empty<string, int>(); Assert.Equal(EqualityComparer<object>.Default.GetHashCode(dictionary), dictionary.GetHashCode()); } [Fact] public void ICollectionOfKVMembers() { var dictionary = (ICollection<KeyValuePair<string, int>>)Empty<string, int>(); Assert.Throws<NotSupportedException>(() => dictionary.Add(new KeyValuePair<string, int>())); Assert.Throws<NotSupportedException>(() => dictionary.Remove(new KeyValuePair<string, int>())); Assert.Throws<NotSupportedException>(() => dictionary.Clear()); Assert.True(dictionary.IsReadOnly); } [Fact] public void ICollectionMembers() { ((ICollection)Empty<string, int>()).CopyTo(Array.Empty<object>(), 0); var dictionary = (ICollection)Empty<string, int>().Add("a", 1); Assert.True(dictionary.IsSynchronized); Assert.NotNull(dictionary.SyncRoot); Assert.Same(dictionary.SyncRoot, dictionary.SyncRoot); var array = new DictionaryEntry[2]; dictionary.CopyTo(array, 1); Assert.Null(array[0].Value); Assert.Equal(new DictionaryEntry("a", 1), (DictionaryEntry)array[1]); } [Fact] public void IDictionaryOfKVMembers() { var dictionary = (IDictionary<string, int>)Empty<string, int>().Add("c", 3); Assert.Throws<NotSupportedException>(() => dictionary.Add("a", 1)); Assert.Throws<NotSupportedException>(() => dictionary.Remove("a")); Assert.Throws<NotSupportedException>(() => dictionary["a"] = 2); Assert.Throws<KeyNotFoundException>(() => dictionary["a"]); Assert.Equal(3, dictionary["c"]); } [Fact] public void IDictionaryMembers() { var dictionary = (IDictionary)Empty<string, int>().Add("c", 3); Assert.Throws<NotSupportedException>(() => dictionary.Add("a", 1)); Assert.Throws<NotSupportedException>(() => dictionary.Remove("a")); Assert.Throws<NotSupportedException>(() => dictionary["a"] = 2); Assert.Throws<NotSupportedException>(() => dictionary.Clear()); Assert.False(dictionary.Contains("a")); Assert.True(dictionary.Contains("c")); Assert.Null(dictionary["a"]); Assert.Equal(3, dictionary["c"]); Assert.True(dictionary.IsFixedSize); Assert.True(dictionary.IsReadOnly); Assert.Equal(new[] { "c" }, dictionary.Keys.Cast<string>().ToArray()); Assert.Equal(new[] { 3 }, dictionary.Values.Cast<int>().ToArray()); } [Fact] public void IDictionaryEnumerator() { var dictionary = (IDictionary)Empty<string, int>().Add("a", 1); var enumerator = dictionary.GetEnumerator(); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Current); Assert.Null(enumerator.Key); Assert.Equal(0, enumerator.Value); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Entry); Assert.True(enumerator.MoveNext()); Assert.Equal(enumerator.Entry, enumerator.Current); Assert.Equal(enumerator.Key, enumerator.Entry.Key); Assert.Equal(enumerator.Value, enumerator.Entry.Value); Assert.Equal("a", enumerator.Key); Assert.Equal(1, enumerator.Value); Assert.False(enumerator.MoveNext()); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Current); Assert.Null(enumerator.Key); Assert.Equal(0, enumerator.Value); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Entry); Assert.False(enumerator.MoveNext()); enumerator.Reset(); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Current); Assert.Null(enumerator.Key); Assert.Equal(0, enumerator.Value); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Entry); Assert.True(enumerator.MoveNext()); Assert.Equal(enumerator.Key, ((DictionaryEntry)enumerator.Current).Key); Assert.Equal(enumerator.Value, ((DictionaryEntry)enumerator.Current).Value); Assert.Equal("a", enumerator.Key); Assert.Equal(1, enumerator.Value); Assert.False(enumerator.MoveNext()); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Current); Assert.Null(enumerator.Key); Assert.Equal(0, enumerator.Value); Assert.Equal(new DictionaryEntry(null!, 0), enumerator.Entry); Assert.False(enumerator.MoveNext()); } [Fact] public void TryGetKey() { var dictionary = Empty<int>(StringComparer.OrdinalIgnoreCase) .Add("a", 1); Assert.True(dictionary.TryGetKey("a", out string actualKey)); Assert.Equal("a", actualKey); Assert.True(dictionary.TryGetKey("A", out actualKey)); Assert.Equal("a", actualKey); Assert.False(dictionary.TryGetKey("b", out actualKey)); Assert.Equal("b", actualKey); } protected void EmptyTestHelper<K, V>(IImmutableDictionary<K, V?> empty, K someKey) where K : notnull { Assert.True(IsSame(empty, empty.Clear())); Assert.Equal(0, empty.Count); Assert.Equal(0, empty.Count()); Assert.Equal(0, empty.Keys.Count()); Assert.Equal(0, empty.Values.Count()); Assert.Same(EqualityComparer<V>.Default, GetValueComparer(empty)); Assert.False(empty.ContainsKey(someKey)); Assert.False(empty.Contains(new KeyValuePair<K, V?>(someKey, default(V)))); Assert.Equal(default(V), empty.GetValueOrDefault(someKey)); Assert.False(empty.TryGetValue(someKey, out V? value)); Assert.Equal(default(V), value); } protected void AddExistingKeySameValueTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value1, TValue value2) where TKey : notnull { Assert.NotNull(map); Assert.NotNull(key); Assert.True(GetValueComparer(map).Equals(value1, value2)); map = map.Add(key, value1); Assert.True(IsSame(map, map.Add(key, value2))); Assert.True(IsSame(map, map.AddRange(new[] { new KeyValuePair<TKey, TValue>(key, value2) }))); } /// <summary> /// Verifies that adding a key-value pair where the key already is in the map but with a different value throws. /// </summary> /// <typeparam name="TKey">The type of key in the map.</typeparam> /// <typeparam name="TValue">The type of value in the map.</typeparam> /// <param name="map">The map to manipulate.</param> /// <param name="key">The key to add.</param> /// <param name="value1">The first value to add.</param> /// <param name="value2">The second value to add.</param> /// <remarks> /// Adding a key-value pair to a map where that key already exists, but with a different value, cannot fit the /// semantic of "adding", either by just returning or mutating the value on the existing key. Throwing is the only reasonable response. /// </remarks> protected void AddExistingKeyDifferentValueTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value1, TValue value2) where TKey : notnull { Assert.NotNull(map); Assert.NotNull(key); Assert.False(GetValueComparer(map).Equals(value1, value2)); var map1 = map.Add(key, value1); var map2 = map.Add(key, value2); Assert.Throws<ArgumentException>(null, () => map1.Add(key, value2)); Assert.Throws<ArgumentException>(null, () => map2.Add(key, value1)); } protected static void ContainsKeyTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value) { Assert.False(map.ContainsKey(key)); Assert.True(map.Add(key, value).ContainsKey(key)); } protected static void ContainsTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value) where TKey : notnull { Assert.False(map.Contains(new KeyValuePair<TKey, TValue>(key, value))); Assert.False(map.Contains(key, value)); Assert.True(map.Add(key, value).Contains(new KeyValuePair<TKey, TValue>(key, value))); Assert.True(map.Add(key, value).Contains(key, value)); } protected void RemoveTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue?> map, TKey key) where TKey : notnull { // no-op remove Assert.True(IsSame(map, map.Remove(key))); Assert.True(IsSame(map, map.RemoveRange(Enumerable.Empty<TKey>()))); // substantial remove var addedMap = map.Add(key, default(TValue)); var removedMap = addedMap.Remove(key); Assert.NotSame(addedMap, removedMap); Assert.False(removedMap.ContainsKey(key)); } protected abstract IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>() where TKey : notnull; protected abstract IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer); protected abstract IEqualityComparer<TValue> GetValueComparer<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary) where TKey : notnull; } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpSyntaxFactsServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.CSharp { [ExportLanguageServiceFactory(typeof(ISyntaxFactsService), LanguageNames.CSharp), Shared] internal sealed partial class CSharpSyntaxFactsServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSyntaxFactsServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) => CSharpSyntaxFactsService.Instance; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.CSharp { [ExportLanguageServiceFactory(typeof(ISyntaxFactsService), LanguageNames.CSharp), Shared] internal sealed partial class CSharpSyntaxFactsServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSyntaxFactsServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) => CSharpSyntaxFactsService.Instance; } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/VisualBasic/Portable/Lowering/MethodToClassRewriter/MethodToClassRewriter.MyBaseMyClassWrapper.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 System.Collections.Generic Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Linq Imports System.Text Imports Microsoft.Cci Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend MustInherit Class MethodToClassRewriter(Of TProxy) Private Function SubstituteMethodForMyBaseOrMyClassCall(receiverOpt As BoundExpression, originalMethodBeingCalled As MethodSymbol) As MethodSymbol If (originalMethodBeingCalled.IsMetadataVirtual OrElse Me.IsInExpressionLambda) AndAlso receiverOpt IsNot Nothing AndAlso (receiverOpt.Kind = BoundKind.MyBaseReference OrElse receiverOpt.Kind = BoundKind.MyClassReference) Then ' NOTE: We can only call a virtual method non-virtually if the type of Me reference ' we pass to this method IS or INHERITS FROM the type of the method we want to call; ' ' Thus, for MyBase/MyClass receivers we MAY need to replace ' the method with a wrapper one to be able to call it non-virtually; ' Dim callingMethodType As TypeSymbol = Me.CurrentMethod.ContainingType Dim topLevelMethodType As TypeSymbol = Me.TopLevelMethod.ContainingType If callingMethodType IsNot topLevelMethodType OrElse Me.IsInExpressionLambda Then Dim newMethod = GetOrCreateMyBaseOrMyClassWrapperFunction(receiverOpt, originalMethodBeingCalled) ' substitute type parameters if needed If newMethod.IsGenericMethod Then Debug.Assert(originalMethodBeingCalled.IsGenericMethod) Dim typeArgs = originalMethodBeingCalled.TypeArguments Debug.Assert(typeArgs.Length = newMethod.Arity) Dim visitedTypeArgs(typeArgs.Length - 1) As TypeSymbol For i = 0 To typeArgs.Length - 1 visitedTypeArgs(i) = VisitType(typeArgs(i)) Next newMethod = newMethod.Construct(visitedTypeArgs.AsImmutableOrNull()) End If Return newMethod End If End If Return originalMethodBeingCalled End Function Private Function GetOrCreateMyBaseOrMyClassWrapperFunction(receiver As BoundExpression, method As MethodSymbol) As MethodSymbol Debug.Assert(receiver IsNot Nothing) Debug.Assert(receiver.IsMyClassReference() OrElse receiver.IsMyBaseReference()) Debug.Assert(method IsNot Nothing) method = method.ConstructedFrom() Dim methodWrapper As MethodSymbol = CompilationState.GetMethodWrapper(method) If methodWrapper IsNot Nothing Then Return methodWrapper End If ' Disregarding what was passed as the receiver, we only need to create one wrapper ' method for a method _symbol_ being called. Thus, if topLevelMethod.ContainingType ' overrides the virtual method M1, 'MyClass.M1' will use a wrapper method for ' topLevelMethod.ContainingType.M1 method symbol and 'MyBase.M1' will use ' a wrapper method for topLevelMethod.ContainingType.BaseType.M1 method symbol. ' In case topLevelMethod.ContainingType DOES NOT override M1, both 'MyClass.M1' and ' 'MyBase.M1' will use a wrapper method for topLevelMethod.ContainingType.BaseType.M1. Dim containingType As NamedTypeSymbol = Me.TopLevelMethod.ContainingType Dim methodContainingType As NamedTypeSymbol = method.ContainingType Dim isMyBase As Boolean = Not methodContainingType.Equals(containingType) Debug.Assert(isMyBase OrElse receiver.Kind = BoundKind.MyClassReference) Dim syntax As SyntaxNode = Me.CurrentMethod.Syntax ' generate and register wrapper method Dim wrapperMethodName As String = GeneratedNames.MakeBaseMethodWrapperName(method.Name, isMyBase) Dim wrapperMethod As New SynthesizedWrapperMethod(DirectCast(containingType, InstanceTypeSymbol), method, wrapperMethodName, syntax) ' register a new method If Me.CompilationState.ModuleBuilderOpt IsNot Nothing Then Me.CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(containingType, wrapperMethod.GetCciAdapter()) End If ' generate method body Dim wrappedMethod As MethodSymbol = wrapperMethod.WrappedMethod Debug.Assert(wrappedMethod.ConstructedFrom() Is method) Dim boundArguments(wrapperMethod.ParameterCount - 1) As BoundExpression For argIndex = 0 To wrapperMethod.ParameterCount - 1 Dim parameterSymbol As ParameterSymbol = wrapperMethod.Parameters(argIndex) boundArguments(argIndex) = New BoundParameter(syntax, parameterSymbol, isLValue:=parameterSymbol.IsByRef, type:=parameterSymbol.Type) Next Dim meParameter As ParameterSymbol = wrapperMethod.MeParameter Dim newReceiver As BoundExpression = Nothing If isMyBase Then newReceiver = New BoundMyBaseReference(syntax, meParameter.Type) Else newReceiver = New BoundMyClassReference(syntax, meParameter.Type) End If Dim boundCall As New BoundCall(syntax, wrappedMethod, Nothing, newReceiver, boundArguments.AsImmutableOrNull, Nothing, wrappedMethod.ReturnType) Dim boundMethodBody As BoundStatement = If(Not wrappedMethod.ReturnType.IsVoidType(), DirectCast(New BoundReturnStatement(syntax, boundCall, Nothing, Nothing), BoundStatement), New BoundBlock(syntax, Nothing, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(Of BoundStatement)( New BoundExpressionStatement(syntax, boundCall), New BoundReturnStatement(syntax, Nothing, Nothing, Nothing)))) ' add to generated method collection and return CompilationState.AddMethodWrapper(method, wrapperMethod, boundMethodBody) Return wrapperMethod End Function ''' <summary> ''' A method that wraps the call to a method through MyBase/MyClass receiver. ''' </summary> ''' <remarks> ''' <example> ''' Class A ''' Protected Overridable Sub F(a As Integer) ''' End Sub ''' End Class ''' ''' Class B ''' Inherits A ''' ''' Public Sub M() ''' Dim b As Integer = 1 ''' Dim f As System.Action = Sub() MyBase.F(b) ''' End Sub ''' End Class ''' </example> ''' </remarks> Friend NotInheritable Class SynthesizedWrapperMethod Inherits SynthesizedMethod Private ReadOnly _wrappedMethod As MethodSymbol Private ReadOnly _typeMap As TypeSubstitution Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol) Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol) Private ReadOnly _returnType As TypeSymbol Private ReadOnly _locations As ImmutableArray(Of Location) ''' <summary> ''' Creates a symbol for a method that wraps the call to a method through MyBase/MyClass receiver. ''' </summary> ''' <param name="containingType">Type that contains wrapper method.</param> ''' <param name="methodToWrap">Method to wrap</param> ''' <param name="wrapperName">Wrapper method name</param> ''' <param name="syntax">Syntax node.</param> Friend Sub New(containingType As InstanceTypeSymbol, methodToWrap As MethodSymbol, wrapperName As String, syntax As SyntaxNode) MyBase.New(syntax, containingType, wrapperName, False) Me._locations = ImmutableArray.Create(Of Location)(syntax.GetLocation()) Me._typeMap = Nothing If Not methodToWrap.IsGenericMethod Then Me._typeParameters = ImmutableArray(Of TypeParameterSymbol).Empty Me._wrappedMethod = methodToWrap Else Me._typeParameters = SynthesizedClonedTypeParameterSymbol.MakeTypeParameters(methodToWrap.OriginalDefinition.TypeParameters, Me, CreateTypeParameter) Dim typeArgs(Me._typeParameters.Length - 1) As TypeSymbol For ind = 0 To Me._typeParameters.Length - 1 typeArgs(ind) = Me._typeParameters(ind) Next Dim newConstructedWrappedMethod As MethodSymbol = methodToWrap.Construct(typeArgs.AsImmutableOrNull()) Me._typeMap = TypeSubstitution.Create(newConstructedWrappedMethod.OriginalDefinition, newConstructedWrappedMethod.OriginalDefinition.TypeParameters, typeArgs.AsImmutableOrNull()) Me._wrappedMethod = newConstructedWrappedMethod End If Dim params(Me._wrappedMethod.ParameterCount - 1) As ParameterSymbol For i = 0 To params.Length - 1 Dim curParam = Me._wrappedMethod.Parameters(i) params(i) = SynthesizedMethod.WithNewContainerAndType(Me, curParam.Type.InternalSubstituteTypeParameters(Me._typeMap).Type, curParam) Next Me._parameters = params.AsImmutableOrNull() Me._returnType = Me._wrappedMethod.ReturnType.InternalSubstituteTypeParameters(Me._typeMap).Type End Sub Friend Overrides ReadOnly Property TypeMap As TypeSubstitution Get Return Me._typeMap End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState as ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) Dim compilation = Me.DeclaringCompilation AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)) ' Dev11 emits DebuggerNonUserCode. We emit DebuggerHidden to hide the method even if JustMyCode is off. AddSynthesizedAttribute(attributes, compilation.SynthesizeDebuggerHiddenAttribute()) End Sub Public ReadOnly Property WrappedMethod As MethodSymbol Get Return Me._wrappedMethod End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return _typeParameters End Get End Property Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol) Get ' This is always a method definition, so the type arguments are the same as the type parameters. If Arity > 0 Then Return StaticCast(Of TypeSymbol).From(Me.TypeParameters) Else Return ImmutableArray(Of TypeSymbol).Empty End If End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return _locations End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return _parameters End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return _returnType End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return Me._wrappedMethod.IsSub End Get End Property Public Overrides ReadOnly Property IsVararg As Boolean Get Return Me._wrappedMethod.IsVararg End Get End Property Public Overrides ReadOnly Property Arity As Integer Get Return _typeParameters.Length End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Private End Get End Property Friend Overrides ReadOnly Property ParameterCount As Integer Get Return Me._parameters.Length End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return False End Get End Property Friend Overrides Function IsMetadataNewSlot(Optional ignoreInterfaceImplementationChanges As Boolean = False) As Boolean Return False End Function Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Linq Imports System.Text Imports Microsoft.Cci Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend MustInherit Class MethodToClassRewriter(Of TProxy) Private Function SubstituteMethodForMyBaseOrMyClassCall(receiverOpt As BoundExpression, originalMethodBeingCalled As MethodSymbol) As MethodSymbol If (originalMethodBeingCalled.IsMetadataVirtual OrElse Me.IsInExpressionLambda) AndAlso receiverOpt IsNot Nothing AndAlso (receiverOpt.Kind = BoundKind.MyBaseReference OrElse receiverOpt.Kind = BoundKind.MyClassReference) Then ' NOTE: We can only call a virtual method non-virtually if the type of Me reference ' we pass to this method IS or INHERITS FROM the type of the method we want to call; ' ' Thus, for MyBase/MyClass receivers we MAY need to replace ' the method with a wrapper one to be able to call it non-virtually; ' Dim callingMethodType As TypeSymbol = Me.CurrentMethod.ContainingType Dim topLevelMethodType As TypeSymbol = Me.TopLevelMethod.ContainingType If callingMethodType IsNot topLevelMethodType OrElse Me.IsInExpressionLambda Then Dim newMethod = GetOrCreateMyBaseOrMyClassWrapperFunction(receiverOpt, originalMethodBeingCalled) ' substitute type parameters if needed If newMethod.IsGenericMethod Then Debug.Assert(originalMethodBeingCalled.IsGenericMethod) Dim typeArgs = originalMethodBeingCalled.TypeArguments Debug.Assert(typeArgs.Length = newMethod.Arity) Dim visitedTypeArgs(typeArgs.Length - 1) As TypeSymbol For i = 0 To typeArgs.Length - 1 visitedTypeArgs(i) = VisitType(typeArgs(i)) Next newMethod = newMethod.Construct(visitedTypeArgs.AsImmutableOrNull()) End If Return newMethod End If End If Return originalMethodBeingCalled End Function Private Function GetOrCreateMyBaseOrMyClassWrapperFunction(receiver As BoundExpression, method As MethodSymbol) As MethodSymbol Debug.Assert(receiver IsNot Nothing) Debug.Assert(receiver.IsMyClassReference() OrElse receiver.IsMyBaseReference()) Debug.Assert(method IsNot Nothing) method = method.ConstructedFrom() Dim methodWrapper As MethodSymbol = CompilationState.GetMethodWrapper(method) If methodWrapper IsNot Nothing Then Return methodWrapper End If ' Disregarding what was passed as the receiver, we only need to create one wrapper ' method for a method _symbol_ being called. Thus, if topLevelMethod.ContainingType ' overrides the virtual method M1, 'MyClass.M1' will use a wrapper method for ' topLevelMethod.ContainingType.M1 method symbol and 'MyBase.M1' will use ' a wrapper method for topLevelMethod.ContainingType.BaseType.M1 method symbol. ' In case topLevelMethod.ContainingType DOES NOT override M1, both 'MyClass.M1' and ' 'MyBase.M1' will use a wrapper method for topLevelMethod.ContainingType.BaseType.M1. Dim containingType As NamedTypeSymbol = Me.TopLevelMethod.ContainingType Dim methodContainingType As NamedTypeSymbol = method.ContainingType Dim isMyBase As Boolean = Not methodContainingType.Equals(containingType) Debug.Assert(isMyBase OrElse receiver.Kind = BoundKind.MyClassReference) Dim syntax As SyntaxNode = Me.CurrentMethod.Syntax ' generate and register wrapper method Dim wrapperMethodName As String = GeneratedNames.MakeBaseMethodWrapperName(method.Name, isMyBase) Dim wrapperMethod As New SynthesizedWrapperMethod(DirectCast(containingType, InstanceTypeSymbol), method, wrapperMethodName, syntax) ' register a new method If Me.CompilationState.ModuleBuilderOpt IsNot Nothing Then Me.CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(containingType, wrapperMethod.GetCciAdapter()) End If ' generate method body Dim wrappedMethod As MethodSymbol = wrapperMethod.WrappedMethod Debug.Assert(wrappedMethod.ConstructedFrom() Is method) Dim boundArguments(wrapperMethod.ParameterCount - 1) As BoundExpression For argIndex = 0 To wrapperMethod.ParameterCount - 1 Dim parameterSymbol As ParameterSymbol = wrapperMethod.Parameters(argIndex) boundArguments(argIndex) = New BoundParameter(syntax, parameterSymbol, isLValue:=parameterSymbol.IsByRef, type:=parameterSymbol.Type) Next Dim meParameter As ParameterSymbol = wrapperMethod.MeParameter Dim newReceiver As BoundExpression = Nothing If isMyBase Then newReceiver = New BoundMyBaseReference(syntax, meParameter.Type) Else newReceiver = New BoundMyClassReference(syntax, meParameter.Type) End If Dim boundCall As New BoundCall(syntax, wrappedMethod, Nothing, newReceiver, boundArguments.AsImmutableOrNull, Nothing, wrappedMethod.ReturnType) Dim boundMethodBody As BoundStatement = If(Not wrappedMethod.ReturnType.IsVoidType(), DirectCast(New BoundReturnStatement(syntax, boundCall, Nothing, Nothing), BoundStatement), New BoundBlock(syntax, Nothing, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(Of BoundStatement)( New BoundExpressionStatement(syntax, boundCall), New BoundReturnStatement(syntax, Nothing, Nothing, Nothing)))) ' add to generated method collection and return CompilationState.AddMethodWrapper(method, wrapperMethod, boundMethodBody) Return wrapperMethod End Function ''' <summary> ''' A method that wraps the call to a method through MyBase/MyClass receiver. ''' </summary> ''' <remarks> ''' <example> ''' Class A ''' Protected Overridable Sub F(a As Integer) ''' End Sub ''' End Class ''' ''' Class B ''' Inherits A ''' ''' Public Sub M() ''' Dim b As Integer = 1 ''' Dim f As System.Action = Sub() MyBase.F(b) ''' End Sub ''' End Class ''' </example> ''' </remarks> Friend NotInheritable Class SynthesizedWrapperMethod Inherits SynthesizedMethod Private ReadOnly _wrappedMethod As MethodSymbol Private ReadOnly _typeMap As TypeSubstitution Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol) Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol) Private ReadOnly _returnType As TypeSymbol Private ReadOnly _locations As ImmutableArray(Of Location) ''' <summary> ''' Creates a symbol for a method that wraps the call to a method through MyBase/MyClass receiver. ''' </summary> ''' <param name="containingType">Type that contains wrapper method.</param> ''' <param name="methodToWrap">Method to wrap</param> ''' <param name="wrapperName">Wrapper method name</param> ''' <param name="syntax">Syntax node.</param> Friend Sub New(containingType As InstanceTypeSymbol, methodToWrap As MethodSymbol, wrapperName As String, syntax As SyntaxNode) MyBase.New(syntax, containingType, wrapperName, False) Me._locations = ImmutableArray.Create(Of Location)(syntax.GetLocation()) Me._typeMap = Nothing If Not methodToWrap.IsGenericMethod Then Me._typeParameters = ImmutableArray(Of TypeParameterSymbol).Empty Me._wrappedMethod = methodToWrap Else Me._typeParameters = SynthesizedClonedTypeParameterSymbol.MakeTypeParameters(methodToWrap.OriginalDefinition.TypeParameters, Me, CreateTypeParameter) Dim typeArgs(Me._typeParameters.Length - 1) As TypeSymbol For ind = 0 To Me._typeParameters.Length - 1 typeArgs(ind) = Me._typeParameters(ind) Next Dim newConstructedWrappedMethod As MethodSymbol = methodToWrap.Construct(typeArgs.AsImmutableOrNull()) Me._typeMap = TypeSubstitution.Create(newConstructedWrappedMethod.OriginalDefinition, newConstructedWrappedMethod.OriginalDefinition.TypeParameters, typeArgs.AsImmutableOrNull()) Me._wrappedMethod = newConstructedWrappedMethod End If Dim params(Me._wrappedMethod.ParameterCount - 1) As ParameterSymbol For i = 0 To params.Length - 1 Dim curParam = Me._wrappedMethod.Parameters(i) params(i) = SynthesizedMethod.WithNewContainerAndType(Me, curParam.Type.InternalSubstituteTypeParameters(Me._typeMap).Type, curParam) Next Me._parameters = params.AsImmutableOrNull() Me._returnType = Me._wrappedMethod.ReturnType.InternalSubstituteTypeParameters(Me._typeMap).Type End Sub Friend Overrides ReadOnly Property TypeMap As TypeSubstitution Get Return Me._typeMap End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState as ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) Dim compilation = Me.DeclaringCompilation AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)) ' Dev11 emits DebuggerNonUserCode. We emit DebuggerHidden to hide the method even if JustMyCode is off. AddSynthesizedAttribute(attributes, compilation.SynthesizeDebuggerHiddenAttribute()) End Sub Public ReadOnly Property WrappedMethod As MethodSymbol Get Return Me._wrappedMethod End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return _typeParameters End Get End Property Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol) Get ' This is always a method definition, so the type arguments are the same as the type parameters. If Arity > 0 Then Return StaticCast(Of TypeSymbol).From(Me.TypeParameters) Else Return ImmutableArray(Of TypeSymbol).Empty End If End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return _locations End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return _parameters End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return _returnType End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return Me._wrappedMethod.IsSub End Get End Property Public Overrides ReadOnly Property IsVararg As Boolean Get Return Me._wrappedMethod.IsVararg End Get End Property Public Overrides ReadOnly Property Arity As Integer Get Return _typeParameters.Length End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Private End Get End Property Friend Overrides ReadOnly Property ParameterCount As Integer Get Return Me._parameters.Length End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return False End Get End Property Friend Overrides Function IsMetadataNewSlot(Optional ignoreInterfaceImplementationChanges As Boolean = False) As Boolean Return False End Function Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function End Class End Class End Namespace
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/EditorFeatures/CSharpTest/AddFileBanner/AddFileBannerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.AddFileBanner; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddFileBanner { public partial class AddFileBannerTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpAddFileBannerCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestBanner1() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||]using System; class Program1 { static void Main() { } } </Document> <Document>// This is the banner class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>// This is the banner using System; class Program1 { static void Main() { } } </Document> <Document>// This is the banner class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestMultiLineBanner1() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||]using System; class Program1 { static void Main() { } } </Document> <Document>// This is the banner // It goes over multiple lines class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>// This is the banner // It goes over multiple lines using System; class Program1 { static void Main() { } } </Document> <Document>// This is the banner // It goes over multiple lines class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task TestSingleLineDocCommentBanner() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||]using System; class Program1 { static void Main() { } } </Document> <Document>/// This is the banner /// It goes over multiple lines class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>/// This is the banner /// It goes over multiple lines using System; class Program1 { static void Main() { } } </Document> <Document>/// This is the banner /// It goes over multiple lines class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task TestMultiLineDocCommentBanner() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||]using System; class Program1 { static void Main() { } } </Document> <Document>/** This is the banner * It goes over multiple lines */ class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>/** This is the banner * It goes over multiple lines */ using System; class Program1 { static void Main() { } } </Document> <Document>/** This is the banner * It goes over multiple lines */ class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestMissingWhenAlreadyThere() { await TestMissingAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||]// I already have a banner using System; class Program1 { static void Main() { } } </Document> <Document>// This is the banner class Program2 { } </Document> </Project> </Workspace>"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] [InlineData("", 1)] [InlineData("file_header_template =", 1)] [InlineData("file_header_template = unset", 1)] [InlineData("file_header_template = defined file header", 0)] public async Task TestMissingWhenHandledByAnalyzer(string fileHeaderTemplate, int expectedActionCount) { var initialMarkup = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""/0/Test0.cs"">[||]using System; class Program1 {{ static void Main() {{ }} }} </Document> <Document FilePath=""/0/Test1.cs"">/// This is the banner /// It goes over multiple lines class Program2 {{ }} </Document> <AnalyzerConfigDocument FilePath=""/.editorconfig""> root = true [*] {fileHeaderTemplate} </AnalyzerConfigDocument> </Project> </Workspace>"; await TestActionCountAsync(initialMarkup, expectedActionCount); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestMissingIfOtherFileDoesNotHaveBanner() { await TestMissingAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||] using System; class Program1 { static void Main() { } } </Document> <Document> class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestMissingIfOtherFileIsAutoGenerated() { await TestMissingAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||] using System; class Program1 { static void Main() { } } </Document> <Document>// &lt;autogenerated /&gt; class Program2 { } </Document> </Project> </Workspace>"); } [WorkItem(32792, "https://github.com/dotnet/roslyn/issues/32792")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestUpdateFileNameInComment() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">[||]using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">// This is the banner in Bar.cs // It goes over multiple lines. This line has Baz.cs // The last line includes Bar.cs class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">// This is the banner in Goo.cs // It goes over multiple lines. This line has Baz.cs // The last line includes Goo.cs using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">// This is the banner in Bar.cs // It goes over multiple lines. This line has Baz.cs // The last line includes Bar.cs class Program2 { } </Document> </Project> </Workspace>"); } [WorkItem(32792, "https://github.com/dotnet/roslyn/issues/32792")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestUpdateFileNameInComment2() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">[||]using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/* This is the banner in Bar.cs It goes over multiple lines. This line has Baz.cs The last line includes Bar.cs */ class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">/* This is the banner in Goo.cs It goes over multiple lines. This line has Baz.cs The last line includes Goo.cs */ using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/* This is the banner in Bar.cs It goes over multiple lines. This line has Baz.cs The last line includes Bar.cs */ class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task TestUpdateFileNameInComment3() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">[||]using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/** This is the banner in Bar.cs It goes over multiple lines. This line has Baz.cs The last line includes Bar.cs */ class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">/** This is the banner in Goo.cs It goes over multiple lines. This line has Baz.cs The last line includes Goo.cs */ using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/** This is the banner in Bar.cs It goes over multiple lines. This line has Baz.cs The last line includes Bar.cs */ class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task TestUpdateFileNameInComment4() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">[||]using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/// This is the banner in Bar.cs /// It goes over multiple lines. This line has Baz.cs /// The last line includes Bar.cs class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">/// This is the banner in Goo.cs /// It goes over multiple lines. This line has Baz.cs /// The last line includes Goo.cs using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/// This is the banner in Bar.cs /// It goes over multiple lines. This line has Baz.cs /// The last line includes Bar.cs class Program2 { } </Document> </Project> </Workspace>"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.AddFileBanner; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddFileBanner { public partial class AddFileBannerTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpAddFileBannerCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestBanner1() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||]using System; class Program1 { static void Main() { } } </Document> <Document>// This is the banner class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>// This is the banner using System; class Program1 { static void Main() { } } </Document> <Document>// This is the banner class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestMultiLineBanner1() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||]using System; class Program1 { static void Main() { } } </Document> <Document>// This is the banner // It goes over multiple lines class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>// This is the banner // It goes over multiple lines using System; class Program1 { static void Main() { } } </Document> <Document>// This is the banner // It goes over multiple lines class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task TestSingleLineDocCommentBanner() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||]using System; class Program1 { static void Main() { } } </Document> <Document>/// This is the banner /// It goes over multiple lines class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>/// This is the banner /// It goes over multiple lines using System; class Program1 { static void Main() { } } </Document> <Document>/// This is the banner /// It goes over multiple lines class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task TestMultiLineDocCommentBanner() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||]using System; class Program1 { static void Main() { } } </Document> <Document>/** This is the banner * It goes over multiple lines */ class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>/** This is the banner * It goes over multiple lines */ using System; class Program1 { static void Main() { } } </Document> <Document>/** This is the banner * It goes over multiple lines */ class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestMissingWhenAlreadyThere() { await TestMissingAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||]// I already have a banner using System; class Program1 { static void Main() { } } </Document> <Document>// This is the banner class Program2 { } </Document> </Project> </Workspace>"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] [InlineData("", 1)] [InlineData("file_header_template =", 1)] [InlineData("file_header_template = unset", 1)] [InlineData("file_header_template = defined file header", 0)] public async Task TestMissingWhenHandledByAnalyzer(string fileHeaderTemplate, int expectedActionCount) { var initialMarkup = $@" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""/0/Test0.cs"">[||]using System; class Program1 {{ static void Main() {{ }} }} </Document> <Document FilePath=""/0/Test1.cs"">/// This is the banner /// It goes over multiple lines class Program2 {{ }} </Document> <AnalyzerConfigDocument FilePath=""/.editorconfig""> root = true [*] {fileHeaderTemplate} </AnalyzerConfigDocument> </Project> </Workspace>"; await TestActionCountAsync(initialMarkup, expectedActionCount); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestMissingIfOtherFileDoesNotHaveBanner() { await TestMissingAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||] using System; class Program1 { static void Main() { } } </Document> <Document> class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestMissingIfOtherFileIsAutoGenerated() { await TestMissingAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>[||] using System; class Program1 { static void Main() { } } </Document> <Document>// &lt;autogenerated /&gt; class Program2 { } </Document> </Project> </Workspace>"); } [WorkItem(32792, "https://github.com/dotnet/roslyn/issues/32792")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestUpdateFileNameInComment() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">[||]using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">// This is the banner in Bar.cs // It goes over multiple lines. This line has Baz.cs // The last line includes Bar.cs class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">// This is the banner in Goo.cs // It goes over multiple lines. This line has Baz.cs // The last line includes Goo.cs using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">// This is the banner in Bar.cs // It goes over multiple lines. This line has Baz.cs // The last line includes Bar.cs class Program2 { } </Document> </Project> </Workspace>"); } [WorkItem(32792, "https://github.com/dotnet/roslyn/issues/32792")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] public async Task TestUpdateFileNameInComment2() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">[||]using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/* This is the banner in Bar.cs It goes over multiple lines. This line has Baz.cs The last line includes Bar.cs */ class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">/* This is the banner in Goo.cs It goes over multiple lines. This line has Baz.cs The last line includes Goo.cs */ using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/* This is the banner in Bar.cs It goes over multiple lines. This line has Baz.cs The last line includes Bar.cs */ class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task TestUpdateFileNameInComment3() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">[||]using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/** This is the banner in Bar.cs It goes over multiple lines. This line has Baz.cs The last line includes Bar.cs */ class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">/** This is the banner in Goo.cs It goes over multiple lines. This line has Baz.cs The last line includes Goo.cs */ using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/** This is the banner in Bar.cs It goes over multiple lines. This line has Baz.cs The last line includes Bar.cs */ class Program2 { } </Document> </Project> </Workspace>"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddFileBanner)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task TestUpdateFileNameInComment4() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">[||]using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/// This is the banner in Bar.cs /// It goes over multiple lines. This line has Baz.cs /// The last line includes Bar.cs class Program2 { } </Document> </Project> </Workspace>", @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Goo.cs"">/// This is the banner in Goo.cs /// It goes over multiple lines. This line has Baz.cs /// The last line includes Goo.cs using System; class Program1 { static void Main() { } } </Document> <Document FilePath=""Bar.cs"">/// This is the banner in Bar.cs /// It goes over multiple lines. This line has Baz.cs /// The last line includes Bar.cs class Program2 { } </Document> </Project> </Workspace>"); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/Core/Portable/MetadataReference/AssemblyIdentityExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis { internal static class AssemblyIdentityExtensions { // Windows.*[.winmd] internal static bool IsWindowsComponent(this AssemblyIdentity identity) { return (identity.ContentType == AssemblyContentType.WindowsRuntime) && identity.Name.StartsWith("windows.", StringComparison.OrdinalIgnoreCase); } // Windows[.winmd] internal static bool IsWindowsRuntime(this AssemblyIdentity identity) { return (identity.ContentType == AssemblyContentType.WindowsRuntime) && string.Equals(identity.Name, "windows", StringComparison.OrdinalIgnoreCase); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis { internal static class AssemblyIdentityExtensions { // Windows.*[.winmd] internal static bool IsWindowsComponent(this AssemblyIdentity identity) { return (identity.ContentType == AssemblyContentType.WindowsRuntime) && identity.Name.StartsWith("windows.", StringComparison.OrdinalIgnoreCase); } // Windows[.winmd] internal static bool IsWindowsRuntime(this AssemblyIdentity identity) { return (identity.ContentType == AssemblyContentType.WindowsRuntime) && string.Equals(identity.Name, "windows", StringComparison.OrdinalIgnoreCase); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/CSharp/Portable/BoundTree/ConversionGroup.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A group is a common instance referenced by all BoundConversion instances /// generated from a single Conversion. The group is used by NullableWalker to /// determine which BoundConversion nodes should be considered as a unit. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal sealed class ConversionGroup { internal ConversionGroup(Conversion conversion, TypeWithAnnotations explicitType = default) { Conversion = conversion; ExplicitType = explicitType; } /// <summary> /// True if the conversion is an explicit conversion. /// </summary> internal bool IsExplicitConversion => ExplicitType.HasType; /// <summary> /// The conversion (from Conversions.ClassifyConversionFromExpression for /// instance) from which all BoundConversions in the group were created. /// </summary> internal readonly Conversion Conversion; /// <summary> /// The target type of the conversion specified explicitly in source, /// or null if not an explicit conversion. /// </summary> internal readonly TypeWithAnnotations ExplicitType; #if DEBUG private static int _nextId; private readonly int _id = _nextId++; internal string GetDebuggerDisplay() { var str = $"#{_id} {Conversion}"; if (ExplicitType.HasType) { str += $" ({ExplicitType})"; } return str; } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A group is a common instance referenced by all BoundConversion instances /// generated from a single Conversion. The group is used by NullableWalker to /// determine which BoundConversion nodes should be considered as a unit. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal sealed class ConversionGroup { internal ConversionGroup(Conversion conversion, TypeWithAnnotations explicitType = default) { Conversion = conversion; ExplicitType = explicitType; } /// <summary> /// True if the conversion is an explicit conversion. /// </summary> internal bool IsExplicitConversion => ExplicitType.HasType; /// <summary> /// The conversion (from Conversions.ClassifyConversionFromExpression for /// instance) from which all BoundConversions in the group were created. /// </summary> internal readonly Conversion Conversion; /// <summary> /// The target type of the conversion specified explicitly in source, /// or null if not an explicit conversion. /// </summary> internal readonly TypeWithAnnotations ExplicitType; #if DEBUG private static int _nextId; private readonly int _id = _nextId++; internal string GetDebuggerDisplay() { var str = $"#{_id} {Conversion}"; if (ExplicitType.HasType) { str += $" ({ExplicitType})"; } return str; } #endif } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/CSharp/Portable/Emitter/Model/GenericNestedTypeInstanceReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Emit; namespace Microsoft.CodeAnalysis.CSharp.Emit { /// <summary> /// Represents a reference to a generic type instantiation that is nested in a non-generic type. /// e.g. A.B{int} /// </summary> internal sealed class GenericNestedTypeInstanceReference : GenericTypeInstanceReference, Cci.INestedTypeReference { public GenericNestedTypeInstanceReference(NamedTypeSymbol underlyingNamedType) : base(underlyingNamedType) { } Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context) { return ((PEModuleBuilder)context.Module).Translate(UnderlyingNamedType.ContainingType, syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNode, diagnostics: context.Diagnostics); } public override Cci.IGenericTypeInstanceReference AsGenericTypeInstanceReference { get { return this; } } public override Cci.INamespaceTypeReference AsNamespaceTypeReference { get { return null; } } public override Cci.INestedTypeReference AsNestedTypeReference { get { return this; } } public override Cci.ISpecializedNestedTypeReference AsSpecializedNestedTypeReference { get { return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.CSharp.Emit { /// <summary> /// Represents a reference to a generic type instantiation that is nested in a non-generic type. /// e.g. A.B{int} /// </summary> internal sealed class GenericNestedTypeInstanceReference : GenericTypeInstanceReference, Cci.INestedTypeReference { public GenericNestedTypeInstanceReference(NamedTypeSymbol underlyingNamedType) : base(underlyingNamedType) { } Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context) { return ((PEModuleBuilder)context.Module).Translate(UnderlyingNamedType.ContainingType, syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNode, diagnostics: context.Diagnostics); } public override Cci.IGenericTypeInstanceReference AsGenericTypeInstanceReference { get { return this; } } public override Cci.INamespaceTypeReference AsNamespaceTypeReference { get { return null; } } public override Cci.INestedTypeReference AsNestedTypeReference { get { return this; } } public override Cci.ISpecializedNestedTypeReference AsSpecializedNestedTypeReference { get { return null; } } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/EditorFeatures/Core.Wpf/SignatureHelp/Model.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp { internal class Model { private readonly DisconnectedBufferGraph _disconnectedBufferGraph; public TextSpan TextSpan { get; } public IList<SignatureHelpItem> Items { get; } public SignatureHelpItem SelectedItem { get; } /// <summary>UserSelected is true if the SelectedItem is the result of a user selection (up/down arrows).</summary> public bool UserSelected { get; } public int ArgumentIndex { get; } public int ArgumentCount { get; } public string ArgumentName { get; } public int? SelectedParameter { get; } public ISignatureHelpProvider Provider { get; } public Model( DisconnectedBufferGraph disconnectedBufferGraph, TextSpan textSpan, ISignatureHelpProvider provider, IList<SignatureHelpItem> items, SignatureHelpItem selectedItem, int argumentIndex, int argumentCount, string argumentName, int? selectedParameter, bool userSelected) { Contract.ThrowIfNull(selectedItem); Contract.ThrowIfFalse(items.Count != 0, "Must have at least one item."); Contract.ThrowIfFalse(items.Contains(selectedItem), "Selected item must be in list of items."); _disconnectedBufferGraph = disconnectedBufferGraph; this.TextSpan = textSpan; this.Items = items; this.Provider = provider; this.SelectedItem = selectedItem; this.UserSelected = userSelected; this.ArgumentIndex = argumentIndex; this.ArgumentCount = argumentCount; this.ArgumentName = argumentName; this.SelectedParameter = selectedParameter; } public Model WithSelectedItem(SignatureHelpItem selectedItem, bool userSelected) { return selectedItem == this.SelectedItem && userSelected == this.UserSelected ? this : new Model(_disconnectedBufferGraph, TextSpan, Provider, Items, selectedItem, ArgumentIndex, ArgumentCount, ArgumentName, SelectedParameter, userSelected); } public Model WithSelectedParameter(int? selectedParameter) { return selectedParameter == this.SelectedParameter ? this : new Model(_disconnectedBufferGraph, TextSpan, Provider, Items, SelectedItem, ArgumentIndex, ArgumentCount, ArgumentName, selectedParameter, UserSelected); } public SnapshotSpan GetCurrentSpanInSubjectBuffer(ITextSnapshot bufferSnapshot) { return _disconnectedBufferGraph.SubjectBufferSnapshot .CreateTrackingSpan(this.TextSpan.ToSpan(), SpanTrackingMode.EdgeInclusive) .GetSpan(bufferSnapshot); } public SnapshotSpan GetCurrentSpanInView(ITextSnapshot textSnapshot) { var originalSpan = _disconnectedBufferGraph.GetSubjectBufferTextSpanInViewBuffer(this.TextSpan); var trackingSpan = _disconnectedBufferGraph.ViewSnapshot.CreateTrackingSpan(originalSpan.TextSpan.ToSpan(), SpanTrackingMode.EdgeInclusive); return trackingSpan.GetSpan(textSnapshot); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp { internal class Model { private readonly DisconnectedBufferGraph _disconnectedBufferGraph; public TextSpan TextSpan { get; } public IList<SignatureHelpItem> Items { get; } public SignatureHelpItem SelectedItem { get; } /// <summary>UserSelected is true if the SelectedItem is the result of a user selection (up/down arrows).</summary> public bool UserSelected { get; } public int ArgumentIndex { get; } public int ArgumentCount { get; } public string ArgumentName { get; } public int? SelectedParameter { get; } public ISignatureHelpProvider Provider { get; } public Model( DisconnectedBufferGraph disconnectedBufferGraph, TextSpan textSpan, ISignatureHelpProvider provider, IList<SignatureHelpItem> items, SignatureHelpItem selectedItem, int argumentIndex, int argumentCount, string argumentName, int? selectedParameter, bool userSelected) { Contract.ThrowIfNull(selectedItem); Contract.ThrowIfFalse(items.Count != 0, "Must have at least one item."); Contract.ThrowIfFalse(items.Contains(selectedItem), "Selected item must be in list of items."); _disconnectedBufferGraph = disconnectedBufferGraph; this.TextSpan = textSpan; this.Items = items; this.Provider = provider; this.SelectedItem = selectedItem; this.UserSelected = userSelected; this.ArgumentIndex = argumentIndex; this.ArgumentCount = argumentCount; this.ArgumentName = argumentName; this.SelectedParameter = selectedParameter; } public Model WithSelectedItem(SignatureHelpItem selectedItem, bool userSelected) { return selectedItem == this.SelectedItem && userSelected == this.UserSelected ? this : new Model(_disconnectedBufferGraph, TextSpan, Provider, Items, selectedItem, ArgumentIndex, ArgumentCount, ArgumentName, SelectedParameter, userSelected); } public Model WithSelectedParameter(int? selectedParameter) { return selectedParameter == this.SelectedParameter ? this : new Model(_disconnectedBufferGraph, TextSpan, Provider, Items, SelectedItem, ArgumentIndex, ArgumentCount, ArgumentName, selectedParameter, UserSelected); } public SnapshotSpan GetCurrentSpanInSubjectBuffer(ITextSnapshot bufferSnapshot) { return _disconnectedBufferGraph.SubjectBufferSnapshot .CreateTrackingSpan(this.TextSpan.ToSpan(), SpanTrackingMode.EdgeInclusive) .GetSpan(bufferSnapshot); } public SnapshotSpan GetCurrentSpanInView(ITextSnapshot textSnapshot) { var originalSpan = _disconnectedBufferGraph.GetSubjectBufferTextSpanInViewBuffer(this.TextSpan); var trackingSpan = _disconnectedBufferGraph.ViewSnapshot.CreateTrackingSpan(originalSpan.TextSpan.ToSpan(), SpanTrackingMode.EdgeInclusive); return trackingSpan.GetSpan(textSnapshot); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/VisualStudio/IntegrationTest/TestUtilities/Common/Reference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Roslyn.Utilities; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Common { /// <summary> /// Represents a result of a Find References operation. /// </summary> [Serializable] public class Reference : IEquatable<Reference> { public string? FilePath { get; set; } public int Line { get; set; } public int Column { get; set; } public string? Code { get; set; } public Reference() { } public bool Equals(Reference? other) { if (other == null) { return false; } return string.Equals(FilePath, other.FilePath, StringComparison.OrdinalIgnoreCase) && Line == other.Line && Column == other.Column && string.Equals(Code, other.Code, StringComparison.Ordinal); } public override bool Equals(object? obj) => Equals(obj as Reference); public override int GetHashCode() { return Hash.Combine(FilePath, Hash.Combine(Line, Hash.Combine(Column, Hash.Combine(Code, 0)))); } public override string ToString() => $"{FilePath} ({Line}, {Column}): {Code}"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Roslyn.Utilities; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Common { /// <summary> /// Represents a result of a Find References operation. /// </summary> [Serializable] public class Reference : IEquatable<Reference> { public string? FilePath { get; set; } public int Line { get; set; } public int Column { get; set; } public string? Code { get; set; } public Reference() { } public bool Equals(Reference? other) { if (other == null) { return false; } return string.Equals(FilePath, other.FilePath, StringComparison.OrdinalIgnoreCase) && Line == other.Line && Column == other.Column && string.Equals(Code, other.Code, StringComparison.Ordinal); } public override bool Equals(object? obj) => Equals(obj as Reference); public override int GetHashCode() { return Hash.Combine(FilePath, Hash.Combine(Line, Hash.Combine(Column, Hash.Combine(Code, 0)))); } public override string ToString() => $"{FilePath} ({Line}, {Column}): {Code}"; } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/Server/VBCSCompiler/DiagnosticListener.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Pipes; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.CompilerServer { internal interface IDiagnosticListener { /// <summary> /// Called when the server updates the keep alive value. /// </summary> void UpdateKeepAlive(TimeSpan keepAlive); /// <summary> /// Called when a connection to the server occurs. /// </summary> void ConnectionReceived(); /// <summary> /// Called when a connection has finished processing. /// </summary> void ConnectionCompleted(CompletionData completionData); /// <summary> /// Called when the server is shutting down because the keep alive timeout was reached. /// </summary> void KeepAliveReached(); } internal sealed class EmptyDiagnosticListener : IDiagnosticListener { public void UpdateKeepAlive(TimeSpan keepAlive) { } public void ConnectionReceived() { } public void ConnectionCompleted(CompletionData completionData) { } public void KeepAliveReached() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Pipes; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.CompilerServer { internal interface IDiagnosticListener { /// <summary> /// Called when the server updates the keep alive value. /// </summary> void UpdateKeepAlive(TimeSpan keepAlive); /// <summary> /// Called when a connection to the server occurs. /// </summary> void ConnectionReceived(); /// <summary> /// Called when a connection has finished processing. /// </summary> void ConnectionCompleted(CompletionData completionData); /// <summary> /// Called when the server is shutting down because the keep alive timeout was reached. /// </summary> void KeepAliveReached(); } internal sealed class EmptyDiagnosticListener : IDiagnosticListener { public void UpdateKeepAlive(TimeSpan keepAlive) { } public void ConnectionReceived() { } public void ConnectionCompleted(CompletionData completionData) { } public void KeepAliveReached() { } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/Core/Portable/Diagnostic/CustomObsoleteDiagnosticInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal sealed class CustomObsoleteDiagnosticInfo : DiagnosticInfo { private DiagnosticDescriptor? _descriptor; internal ObsoleteAttributeData Data { get; } internal CustomObsoleteDiagnosticInfo(CommonMessageProvider messageProvider, int errorCode, ObsoleteAttributeData data, params object[] arguments) : base(messageProvider, errorCode, arguments) { Data = data; } private CustomObsoleteDiagnosticInfo(CustomObsoleteDiagnosticInfo baseInfo, DiagnosticSeverity effectiveSeverity) : base(baseInfo, effectiveSeverity) { Data = baseInfo.Data; } public override string MessageIdentifier { get { var id = Data.DiagnosticId; if (!string.IsNullOrEmpty(id)) { return id; } return base.MessageIdentifier; } } public override DiagnosticDescriptor Descriptor { get { if (_descriptor == null) { Interlocked.CompareExchange(ref _descriptor, CreateDescriptor(), null); } return _descriptor; } } internal override DiagnosticInfo GetInstanceWithSeverity(DiagnosticSeverity severity) { return new CustomObsoleteDiagnosticInfo(this, severity); } private DiagnosticDescriptor CreateDescriptor() { var baseDescriptor = base.Descriptor; var diagnosticId = Data.DiagnosticId; var urlFormat = Data.UrlFormat; if (diagnosticId is null && urlFormat is null) { return baseDescriptor; } var id = MessageIdentifier; var helpLinkUri = baseDescriptor.HelpLinkUri; if (urlFormat is object) { try { helpLinkUri = string.Format(urlFormat, id); } catch { // if string.Format fails we just want to use the default (non-user specified) URI. } } ImmutableArray<string> customTags; if (diagnosticId is null) { customTags = baseDescriptor.ImmutableCustomTags; } else { customTags = baseDescriptor.ImmutableCustomTags.Add(WellKnownDiagnosticTags.CustomObsolete); } return new DiagnosticDescriptor( id: id, title: baseDescriptor.Title, messageFormat: baseDescriptor.MessageFormat, category: baseDescriptor.Category, defaultSeverity: baseDescriptor.DefaultSeverity, isEnabledByDefault: baseDescriptor.IsEnabledByDefault, description: baseDescriptor.Description, helpLinkUri: helpLinkUri, customTags: customTags); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal sealed class CustomObsoleteDiagnosticInfo : DiagnosticInfo { private DiagnosticDescriptor? _descriptor; internal ObsoleteAttributeData Data { get; } internal CustomObsoleteDiagnosticInfo(CommonMessageProvider messageProvider, int errorCode, ObsoleteAttributeData data, params object[] arguments) : base(messageProvider, errorCode, arguments) { Data = data; } private CustomObsoleteDiagnosticInfo(CustomObsoleteDiagnosticInfo baseInfo, DiagnosticSeverity effectiveSeverity) : base(baseInfo, effectiveSeverity) { Data = baseInfo.Data; } public override string MessageIdentifier { get { var id = Data.DiagnosticId; if (!string.IsNullOrEmpty(id)) { return id; } return base.MessageIdentifier; } } public override DiagnosticDescriptor Descriptor { get { if (_descriptor == null) { Interlocked.CompareExchange(ref _descriptor, CreateDescriptor(), null); } return _descriptor; } } internal override DiagnosticInfo GetInstanceWithSeverity(DiagnosticSeverity severity) { return new CustomObsoleteDiagnosticInfo(this, severity); } private DiagnosticDescriptor CreateDescriptor() { var baseDescriptor = base.Descriptor; var diagnosticId = Data.DiagnosticId; var urlFormat = Data.UrlFormat; if (diagnosticId is null && urlFormat is null) { return baseDescriptor; } var id = MessageIdentifier; var helpLinkUri = baseDescriptor.HelpLinkUri; if (urlFormat is object) { try { helpLinkUri = string.Format(urlFormat, id); } catch { // if string.Format fails we just want to use the default (non-user specified) URI. } } ImmutableArray<string> customTags; if (diagnosticId is null) { customTags = baseDescriptor.ImmutableCustomTags; } else { customTags = baseDescriptor.ImmutableCustomTags.Add(WellKnownDiagnosticTags.CustomObsolete); } return new DiagnosticDescriptor( id: id, title: baseDescriptor.Title, messageFormat: baseDescriptor.MessageFormat, category: baseDescriptor.Category, defaultSeverity: baseDescriptor.DefaultSeverity, isEnabledByDefault: baseDescriptor.IsEnabledByDefault, description: baseDescriptor.Description, helpLinkUri: helpLinkUri, customTags: customTags); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/CSharp/Test/Symbol/Symbols/ModuleInitializers/SignatureTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.ModuleInitializers { [CompilerTrait(CompilerFeature.ModuleInitializers)] public sealed class SignatureTests : CSharpTestBase { private static readonly CSharpParseOptions s_parseOptions = TestOptions.Regular9; [Fact] public void MustNotBeInstanceMethod() { string source = @" using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal void M() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var compilation = CreateCompilation(source, parseOptions: s_parseOptions); compilation.VerifyEmitDiagnostics( // (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void' // [ModuleInitializer] Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(6, 6) ); } [Fact] public void MustNotBeInstanceMethodInInterface() { string source = @" using System.Runtime.CompilerServices; interface i { [ModuleInitializer] internal void M1(); [ModuleInitializer] internal void M2() { } } "; var compilation = CreateCompilation(source, parseOptions: s_parseOptions, targetFramework: TargetFramework.NetCoreApp); compilation.VerifyEmitDiagnostics( // (6,6): error CS8815: Module initializer method 'M1' must be static, must have no parameters, and must return 'void' // [ModuleInitializer] Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M1").WithLocation(6, 6), // (9,6): error CS8815: Module initializer method 'M2' must be static, must have no parameters, and must return 'void' // [ModuleInitializer] Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M2").WithLocation(9, 6) ); } [Fact] public void MustNotHaveParameters() { string source = @" using System.Runtime.CompilerServices; static class C { [ModuleInitializer] internal static void M(object p) { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var compilation = CreateCompilation(source, parseOptions: s_parseOptions); compilation.VerifyEmitDiagnostics( // (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void' // [ModuleInitializer] Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(6, 6) ); } [Fact] public void MustNotHaveOptionalParameters() { string source = @" using System.Runtime.CompilerServices; static class C { [ModuleInitializer] internal static void M(object p = null) { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var compilation = CreateCompilation(source, parseOptions: s_parseOptions); compilation.VerifyEmitDiagnostics( // (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void' // [ModuleInitializer] Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(6, 6) ); } [Fact] public void MustNotHaveParamsArrayParameters() { string source = @" using System.Runtime.CompilerServices; static class C { [ModuleInitializer] internal static void M(params object[] p) { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var compilation = CreateCompilation(source, parseOptions: s_parseOptions); compilation.VerifyEmitDiagnostics( // (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void' // [ModuleInitializer] Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(6, 6) ); } [Fact] public void MustNotReturnAValue() { string source = @" using System.Runtime.CompilerServices; static class C { [ModuleInitializer] internal static object M() => null; } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var compilation = CreateCompilation(source, parseOptions: s_parseOptions); compilation.VerifyEmitDiagnostics( // (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void' // [ModuleInitializer] Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(6, 6) ); } [Fact] public void MayBeAsyncVoid() { string source = @" using System; using System.Runtime.CompilerServices; static class C { [ModuleInitializer] internal static async void M() => Console.WriteLine(""C.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" C.M Program.Main"); } [Fact] public void MayNotReturnAwaitableWithVoidResult() { string source = @" using System.Runtime.CompilerServices; using System.Threading.Tasks; static class C { [ModuleInitializer] internal static async Task M() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var compilation = CreateCompilation(source, parseOptions: s_parseOptions); compilation.VerifyEmitDiagnostics( // (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void' // [ModuleInitializer] Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(7, 6), // (8,32): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // internal static async Task M() { } Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M").WithLocation(8, 32)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.ModuleInitializers { [CompilerTrait(CompilerFeature.ModuleInitializers)] public sealed class SignatureTests : CSharpTestBase { private static readonly CSharpParseOptions s_parseOptions = TestOptions.Regular9; [Fact] public void MustNotBeInstanceMethod() { string source = @" using System.Runtime.CompilerServices; class C { [ModuleInitializer] internal void M() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var compilation = CreateCompilation(source, parseOptions: s_parseOptions); compilation.VerifyEmitDiagnostics( // (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void' // [ModuleInitializer] Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(6, 6) ); } [Fact] public void MustNotBeInstanceMethodInInterface() { string source = @" using System.Runtime.CompilerServices; interface i { [ModuleInitializer] internal void M1(); [ModuleInitializer] internal void M2() { } } "; var compilation = CreateCompilation(source, parseOptions: s_parseOptions, targetFramework: TargetFramework.NetCoreApp); compilation.VerifyEmitDiagnostics( // (6,6): error CS8815: Module initializer method 'M1' must be static, must have no parameters, and must return 'void' // [ModuleInitializer] Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M1").WithLocation(6, 6), // (9,6): error CS8815: Module initializer method 'M2' must be static, must have no parameters, and must return 'void' // [ModuleInitializer] Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M2").WithLocation(9, 6) ); } [Fact] public void MustNotHaveParameters() { string source = @" using System.Runtime.CompilerServices; static class C { [ModuleInitializer] internal static void M(object p) { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var compilation = CreateCompilation(source, parseOptions: s_parseOptions); compilation.VerifyEmitDiagnostics( // (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void' // [ModuleInitializer] Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(6, 6) ); } [Fact] public void MustNotHaveOptionalParameters() { string source = @" using System.Runtime.CompilerServices; static class C { [ModuleInitializer] internal static void M(object p = null) { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var compilation = CreateCompilation(source, parseOptions: s_parseOptions); compilation.VerifyEmitDiagnostics( // (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void' // [ModuleInitializer] Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(6, 6) ); } [Fact] public void MustNotHaveParamsArrayParameters() { string source = @" using System.Runtime.CompilerServices; static class C { [ModuleInitializer] internal static void M(params object[] p) { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var compilation = CreateCompilation(source, parseOptions: s_parseOptions); compilation.VerifyEmitDiagnostics( // (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void' // [ModuleInitializer] Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(6, 6) ); } [Fact] public void MustNotReturnAValue() { string source = @" using System.Runtime.CompilerServices; static class C { [ModuleInitializer] internal static object M() => null; } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var compilation = CreateCompilation(source, parseOptions: s_parseOptions); compilation.VerifyEmitDiagnostics( // (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void' // [ModuleInitializer] Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(6, 6) ); } [Fact] public void MayBeAsyncVoid() { string source = @" using System; using System.Runtime.CompilerServices; static class C { [ModuleInitializer] internal static async void M() => Console.WriteLine(""C.M""); } class Program { static void Main() => Console.WriteLine(""Program.Main""); } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify(source, parseOptions: s_parseOptions, expectedOutput: @" C.M Program.Main"); } [Fact] public void MayNotReturnAwaitableWithVoidResult() { string source = @" using System.Runtime.CompilerServices; using System.Threading.Tasks; static class C { [ModuleInitializer] internal static async Task M() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; var compilation = CreateCompilation(source, parseOptions: s_parseOptions); compilation.VerifyEmitDiagnostics( // (6,6): error CS8815: Module initializer method 'M' must be static, must have no parameters, and must return 'void' // [ModuleInitializer] Diagnostic(ErrorCode.ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid, "ModuleInitializer").WithArguments("M").WithLocation(7, 6), // (8,32): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // internal static async Task M() { } Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M").WithLocation(8, 32)); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/EditorFeatures/Core/IIntellisensePresenterSession.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor { internal interface IIntelliSensePresenterSession { void Dismiss(); event EventHandler<EventArgs> Dismissed; } internal interface IIntelliSensePresenter<TPresenter, TEditorSessionOpt> where TPresenter : IIntelliSensePresenterSession { TPresenter CreateSession(ITextView textView, ITextBuffer subjectBuffer, TEditorSessionOpt sessionOpt); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor { internal interface IIntelliSensePresenterSession { void Dismiss(); event EventHandler<EventArgs> Dismissed; } internal interface IIntelliSensePresenter<TPresenter, TEditorSessionOpt> where TPresenter : IIntelliSensePresenterSession { TPresenter CreateSession(ITextView textView, ITextBuffer subjectBuffer, TEditorSessionOpt sessionOpt); } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/VisualBasic/Portable/Symbols/SymbolVisitor`2.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Virtual dispatch based on a symbol's particular class. ''' </summary> ''' <typeparam name="TResult">Result type</typeparam> ''' <typeparam name="TArgument">Additional argument type</typeparam> Friend MustInherit Class VisualBasicSymbolVisitor(Of TArgument, TResult) ''' <summary> ''' Call the correct VisitXXX method in this class based on the particular type of symbol that is passed in. ''' </summary> Public Overridable Function Visit(symbol As Symbol, Optional arg As TArgument = Nothing) As TResult If symbol Is Nothing Then Return Nothing End If Return symbol.Accept(Me, arg) End Function Public Overridable Function DefaultVisit(symbol As Symbol, arg As TArgument) As TResult Return Nothing End Function Public Overridable Function VisitAlias(symbol As AliasSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitAssembly(symbol As AssemblySymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitModule(symbol As ModuleSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitNamespace(symbol As NamespaceSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitNamedType(symbol As NamedTypeSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitTypeParameter(symbol As TypeParameterSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitArrayType(symbol As ArrayTypeSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitErrorType(symbol As ErrorTypeSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitMethod(symbol As MethodSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitProperty(symbol As PropertySymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitField(symbol As FieldSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitParameter(symbol As ParameterSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitLocal(symbol As LocalSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitRangeVariable(symbol As RangeVariableSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitLabel(symbol As LabelSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitEvent(symbol As EventSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) 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.Generic Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Virtual dispatch based on a symbol's particular class. ''' </summary> ''' <typeparam name="TResult">Result type</typeparam> ''' <typeparam name="TArgument">Additional argument type</typeparam> Friend MustInherit Class VisualBasicSymbolVisitor(Of TArgument, TResult) ''' <summary> ''' Call the correct VisitXXX method in this class based on the particular type of symbol that is passed in. ''' </summary> Public Overridable Function Visit(symbol As Symbol, Optional arg As TArgument = Nothing) As TResult If symbol Is Nothing Then Return Nothing End If Return symbol.Accept(Me, arg) End Function Public Overridable Function DefaultVisit(symbol As Symbol, arg As TArgument) As TResult Return Nothing End Function Public Overridable Function VisitAlias(symbol As AliasSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitAssembly(symbol As AssemblySymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitModule(symbol As ModuleSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitNamespace(symbol As NamespaceSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitNamedType(symbol As NamedTypeSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitTypeParameter(symbol As TypeParameterSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitArrayType(symbol As ArrayTypeSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitErrorType(symbol As ErrorTypeSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitMethod(symbol As MethodSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitProperty(symbol As PropertySymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitField(symbol As FieldSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitParameter(symbol As ParameterSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitLocal(symbol As LocalSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitRangeVariable(symbol As RangeVariableSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitLabel(symbol As LabelSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function Public Overridable Function VisitEvent(symbol As EventSymbol, arg As TArgument) As TResult Return DefaultVisit(symbol, arg) End Function End Class End Namespace
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/EditorFeatures/VisualBasicTest/Structure/MetadataAsSource/EnumMemberDeclarationStructureTests.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.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining.MetadataAsSource Public Class EnumMemberDeclarationStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of EnumMemberDeclarationSyntax) Protected Overrides ReadOnly Property WorkspaceKind As String Get Return CodeAnalysis.WorkspaceKind.MetadataAsSource End Get End Property Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New EnumMemberDeclarationStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function NoCommentsOrAttributes() As Task Dim code = " Enum E $$Goo Bar End Enum " Await VerifyNoBlockSpansAsync(code) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithAttributes() As Task Dim code = " Enum E {|hint:{|textspan:<Blah> |}$$Goo|} Bar End Enum " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithCommentsAndAttributes() As Task Dim code = " Enum E {|hint:{|textspan:' Summary: ' This is a summary. <Blah> |}$$Goo|} Bar End Enum " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining.MetadataAsSource Public Class EnumMemberDeclarationStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of EnumMemberDeclarationSyntax) Protected Overrides ReadOnly Property WorkspaceKind As String Get Return CodeAnalysis.WorkspaceKind.MetadataAsSource End Get End Property Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New EnumMemberDeclarationStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function NoCommentsOrAttributes() As Task Dim code = " Enum E $$Goo Bar End Enum " Await VerifyNoBlockSpansAsync(code) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithAttributes() As Task Dim code = " Enum E {|hint:{|textspan:<Blah> |}$$Goo|} Bar End Enum " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithCommentsAndAttributes() As Task Dim code = " Enum E {|hint:{|textspan:' Summary: ' This is a summary. <Blah> |}$$Goo|} Bar End Enum " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function End Class End Namespace
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/VisualStudio/Core/Test/CodeModel/VisualBasic/FileCodeModelTests.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.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements Imports Microsoft.VisualStudio.LanguageServices.Implementation.Interop Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Public Class VisualBasicFileCodeModelTests Inherits AbstractFileCodeModelTests <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestEnumerationWithCountAndItem() Dim code = <Code> Namespace N End Namespace Class C End Class Interface I End Interface Structure S End Structure Enum E Goo End Enum Delegate Sub D() </Code> Using workspaceAndFileCodeModel = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim codeElements = workspaceAndFileCodeModel.FileCodeModel.CodeElements Dim count = codeElements.Count Assert.Equal(6, count) Dim expectedKinds = {EnvDTE.vsCMElement.vsCMElementNamespace, EnvDTE.vsCMElement.vsCMElementClass, EnvDTE.vsCMElement.vsCMElementInterface, EnvDTE.vsCMElement.vsCMElementStruct, EnvDTE.vsCMElement.vsCMElementEnum, EnvDTE.vsCMElement.vsCMElementDelegate} Dim expectedNames = {"N", "C", "I", "S", "E", "D"} For i = 0 To count - 1 Dim element = codeElements.Item(i + 1) Assert.Equal(expectedKinds(i), element.Kind) Assert.Equal(expectedNames(i), element.Name) Next Dim j As Integer For Each element As EnvDTE.CodeElement In codeElements Assert.Equal(expectedKinds(j), element.Kind) Assert.Equal(expectedNames(j), element.Name) j += 1 Next End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAssemblyLevelAttribute() Dim code = <Code> &lt;Assembly: Goo(0, True, S:="x")&gt; Class GooAttribute Inherits System.Attribute Public Sub New(i As Integer, b As Boolean) End Sub Public Property S() As String Get Return String.Empty End Get Set(ByVal value As String) End Set End Property End Class </Code> Using workspaceAndFileCodeModel = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim codeElements = workspaceAndFileCodeModel.FileCodeModel.CodeElements Dim count = codeElements.Count Assert.Equal(2, count) Dim codeAttribute = TryCast(codeElements.Item(1), EnvDTE80.CodeAttribute2) Assert.NotNull(codeAttribute) Assert.Same(workspaceAndFileCodeModel.FileCodeModel, codeAttribute.Parent) Assert.Equal("Goo", codeAttribute.Name) Assert.Equal("GooAttribute", codeAttribute.FullName) Assert.Equal("Assembly", codeAttribute.Target) Assert.Equal("0, True, S:=""x""", codeAttribute.Value) Dim arguments = codeAttribute.Arguments Assert.Equal(3, arguments.Count) Dim arg1 = TryCast(arguments.Item(1), EnvDTE80.CodeAttributeArgument) Assert.NotNull(arg1) Assert.Equal("", arg1.Name) Assert.Equal("0", arg1.Value) Dim arg2 = TryCast(arguments.Item(2), EnvDTE80.CodeAttributeArgument) Assert.NotNull(arg2) Assert.Equal("", arg2.Name) Assert.Equal("True", arg2.Value) Dim arg3 = TryCast(arguments.Item(3), EnvDTE80.CodeAttributeArgument) Assert.NotNull(arg3) Assert.Equal("S", arg3.Name) Assert.Equal("""x""", arg3.Value) End Using End Sub <WorkItem(1111417, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1111417")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestCodeElementFullName() Dim code = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Namespace Outer Public Class Class1 Public Property Prop1 As Integer Public var1 As Class3 Public Event event1() Public Function func1() As Integer Return 1 End Function Public Class Class3 End Class End Class End Namespace</Document> </Project> </Workspace> Using workspaceAndFileCodeModel = CreateCodeModelTestState(code) Dim codeElements = workspaceAndFileCodeModel.FileCodeModel.CodeElements Dim namespaceElement = TryCast(codeElements.Item(1), EnvDTE.CodeNamespace) Assert.NotNull(namespaceElement) Assert.Same(workspaceAndFileCodeModel.FileCodeModel, namespaceElement.Parent) Assert.Equal("Outer", namespaceElement.Name) Assert.Equal("BarBaz.Outer", namespaceElement.FullName) Dim codeClass = TryCast(namespaceElement.Members.Item(1), EnvDTE.CodeClass) Assert.NotNull(codeClass) Assert.Equal("Class1", codeClass.Name) Assert.Equal("BarBaz.Outer.Class1", codeClass.FullName) Dim classMembers = codeClass.Members Dim prop = TryCast(classMembers.Item(1), EnvDTE.CodeProperty) Assert.NotNull(prop) Assert.Equal("Prop1", prop.Name) Assert.Equal("BarBaz.Outer.Class1.Prop1", prop.FullName) Dim variable = TryCast(classMembers.Item(2), EnvDTE.CodeVariable) Assert.NotNull(variable) Assert.Equal("var1", variable.Name) Assert.Equal("BarBaz.Outer.Class1.var1", variable.FullName) Assert.Equal("BarBaz.Outer.Class1.Class3", variable.Type.AsFullName) Dim event1 = TryCast(classMembers.Item(3), EnvDTE80.CodeEvent) Assert.NotNull(event1) Assert.Equal("event1", event1.Name) Assert.Equal("BarBaz.Outer.Class1.event1", event1.FullName) Dim func1 = TryCast(classMembers.Item(4), EnvDTE.CodeFunction) Assert.NotNull(func1) Assert.Equal("func1", func1.Name) Assert.Equal("BarBaz.Outer.Class1.func1", func1.FullName) End Using End Sub <WorkItem(150349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150349")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub NoChildrenForInvalidMembers() Dim code = <Code> Sub M() End Sub Function M() As Integer End Function Property P As Integer Event E() Class C End Class </Code> TestChildren(code, IsElement("C")) End Sub #Region "AddAttribute tests" Private Function TestAddAttributeWithSimplificationAsync( code As XElement, expectedCode As XElement, data As AttributeData, expectedUnsimplifiedName As String, expectedSimplifiedName As String) As Task Return TestAddAttributeWithSimplificationAsync(code, expectedCode, Sub(fileCodeModel, batch) Dim newAttribute = fileCodeModel.AddAttribute(data.Name, data.Value, data.Position) Assert.NotNull(newAttribute) Assert.Equal(If(batch, expectedUnsimplifiedName, expectedSimplifiedName), newAttribute.Name) End Sub) End Function Protected Async Function TestAddAttributeWithSimplificationAsync(code As XElement, expectedCode As XElement, testOperation As Action(Of EnvDTE.FileCodeModel, Boolean)) As Task Await TestAddAttributeWithBatchModeAsync(code, expectedCode, testOperation, False) Await TestAddAttributeWithBatchModeAsync(code, expectedCode, testOperation, True) End Function Private Async Function TestAddAttributeWithBatchModeAsync(code As XElement, expectedCode As XElement, testOperation As Action(Of EnvDTE.FileCodeModel, Boolean), batch As Boolean) As Task WpfTestRunner.RequireWpfFact($"Test calls {NameOf(Me.TestAddAttributeWithBatchModeAsync)} which means we're creating new {NameOf(EnvDTE.CodeModel)} elements.") ' NOTE: this method is the same as MyBase.TestOperation, but tells the lambda whether we are batching or not. ' This is because the tests have different behavior up until EndBatch is called. Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) If batch Then fileCodeModel.BeginBatch() End If testOperation(fileCodeModel, batch) If batch Then fileCodeModel.EndBatch() End If Dim text = (Await state.GetDocumentAtCursor().GetTextAsync()).ToString() Assert.Equal(expectedCode.NormalizedValue.Trim(), text.Trim()) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute1() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> &lt;Assembly: CLSCompliant(True)&gt; Class C End Class </Code> Await TestAddAttributeWithSimplificationAsync(code, expected, New AttributeData With {.Name = "System.CLSCompliant", .Value = "True"}, "System.CLSCompliant", "CLSCompliant") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute2() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> &lt;Assembly: CLSCompliant(True)&gt; Class C End Class </Code> Await TestAddAttributeWithSimplificationAsync(code, expected, New AttributeData With {.Name = "System.CLSCompliant", .Value = "True", .Position = "C"}, "System.CLSCompliant", "CLSCompliant") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute3() As Task Dim code = <Code> $$&lt;Assembly: System.Reflection.AssemblyCompany("Microsoft")&gt; </Code> Dim expected = <Code> &lt;Assembly: System.Reflection.AssemblyCompany("Microsoft")&gt; &lt;Assembly: CLSCompliant(True)&gt; </Code> Await TestAddAttributeWithSimplificationAsync(code, expected, New AttributeData With {.Name = "System.CLSCompliant", .Value = "True", .Position = -1}, "System.CLSCompliant", "CLSCompliant") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute4() As Task Dim code = <Code> $$&lt;Assembly: System.Reflection.AssemblyCompany("Microsoft")&gt; Class C End Class </Code> Dim expected = <Code> &lt;Assembly: System.Reflection.AssemblyCompany("Microsoft")&gt; &lt;Assembly: CLSCompliant(True)&gt; Class C End Class </Code> Await TestAddAttributeWithSimplificationAsync(code, expected, New AttributeData With {.Name = "System.CLSCompliant", .Value = "True", .Position = -1}, "System.CLSCompliant", "CLSCompliant") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute5() As Task Dim code = <Code> $$&lt;Assembly: System.Reflection.AssemblyCompany("Microsoft")&gt; &lt;Assembly: System.Reflection.AssemblyCopyright("2012")&gt; Class C End Class </Code> Dim expected = <Code> &lt;Assembly: System.Reflection.AssemblyCompany("Microsoft")&gt; &lt;Assembly: System.Reflection.AssemblyCopyright("2012")&gt; &lt;Assembly: CLSCompliant(True)&gt; Class C End Class</Code> Await TestAddAttributeWithSimplificationAsync(code, expected, New AttributeData With {.Name = "System.CLSCompliant", .Value = "True", .Position = -1}, "System.CLSCompliant", "CLSCompliant") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute6() As Task Dim code = <Code> ''' &lt;summary&gt;&lt;/summary&gt; Class $$C End Class </Code> Dim expected = <Code> &lt;Assembly: CLSCompliant(True)&gt; ''' &lt;summary&gt;&lt;/summary&gt; Class C End Class </Code> Await TestAddAttributeWithSimplificationAsync(code, expected, New AttributeData With {.Name = "System.CLSCompliant", .Value = "True"}, "System.CLSCompliant", "CLSCompliant") End Function #End Region #Region "AddClass tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass1() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> Public Class B End Class Class C End Class </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "B"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass2() As Task Dim code = <Code> Class $$C : End Class </Code> Dim expected = <Code> Public Class B End Class Class C : End Class </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "B"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass3() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> Class C End Class Public Class B End Class </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "B", .Position = "C"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass4() As Task Dim code = <Code> Class $$C : End Class </Code> Dim expected = <Code> Class C : End Class Public Class B End Class </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "B", .Position = "C"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass5() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> Class C End Class Public Class B Inherits C End Class </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "B", .Position = "C", .Bases = {"C"}}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass6() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> Class C End Class Public Class B Inherits C End Class </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "B", .Position = "C", .Bases = "C"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass7() As Task Dim code = <Code> Interface $$I End Interface </Code> Dim expected = <Code> Interface I End Interface Public Class C Inherits I End Class </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "C", .Position = "I", .Bases = {"I"}}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass8() As Task Dim code = <Code> Interface $$I End Interface </Code> Dim expected = <Code> Interface I End Interface Public Class C Inherits I End Class </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "C", .Position = "I", .Bases = "I"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass9() As Task Dim code = <Code> Class B : End Class Interface $$I : End Interface </Code> Dim expected = <Code> Class B : End Class Interface I : End Interface Public Class C Inherits B Implements I End Class </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "C", .Position = "I", .Bases = "B", .ImplementedInterfaces = "I"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass10() As Task Dim code = <Code> Class B : End Class Interface $$IGoo : End Interface Interface IBar : End Interface </Code> Dim expected = <Code> Class B : End Class Interface IGoo : End Interface Interface IBar : End Interface Public Class C Inherits B Implements IGoo, IBar End Class </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "C", .Position = "IBar", .Bases = "B", .ImplementedInterfaces = {"IGoo", "IBar"}}) End Function #End Region #Region "AddImport tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImport1() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> Imports System Class C End Class </Code> Await TestAddImport(code, expected, New ImportData With {.[Namespace] = "System"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImport2() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> Imports S = System Class C End Class </Code> Await TestAddImport(code, expected, New ImportData With {.[Namespace] = "System", .Alias = "S"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImport3() As Task Dim code = <Code> Imports System.Collections.Generic Class $$C End Class </Code> Dim expected = <Code> Imports System Imports System.Collections.Generic Class C End Class </Code> Await TestAddImport(code, expected, New ImportData With {.[Namespace] = "System"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImport4() As Task Dim code = <Code> Imports System.Collections.Generic Class $$C End Class </Code> Dim expected = <Code> Imports System.Collections.Generic Imports System Class C End Class </Code> Await TestAddImport(code, expected, New ImportData With {.[Namespace] = "System", .Position = -1}) End Function #End Region #Region "AddNamespace tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddNamespace1() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> Namespace N End Namespace Class C End Class </Code> Await TestAddNamespace(code, expected, New NamespaceData With {.Name = "N"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddNamespace2() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> Namespace N End Namespace Class C End Class </Code> Await TestAddNamespace(code, expected, New NamespaceData With {.Name = "N", .Position = 0}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddNamespace3() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> Class C End Class Namespace N End Namespace </Code> Await TestAddNamespace(code, expected, New NamespaceData With {.Name = "N", .Position = "C"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddNamespace4() As Task Dim code = <Code>$$</Code> Dim expected = <Code> Namespace N End Namespace </Code> Await TestAddNamespace(code, expected, New NamespaceData With {.Name = "N"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddNamespace5() As Task Dim code = <Code> $$Imports System </Code> Dim expected = <Code> Imports System Namespace N End Namespace </Code> Await TestAddNamespace(code, expected, New NamespaceData With {.Name = "N"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddNamespace6() As Task Dim code = <Code> $$Imports System </Code> Dim expected = <Code> Imports System Namespace N End Namespace </Code> Await TestAddNamespace(code, expected, New NamespaceData With {.Name = "N", .Position = 0}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddNamespace7() As Task Dim code = <Code> $$Imports System </Code> Dim expected = <Code> Imports System Namespace N End Namespace </Code> Await TestAddNamespace(code, expected, New NamespaceData With {.Name = "N", .Position = Type.Missing}) End Function #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestClass() Dim code = <Code> Class C End Class </Code> Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim codeElements = state.FileCodeModel.CodeElements Assert.Equal(1, codeElements.Count) Dim codeClass = TryCast(codeElements.Item(1), EnvDTE.CodeClass) Assert.NotNull(codeClass) Assert.Equal("C", codeClass.Name) Assert.Equal(1, codeClass.StartPoint.Line) Assert.Equal(1, codeClass.StartPoint.LineCharOffset) Assert.Equal(2, codeClass.EndPoint.Line) Assert.Equal(10, codeClass.EndPoint.LineCharOffset) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestClassWithTopLevelJunk() Dim code = <Code> Class C End Class A </Code> Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim codeElements = state.FileCodeModel.CodeElements Assert.Equal(1, codeElements.Count) Dim codeClass = TryCast(codeElements.Item(1), EnvDTE.CodeClass) Assert.NotNull(codeClass) Assert.Equal("C", codeClass.Name) Assert.Equal(1, codeClass.StartPoint.Line) Assert.Equal(1, codeClass.StartPoint.LineCharOffset) Assert.Equal(2, codeClass.EndPoint.Line) Assert.Equal(10, codeClass.EndPoint.LineCharOffset) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestClassNavigatePoints() Dim code = <Code> Class B End Class Class C Inherits B End Class </Code> Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim codeElements = state.FileCodeModel.CodeElements Assert.Equal(2, codeElements.Count) Dim codeClassB = TryCast(codeElements.Item(1), EnvDTE.CodeClass) Assert.NotNull(codeClassB) Assert.Equal("B", codeClassB.Name) Dim startPointB = codeClassB.GetStartPoint(EnvDTE.vsCMPart.vsCMPartNavigate) Assert.Equal(2, startPointB.Line) Assert.Equal(1, startPointB.LineCharOffset) Dim codeClassC = TryCast(codeElements.Item(2), EnvDTE.CodeClass) Assert.NotNull(codeClassC) Assert.Equal("C", codeClassC.Name) Dim startPointC = codeClassC.GetStartPoint(EnvDTE.vsCMPart.vsCMPartNavigate) Assert.Equal(6, startPointC.Line) Assert.Equal(5, startPointC.LineCharOffset) End Using End Sub <WorkItem(579801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579801")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOptionStatement() Dim code = <Code> Option Explicit On Class C End Class </Code> Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim codeElements = state.FileCodeModel.CodeElements Assert.Equal(2, codeElements.Count) Dim optionStatement = codeElements.Item(1) Assert.NotNull(optionStatement) Assert.Equal(EnvDTE.vsCMElement.vsCMElementOptionStmt, optionStatement.Kind) Dim codeClassC = TryCast(codeElements.Item(2), EnvDTE.CodeClass) Assert.NotNull(codeClassC) Assert.Equal("C", codeClassC.Name) End Using End Sub #Region "Remove tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemove1() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> </Code> Await TestRemoveChild(code, expected, "C") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemove2() As Task Dim code = <Code> ''' &lt;summary&gt; ''' ''' &lt;/summary&gt; Class $$C End Class </Code> Dim expected = <Code> </Code> Await TestRemoveChild(code, expected, "C") End Function #End Region <WpfFact> Public Sub TestOutsideEditsFormattedAfterEndBatch() Using state = CreateCodeModelTestState(GetWorkspaceDefinition(<File>Class C : End Class</File>)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) fileCodeModel.BeginBatch() ' Make an outside edit not through the CodeModel APIs Dim buffer = state.Workspace.Documents.Single().GetTextBuffer() buffer.Replace(New Text.Span(0, 1), "c") WpfTestRunner.RequireWpfFact($"Test requires {NameOf(EnvDTE80.FileCodeModel2)}.{NameOf(EnvDTE80.FileCodeModel2.EndBatch)}") fileCodeModel.EndBatch() Assert.Contains("Class C", buffer.CurrentSnapshot.GetText(), StringComparison.Ordinal) End Using End Sub <WorkItem(925569, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/925569")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub ChangeClassNameAndGetNameOfChildFunction() Dim code = <Code> Class C Sub M() End Sub End Class </Code> TestOperation(code, Sub(fileCodeModel) Dim codeClass = TryCast(fileCodeModel.CodeElements.Item(1), EnvDTE.CodeClass) Assert.NotNull(codeClass) Assert.Equal("C", codeClass.Name) Dim codeFunction = TryCast(codeClass.Members.Item(1), EnvDTE.CodeFunction) Assert.NotNull(codeFunction) Assert.Equal("M", codeFunction.Name) codeClass.Name = "NewClassName" Assert.Equal("NewClassName", codeClass.Name) Assert.Equal("M", codeFunction.Name) End Sub) End Sub <WorkItem(2355, "https://github.com/dotnet/roslyn/issues/2355")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function CreateUnknownElementForDeclarationFunctionAndSub() As Task Dim oldCode = <Code> Public Class Class1 Public Declare Sub f1 Lib "MyLib.dll" () Public Declare Function f2 Lib "MyLib.dll" () As Integer End Class </Code> Dim changedCodeRemoveFunction = <Code> Public Class Class1 Public Declare Sub f1 Lib "MyLib.dll" () End Class </Code> Dim changedCodeSubFunction = <Code> Public Class Class1 Public Declare Function f2 Lib "MyLib.dll" () As Integer End Class </Code> Dim changedDefinition = <Workspace> <Project Language=<%= LanguageName %> CommonReferences="true"> <Document FilePath="File1.vb"><%= changedCodeRemoveFunction.Value %></Document> <Document FilePath="File2.vb"><%= changedCodeSubFunction.Value %></Document> </Project> </Workspace> Using originalWorkspaceAndFileCodeModel = CreateCodeModelTestState(GetWorkspaceDefinition(oldCode)) Using changedworkspace = TestWorkspace.Create(changedDefinition, composition:=VisualStudioTestCompositions.LanguageServices) Dim originalDocument = originalWorkspaceAndFileCodeModel.Workspace.CurrentSolution.GetDocument(originalWorkspaceAndFileCodeModel.Workspace.Documents(0).Id) Dim originalTree = Await originalDocument.GetSyntaxTreeAsync() ' Assert Declaration Function Removal Dim changeDocument = changedworkspace.CurrentSolution.GetDocument(changedworkspace.Documents.First(Function(d) d.Name.Equals("File1.vb")).Id) Dim changeTree = Await changeDocument.GetSyntaxTreeAsync() Dim codeModelEvent = originalWorkspaceAndFileCodeModel.CodeModelService.CollectCodeModelEvents(originalTree, changeTree) Dim fileCodeModel = originalWorkspaceAndFileCodeModel.FileCodeModelObject Dim element As EnvDTE.CodeElement = Nothing Dim parentElement As Object = Nothing fileCodeModel.GetElementsForCodeModelEvent(codeModelEvent.First(), element, parentElement) Assert.NotNull(element) Assert.NotNull(parentElement) Dim unknownCodeFunction = TryCast(element, EnvDTE.CodeFunction) Assert.Equal(unknownCodeFunction.Name, "f2") ' Assert Declaration Sub Removal changeDocument = changedworkspace.CurrentSolution.GetDocument(changedworkspace.Documents.First(Function(d) d.Name.Equals("File2.vb")).Id) changeTree = Await changeDocument.GetSyntaxTreeAsync() codeModelEvent = originalWorkspaceAndFileCodeModel.CodeModelService.CollectCodeModelEvents(originalTree, changeTree) element = Nothing parentElement = Nothing fileCodeModel.GetElementsForCodeModelEvent(codeModelEvent.First(), element, parentElement) Assert.NotNull(element) Assert.NotNull(parentElement) unknownCodeFunction = TryCast(element, EnvDTE.CodeFunction) Assert.Equal(unknownCodeFunction.Name, "f1") End Using End Using End Function <WorkItem(858153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858153")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestCodeElements_InheritsStatements() Dim code = <code> Class A End Class Class C Inherits A End Class </code> TestOperation(code, Sub(fileCodeModel) Dim classC = TryCast(fileCodeModel.CodeElements.Item(2), EnvDTE.CodeClass) Assert.NotNull(classC) Assert.Equal("C", classC.Name) Dim inheritsA = TryCast(classC.Children.Item(1), EnvDTE80.CodeElement2) Assert.NotNull(inheritsA) Dim parent = TryCast(inheritsA.Collection.Parent, EnvDTE.CodeClass) Assert.NotNull(parent) Assert.Equal("C", parent.Name) ' This assert is very important! ' ' We are testing that we don't regress a bug where the VB Inherits statement creates its ' parent incorrectly such that *existing* Code Model objects for its parent ("C") get a different ' NodeKey that makes the existing objects invalid. If the bug regresses, the line below will ' fail with an ArguementException when trying to use classC's NodeKey to lookup its node. ' (Essentially, its NodeKey will be {C,2} rather than {C,1}). Assert.Equal("C", classC.Name) ' Sanity: ensure that the NodeKeys are correct Dim member1 = ComAggregate.GetManagedObject(Of AbstractCodeMember)(parent) Dim member2 = ComAggregate.GetManagedObject(Of AbstractCodeMember)(classC) Assert.Equal("C", member1.NodeKey.Name) Assert.Equal(1, member1.NodeKey.Ordinal) Assert.Equal("C", member2.NodeKey.Name) Assert.Equal(1, member2.NodeKey.Ordinal) End Sub) End Sub <WorkItem(858153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858153")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestCodeElements_ImplementsStatements() Dim code = <code> Interface I End Interface Class C Implements I End Class </code> TestOperation(code, Sub(fileCodeModel) Dim classC = TryCast(fileCodeModel.CodeElements.Item(2), EnvDTE.CodeClass) Assert.NotNull(classC) Assert.Equal("C", classC.Name) Dim implementsI = TryCast(classC.Children.Item(1), EnvDTE80.CodeElement2) Assert.NotNull(implementsI) Dim parent = TryCast(implementsI.Collection.Parent, EnvDTE.CodeClass) Assert.NotNull(parent) Assert.Equal("C", parent.Name) ' This assert is very important! ' ' We are testing that we don't regress a bug where the VB Implements statement creates its ' parent incorrectly such that *existing* Code Model objects for its parent ("C") get a different ' NodeKey that makes the existing objects invalid. If the bug regresses, the line below will ' fail with an ArguementException when trying to use classC's NodeKey to lookup its node. ' (Essentially, its NodeKey will be {C,2} rather than {C,1}). Assert.Equal("C", classC.Name) ' Sanity: ensure that the NodeKeys are correct Dim member1 = ComAggregate.GetManagedObject(Of AbstractCodeMember)(parent) Dim member2 = ComAggregate.GetManagedObject(Of AbstractCodeMember)(classC) Assert.Equal("C", member1.NodeKey.Name) Assert.Equal(1, member1.NodeKey.Ordinal) Assert.Equal("C", member2.NodeKey.Name) Assert.Equal(1, member2.NodeKey.Ordinal) End Sub) End Sub <WorkItem(858153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858153")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestCodeElements_PropertyAccessor() Dim code = <code> Class C ReadOnly Property P As Integer Get End Get End Property End Class </code> TestOperation(code, Sub(fileCodeModel) Dim classC = TryCast(fileCodeModel.CodeElements.Item(1), EnvDTE.CodeClass) Assert.NotNull(classC) Assert.Equal("C", classC.Name) Dim propertyP = TryCast(classC.Members.Item(1), EnvDTE.CodeProperty) Assert.NotNull(propertyP) Assert.Equal("P", propertyP.Name) Dim getter = propertyP.Getter Assert.NotNull(getter) Dim searchedGetter = fileCodeModel.CodeElementFromPoint(getter.StartPoint, EnvDTE.vsCMElement.vsCMElementFunction) Dim parent = TryCast(getter.Collection.Parent, EnvDTE.CodeProperty) Assert.NotNull(parent) Assert.Equal("P", parent.Name) ' This assert is very important! ' ' We are testing that we don't regress a bug where a property accessor creates its ' parent incorrectly such that *existing* Code Model objects for its parent ("P") get a different ' NodeKey that makes the existing objects invalid. If the bug regresses, the line below will ' fail with an ArguementException when trying to use propertyP's NodeKey to lookup its node. ' (Essentially, its NodeKey will be {C.P As Integer,2} rather than {C.P As Integer,1}). Assert.Equal("P", propertyP.Name) ' Sanity: ensure that the NodeKeys are correct Dim member1 = ComAggregate.GetManagedObject(Of AbstractCodeMember)(parent) Dim member2 = ComAggregate.GetManagedObject(Of AbstractCodeMember)(propertyP) Assert.Equal("C.P As Integer", member1.NodeKey.Name) Assert.Equal(1, member1.NodeKey.Ordinal) Assert.Equal("C.P As Integer", member2.NodeKey.Name) Assert.Equal(1, member2.NodeKey.Ordinal) End Sub) End Sub <WorkItem(858153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858153")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestCodeElements_EventAccessor() Dim code = <code> Class C Custom Event E As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event End Class </code> TestOperation(code, Sub(fileCodeModel) Dim classC = TryCast(fileCodeModel.CodeElements.Item(1), EnvDTE.CodeClass) Assert.NotNull(classC) Assert.Equal("C", classC.Name) Dim eventE = TryCast(classC.Members.Item(1), EnvDTE80.CodeEvent) Assert.NotNull(eventE) Assert.Equal("E", eventE.Name) Dim adder = eventE.Adder Assert.NotNull(adder) Dim searchedAdder = fileCodeModel.CodeElementFromPoint(adder.StartPoint, EnvDTE.vsCMElement.vsCMElementFunction) Dim parent = TryCast(adder.Collection.Parent, EnvDTE80.CodeEvent) Assert.NotNull(parent) Assert.Equal("E", parent.Name) ' This assert is very important! ' ' We are testing that we don't regress a bug where an event accessor creates its ' parent incorrectly such that *existing* Code Model objects for its parent ("E") get a different ' NodeKey that makes the existing objects invalid. If the bug regresses, the line below will ' fail with an ArguementException when trying to use propertyP's NodeKey to lookup its node. ' (Essentially, its NodeKey will be {C.E As System.EventHandler,2} rather than {C.E As System.EventHandler,1}). Assert.Equal("E", eventE.Name) ' Sanity: ensure that the NodeKeys are correct Dim member1 = ComAggregate.GetManagedObject(Of AbstractCodeMember)(parent) Dim member2 = ComAggregate.GetManagedObject(Of AbstractCodeMember)(eventE) Assert.Equal("C.E As System.EventHandler", member1.NodeKey.Name) Assert.Equal(1, member1.NodeKey.Ordinal) Assert.Equal("C.E As System.EventHandler", member2.NodeKey.Name) Assert.Equal(1, member2.NodeKey.Ordinal) End Sub) End Sub <WorkItem(31735, "https://github.com/dotnet/roslyn/issues/31735")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub RenameShouldWorkAndElementsShouldBeUsableAfter() Dim code = <code> Class C End Class </code> TestOperation(code, Sub(fileCodeModel) Dim codeElement = DirectCast(fileCodeModel.CodeElements(0), EnvDTE80.CodeElement2) Assert.Equal("C", codeElement.Name) codeElement.RenameSymbol("D") ' This not only asserts that the rename happened successfully, but that the element was correctly updated ' so the underlying node key is still valid. Assert.Equal("D", codeElement.Name) End Sub) End Sub Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.VisualBasic End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements Imports Microsoft.VisualStudio.LanguageServices.Implementation.Interop Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Public Class VisualBasicFileCodeModelTests Inherits AbstractFileCodeModelTests <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestEnumerationWithCountAndItem() Dim code = <Code> Namespace N End Namespace Class C End Class Interface I End Interface Structure S End Structure Enum E Goo End Enum Delegate Sub D() </Code> Using workspaceAndFileCodeModel = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim codeElements = workspaceAndFileCodeModel.FileCodeModel.CodeElements Dim count = codeElements.Count Assert.Equal(6, count) Dim expectedKinds = {EnvDTE.vsCMElement.vsCMElementNamespace, EnvDTE.vsCMElement.vsCMElementClass, EnvDTE.vsCMElement.vsCMElementInterface, EnvDTE.vsCMElement.vsCMElementStruct, EnvDTE.vsCMElement.vsCMElementEnum, EnvDTE.vsCMElement.vsCMElementDelegate} Dim expectedNames = {"N", "C", "I", "S", "E", "D"} For i = 0 To count - 1 Dim element = codeElements.Item(i + 1) Assert.Equal(expectedKinds(i), element.Kind) Assert.Equal(expectedNames(i), element.Name) Next Dim j As Integer For Each element As EnvDTE.CodeElement In codeElements Assert.Equal(expectedKinds(j), element.Kind) Assert.Equal(expectedNames(j), element.Name) j += 1 Next End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAssemblyLevelAttribute() Dim code = <Code> &lt;Assembly: Goo(0, True, S:="x")&gt; Class GooAttribute Inherits System.Attribute Public Sub New(i As Integer, b As Boolean) End Sub Public Property S() As String Get Return String.Empty End Get Set(ByVal value As String) End Set End Property End Class </Code> Using workspaceAndFileCodeModel = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim codeElements = workspaceAndFileCodeModel.FileCodeModel.CodeElements Dim count = codeElements.Count Assert.Equal(2, count) Dim codeAttribute = TryCast(codeElements.Item(1), EnvDTE80.CodeAttribute2) Assert.NotNull(codeAttribute) Assert.Same(workspaceAndFileCodeModel.FileCodeModel, codeAttribute.Parent) Assert.Equal("Goo", codeAttribute.Name) Assert.Equal("GooAttribute", codeAttribute.FullName) Assert.Equal("Assembly", codeAttribute.Target) Assert.Equal("0, True, S:=""x""", codeAttribute.Value) Dim arguments = codeAttribute.Arguments Assert.Equal(3, arguments.Count) Dim arg1 = TryCast(arguments.Item(1), EnvDTE80.CodeAttributeArgument) Assert.NotNull(arg1) Assert.Equal("", arg1.Name) Assert.Equal("0", arg1.Value) Dim arg2 = TryCast(arguments.Item(2), EnvDTE80.CodeAttributeArgument) Assert.NotNull(arg2) Assert.Equal("", arg2.Name) Assert.Equal("True", arg2.Value) Dim arg3 = TryCast(arguments.Item(3), EnvDTE80.CodeAttributeArgument) Assert.NotNull(arg3) Assert.Equal("S", arg3.Name) Assert.Equal("""x""", arg3.Value) End Using End Sub <WorkItem(1111417, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1111417")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestCodeElementFullName() Dim code = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Namespace Outer Public Class Class1 Public Property Prop1 As Integer Public var1 As Class3 Public Event event1() Public Function func1() As Integer Return 1 End Function Public Class Class3 End Class End Class End Namespace</Document> </Project> </Workspace> Using workspaceAndFileCodeModel = CreateCodeModelTestState(code) Dim codeElements = workspaceAndFileCodeModel.FileCodeModel.CodeElements Dim namespaceElement = TryCast(codeElements.Item(1), EnvDTE.CodeNamespace) Assert.NotNull(namespaceElement) Assert.Same(workspaceAndFileCodeModel.FileCodeModel, namespaceElement.Parent) Assert.Equal("Outer", namespaceElement.Name) Assert.Equal("BarBaz.Outer", namespaceElement.FullName) Dim codeClass = TryCast(namespaceElement.Members.Item(1), EnvDTE.CodeClass) Assert.NotNull(codeClass) Assert.Equal("Class1", codeClass.Name) Assert.Equal("BarBaz.Outer.Class1", codeClass.FullName) Dim classMembers = codeClass.Members Dim prop = TryCast(classMembers.Item(1), EnvDTE.CodeProperty) Assert.NotNull(prop) Assert.Equal("Prop1", prop.Name) Assert.Equal("BarBaz.Outer.Class1.Prop1", prop.FullName) Dim variable = TryCast(classMembers.Item(2), EnvDTE.CodeVariable) Assert.NotNull(variable) Assert.Equal("var1", variable.Name) Assert.Equal("BarBaz.Outer.Class1.var1", variable.FullName) Assert.Equal("BarBaz.Outer.Class1.Class3", variable.Type.AsFullName) Dim event1 = TryCast(classMembers.Item(3), EnvDTE80.CodeEvent) Assert.NotNull(event1) Assert.Equal("event1", event1.Name) Assert.Equal("BarBaz.Outer.Class1.event1", event1.FullName) Dim func1 = TryCast(classMembers.Item(4), EnvDTE.CodeFunction) Assert.NotNull(func1) Assert.Equal("func1", func1.Name) Assert.Equal("BarBaz.Outer.Class1.func1", func1.FullName) End Using End Sub <WorkItem(150349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/150349")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub NoChildrenForInvalidMembers() Dim code = <Code> Sub M() End Sub Function M() As Integer End Function Property P As Integer Event E() Class C End Class </Code> TestChildren(code, IsElement("C")) End Sub #Region "AddAttribute tests" Private Function TestAddAttributeWithSimplificationAsync( code As XElement, expectedCode As XElement, data As AttributeData, expectedUnsimplifiedName As String, expectedSimplifiedName As String) As Task Return TestAddAttributeWithSimplificationAsync(code, expectedCode, Sub(fileCodeModel, batch) Dim newAttribute = fileCodeModel.AddAttribute(data.Name, data.Value, data.Position) Assert.NotNull(newAttribute) Assert.Equal(If(batch, expectedUnsimplifiedName, expectedSimplifiedName), newAttribute.Name) End Sub) End Function Protected Async Function TestAddAttributeWithSimplificationAsync(code As XElement, expectedCode As XElement, testOperation As Action(Of EnvDTE.FileCodeModel, Boolean)) As Task Await TestAddAttributeWithBatchModeAsync(code, expectedCode, testOperation, False) Await TestAddAttributeWithBatchModeAsync(code, expectedCode, testOperation, True) End Function Private Async Function TestAddAttributeWithBatchModeAsync(code As XElement, expectedCode As XElement, testOperation As Action(Of EnvDTE.FileCodeModel, Boolean), batch As Boolean) As Task WpfTestRunner.RequireWpfFact($"Test calls {NameOf(Me.TestAddAttributeWithBatchModeAsync)} which means we're creating new {NameOf(EnvDTE.CodeModel)} elements.") ' NOTE: this method is the same as MyBase.TestOperation, but tells the lambda whether we are batching or not. ' This is because the tests have different behavior up until EndBatch is called. Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) If batch Then fileCodeModel.BeginBatch() End If testOperation(fileCodeModel, batch) If batch Then fileCodeModel.EndBatch() End If Dim text = (Await state.GetDocumentAtCursor().GetTextAsync()).ToString() Assert.Equal(expectedCode.NormalizedValue.Trim(), text.Trim()) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute1() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> &lt;Assembly: CLSCompliant(True)&gt; Class C End Class </Code> Await TestAddAttributeWithSimplificationAsync(code, expected, New AttributeData With {.Name = "System.CLSCompliant", .Value = "True"}, "System.CLSCompliant", "CLSCompliant") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute2() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> &lt;Assembly: CLSCompliant(True)&gt; Class C End Class </Code> Await TestAddAttributeWithSimplificationAsync(code, expected, New AttributeData With {.Name = "System.CLSCompliant", .Value = "True", .Position = "C"}, "System.CLSCompliant", "CLSCompliant") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute3() As Task Dim code = <Code> $$&lt;Assembly: System.Reflection.AssemblyCompany("Microsoft")&gt; </Code> Dim expected = <Code> &lt;Assembly: System.Reflection.AssemblyCompany("Microsoft")&gt; &lt;Assembly: CLSCompliant(True)&gt; </Code> Await TestAddAttributeWithSimplificationAsync(code, expected, New AttributeData With {.Name = "System.CLSCompliant", .Value = "True", .Position = -1}, "System.CLSCompliant", "CLSCompliant") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute4() As Task Dim code = <Code> $$&lt;Assembly: System.Reflection.AssemblyCompany("Microsoft")&gt; Class C End Class </Code> Dim expected = <Code> &lt;Assembly: System.Reflection.AssemblyCompany("Microsoft")&gt; &lt;Assembly: CLSCompliant(True)&gt; Class C End Class </Code> Await TestAddAttributeWithSimplificationAsync(code, expected, New AttributeData With {.Name = "System.CLSCompliant", .Value = "True", .Position = -1}, "System.CLSCompliant", "CLSCompliant") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute5() As Task Dim code = <Code> $$&lt;Assembly: System.Reflection.AssemblyCompany("Microsoft")&gt; &lt;Assembly: System.Reflection.AssemblyCopyright("2012")&gt; Class C End Class </Code> Dim expected = <Code> &lt;Assembly: System.Reflection.AssemblyCompany("Microsoft")&gt; &lt;Assembly: System.Reflection.AssemblyCopyright("2012")&gt; &lt;Assembly: CLSCompliant(True)&gt; Class C End Class</Code> Await TestAddAttributeWithSimplificationAsync(code, expected, New AttributeData With {.Name = "System.CLSCompliant", .Value = "True", .Position = -1}, "System.CLSCompliant", "CLSCompliant") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute6() As Task Dim code = <Code> ''' &lt;summary&gt;&lt;/summary&gt; Class $$C End Class </Code> Dim expected = <Code> &lt;Assembly: CLSCompliant(True)&gt; ''' &lt;summary&gt;&lt;/summary&gt; Class C End Class </Code> Await TestAddAttributeWithSimplificationAsync(code, expected, New AttributeData With {.Name = "System.CLSCompliant", .Value = "True"}, "System.CLSCompliant", "CLSCompliant") End Function #End Region #Region "AddClass tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass1() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> Public Class B End Class Class C End Class </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "B"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass2() As Task Dim code = <Code> Class $$C : End Class </Code> Dim expected = <Code> Public Class B End Class Class C : End Class </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "B"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass3() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> Class C End Class Public Class B End Class </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "B", .Position = "C"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass4() As Task Dim code = <Code> Class $$C : End Class </Code> Dim expected = <Code> Class C : End Class Public Class B End Class </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "B", .Position = "C"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass5() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> Class C End Class Public Class B Inherits C End Class </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "B", .Position = "C", .Bases = {"C"}}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass6() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> Class C End Class Public Class B Inherits C End Class </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "B", .Position = "C", .Bases = "C"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass7() As Task Dim code = <Code> Interface $$I End Interface </Code> Dim expected = <Code> Interface I End Interface Public Class C Inherits I End Class </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "C", .Position = "I", .Bases = {"I"}}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass8() As Task Dim code = <Code> Interface $$I End Interface </Code> Dim expected = <Code> Interface I End Interface Public Class C Inherits I End Class </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "C", .Position = "I", .Bases = "I"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass9() As Task Dim code = <Code> Class B : End Class Interface $$I : End Interface </Code> Dim expected = <Code> Class B : End Class Interface I : End Interface Public Class C Inherits B Implements I End Class </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "C", .Position = "I", .Bases = "B", .ImplementedInterfaces = "I"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddClass10() As Task Dim code = <Code> Class B : End Class Interface $$IGoo : End Interface Interface IBar : End Interface </Code> Dim expected = <Code> Class B : End Class Interface IGoo : End Interface Interface IBar : End Interface Public Class C Inherits B Implements IGoo, IBar End Class </Code> Await TestAddClass(code, expected, New ClassData With {.Name = "C", .Position = "IBar", .Bases = "B", .ImplementedInterfaces = {"IGoo", "IBar"}}) End Function #End Region #Region "AddImport tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImport1() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> Imports System Class C End Class </Code> Await TestAddImport(code, expected, New ImportData With {.[Namespace] = "System"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImport2() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> Imports S = System Class C End Class </Code> Await TestAddImport(code, expected, New ImportData With {.[Namespace] = "System", .Alias = "S"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImport3() As Task Dim code = <Code> Imports System.Collections.Generic Class $$C End Class </Code> Dim expected = <Code> Imports System Imports System.Collections.Generic Class C End Class </Code> Await TestAddImport(code, expected, New ImportData With {.[Namespace] = "System"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddImport4() As Task Dim code = <Code> Imports System.Collections.Generic Class $$C End Class </Code> Dim expected = <Code> Imports System.Collections.Generic Imports System Class C End Class </Code> Await TestAddImport(code, expected, New ImportData With {.[Namespace] = "System", .Position = -1}) End Function #End Region #Region "AddNamespace tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddNamespace1() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> Namespace N End Namespace Class C End Class </Code> Await TestAddNamespace(code, expected, New NamespaceData With {.Name = "N"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddNamespace2() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> Namespace N End Namespace Class C End Class </Code> Await TestAddNamespace(code, expected, New NamespaceData With {.Name = "N", .Position = 0}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddNamespace3() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> Class C End Class Namespace N End Namespace </Code> Await TestAddNamespace(code, expected, New NamespaceData With {.Name = "N", .Position = "C"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddNamespace4() As Task Dim code = <Code>$$</Code> Dim expected = <Code> Namespace N End Namespace </Code> Await TestAddNamespace(code, expected, New NamespaceData With {.Name = "N"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddNamespace5() As Task Dim code = <Code> $$Imports System </Code> Dim expected = <Code> Imports System Namespace N End Namespace </Code> Await TestAddNamespace(code, expected, New NamespaceData With {.Name = "N"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddNamespace6() As Task Dim code = <Code> $$Imports System </Code> Dim expected = <Code> Imports System Namespace N End Namespace </Code> Await TestAddNamespace(code, expected, New NamespaceData With {.Name = "N", .Position = 0}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddNamespace7() As Task Dim code = <Code> $$Imports System </Code> Dim expected = <Code> Imports System Namespace N End Namespace </Code> Await TestAddNamespace(code, expected, New NamespaceData With {.Name = "N", .Position = Type.Missing}) End Function #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestClass() Dim code = <Code> Class C End Class </Code> Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim codeElements = state.FileCodeModel.CodeElements Assert.Equal(1, codeElements.Count) Dim codeClass = TryCast(codeElements.Item(1), EnvDTE.CodeClass) Assert.NotNull(codeClass) Assert.Equal("C", codeClass.Name) Assert.Equal(1, codeClass.StartPoint.Line) Assert.Equal(1, codeClass.StartPoint.LineCharOffset) Assert.Equal(2, codeClass.EndPoint.Line) Assert.Equal(10, codeClass.EndPoint.LineCharOffset) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestClassWithTopLevelJunk() Dim code = <Code> Class C End Class A </Code> Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim codeElements = state.FileCodeModel.CodeElements Assert.Equal(1, codeElements.Count) Dim codeClass = TryCast(codeElements.Item(1), EnvDTE.CodeClass) Assert.NotNull(codeClass) Assert.Equal("C", codeClass.Name) Assert.Equal(1, codeClass.StartPoint.Line) Assert.Equal(1, codeClass.StartPoint.LineCharOffset) Assert.Equal(2, codeClass.EndPoint.Line) Assert.Equal(10, codeClass.EndPoint.LineCharOffset) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestClassNavigatePoints() Dim code = <Code> Class B End Class Class C Inherits B End Class </Code> Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim codeElements = state.FileCodeModel.CodeElements Assert.Equal(2, codeElements.Count) Dim codeClassB = TryCast(codeElements.Item(1), EnvDTE.CodeClass) Assert.NotNull(codeClassB) Assert.Equal("B", codeClassB.Name) Dim startPointB = codeClassB.GetStartPoint(EnvDTE.vsCMPart.vsCMPartNavigate) Assert.Equal(2, startPointB.Line) Assert.Equal(1, startPointB.LineCharOffset) Dim codeClassC = TryCast(codeElements.Item(2), EnvDTE.CodeClass) Assert.NotNull(codeClassC) Assert.Equal("C", codeClassC.Name) Dim startPointC = codeClassC.GetStartPoint(EnvDTE.vsCMPart.vsCMPartNavigate) Assert.Equal(6, startPointC.Line) Assert.Equal(5, startPointC.LineCharOffset) End Using End Sub <WorkItem(579801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579801")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOptionStatement() Dim code = <Code> Option Explicit On Class C End Class </Code> Using state = CreateCodeModelTestState(GetWorkspaceDefinition(code)) Dim codeElements = state.FileCodeModel.CodeElements Assert.Equal(2, codeElements.Count) Dim optionStatement = codeElements.Item(1) Assert.NotNull(optionStatement) Assert.Equal(EnvDTE.vsCMElement.vsCMElementOptionStmt, optionStatement.Kind) Dim codeClassC = TryCast(codeElements.Item(2), EnvDTE.CodeClass) Assert.NotNull(codeClassC) Assert.Equal("C", codeClassC.Name) End Using End Sub #Region "Remove tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemove1() As Task Dim code = <Code> Class $$C End Class </Code> Dim expected = <Code> </Code> Await TestRemoveChild(code, expected, "C") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestRemove2() As Task Dim code = <Code> ''' &lt;summary&gt; ''' ''' &lt;/summary&gt; Class $$C End Class </Code> Dim expected = <Code> </Code> Await TestRemoveChild(code, expected, "C") End Function #End Region <WpfFact> Public Sub TestOutsideEditsFormattedAfterEndBatch() Using state = CreateCodeModelTestState(GetWorkspaceDefinition(<File>Class C : End Class</File>)) Dim fileCodeModel = state.FileCodeModel Assert.NotNull(fileCodeModel) fileCodeModel.BeginBatch() ' Make an outside edit not through the CodeModel APIs Dim buffer = state.Workspace.Documents.Single().GetTextBuffer() buffer.Replace(New Text.Span(0, 1), "c") WpfTestRunner.RequireWpfFact($"Test requires {NameOf(EnvDTE80.FileCodeModel2)}.{NameOf(EnvDTE80.FileCodeModel2.EndBatch)}") fileCodeModel.EndBatch() Assert.Contains("Class C", buffer.CurrentSnapshot.GetText(), StringComparison.Ordinal) End Using End Sub <WorkItem(925569, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/925569")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub ChangeClassNameAndGetNameOfChildFunction() Dim code = <Code> Class C Sub M() End Sub End Class </Code> TestOperation(code, Sub(fileCodeModel) Dim codeClass = TryCast(fileCodeModel.CodeElements.Item(1), EnvDTE.CodeClass) Assert.NotNull(codeClass) Assert.Equal("C", codeClass.Name) Dim codeFunction = TryCast(codeClass.Members.Item(1), EnvDTE.CodeFunction) Assert.NotNull(codeFunction) Assert.Equal("M", codeFunction.Name) codeClass.Name = "NewClassName" Assert.Equal("NewClassName", codeClass.Name) Assert.Equal("M", codeFunction.Name) End Sub) End Sub <WorkItem(2355, "https://github.com/dotnet/roslyn/issues/2355")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function CreateUnknownElementForDeclarationFunctionAndSub() As Task Dim oldCode = <Code> Public Class Class1 Public Declare Sub f1 Lib "MyLib.dll" () Public Declare Function f2 Lib "MyLib.dll" () As Integer End Class </Code> Dim changedCodeRemoveFunction = <Code> Public Class Class1 Public Declare Sub f1 Lib "MyLib.dll" () End Class </Code> Dim changedCodeSubFunction = <Code> Public Class Class1 Public Declare Function f2 Lib "MyLib.dll" () As Integer End Class </Code> Dim changedDefinition = <Workspace> <Project Language=<%= LanguageName %> CommonReferences="true"> <Document FilePath="File1.vb"><%= changedCodeRemoveFunction.Value %></Document> <Document FilePath="File2.vb"><%= changedCodeSubFunction.Value %></Document> </Project> </Workspace> Using originalWorkspaceAndFileCodeModel = CreateCodeModelTestState(GetWorkspaceDefinition(oldCode)) Using changedworkspace = TestWorkspace.Create(changedDefinition, composition:=VisualStudioTestCompositions.LanguageServices) Dim originalDocument = originalWorkspaceAndFileCodeModel.Workspace.CurrentSolution.GetDocument(originalWorkspaceAndFileCodeModel.Workspace.Documents(0).Id) Dim originalTree = Await originalDocument.GetSyntaxTreeAsync() ' Assert Declaration Function Removal Dim changeDocument = changedworkspace.CurrentSolution.GetDocument(changedworkspace.Documents.First(Function(d) d.Name.Equals("File1.vb")).Id) Dim changeTree = Await changeDocument.GetSyntaxTreeAsync() Dim codeModelEvent = originalWorkspaceAndFileCodeModel.CodeModelService.CollectCodeModelEvents(originalTree, changeTree) Dim fileCodeModel = originalWorkspaceAndFileCodeModel.FileCodeModelObject Dim element As EnvDTE.CodeElement = Nothing Dim parentElement As Object = Nothing fileCodeModel.GetElementsForCodeModelEvent(codeModelEvent.First(), element, parentElement) Assert.NotNull(element) Assert.NotNull(parentElement) Dim unknownCodeFunction = TryCast(element, EnvDTE.CodeFunction) Assert.Equal(unknownCodeFunction.Name, "f2") ' Assert Declaration Sub Removal changeDocument = changedworkspace.CurrentSolution.GetDocument(changedworkspace.Documents.First(Function(d) d.Name.Equals("File2.vb")).Id) changeTree = Await changeDocument.GetSyntaxTreeAsync() codeModelEvent = originalWorkspaceAndFileCodeModel.CodeModelService.CollectCodeModelEvents(originalTree, changeTree) element = Nothing parentElement = Nothing fileCodeModel.GetElementsForCodeModelEvent(codeModelEvent.First(), element, parentElement) Assert.NotNull(element) Assert.NotNull(parentElement) unknownCodeFunction = TryCast(element, EnvDTE.CodeFunction) Assert.Equal(unknownCodeFunction.Name, "f1") End Using End Using End Function <WorkItem(858153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858153")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestCodeElements_InheritsStatements() Dim code = <code> Class A End Class Class C Inherits A End Class </code> TestOperation(code, Sub(fileCodeModel) Dim classC = TryCast(fileCodeModel.CodeElements.Item(2), EnvDTE.CodeClass) Assert.NotNull(classC) Assert.Equal("C", classC.Name) Dim inheritsA = TryCast(classC.Children.Item(1), EnvDTE80.CodeElement2) Assert.NotNull(inheritsA) Dim parent = TryCast(inheritsA.Collection.Parent, EnvDTE.CodeClass) Assert.NotNull(parent) Assert.Equal("C", parent.Name) ' This assert is very important! ' ' We are testing that we don't regress a bug where the VB Inherits statement creates its ' parent incorrectly such that *existing* Code Model objects for its parent ("C") get a different ' NodeKey that makes the existing objects invalid. If the bug regresses, the line below will ' fail with an ArguementException when trying to use classC's NodeKey to lookup its node. ' (Essentially, its NodeKey will be {C,2} rather than {C,1}). Assert.Equal("C", classC.Name) ' Sanity: ensure that the NodeKeys are correct Dim member1 = ComAggregate.GetManagedObject(Of AbstractCodeMember)(parent) Dim member2 = ComAggregate.GetManagedObject(Of AbstractCodeMember)(classC) Assert.Equal("C", member1.NodeKey.Name) Assert.Equal(1, member1.NodeKey.Ordinal) Assert.Equal("C", member2.NodeKey.Name) Assert.Equal(1, member2.NodeKey.Ordinal) End Sub) End Sub <WorkItem(858153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858153")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestCodeElements_ImplementsStatements() Dim code = <code> Interface I End Interface Class C Implements I End Class </code> TestOperation(code, Sub(fileCodeModel) Dim classC = TryCast(fileCodeModel.CodeElements.Item(2), EnvDTE.CodeClass) Assert.NotNull(classC) Assert.Equal("C", classC.Name) Dim implementsI = TryCast(classC.Children.Item(1), EnvDTE80.CodeElement2) Assert.NotNull(implementsI) Dim parent = TryCast(implementsI.Collection.Parent, EnvDTE.CodeClass) Assert.NotNull(parent) Assert.Equal("C", parent.Name) ' This assert is very important! ' ' We are testing that we don't regress a bug where the VB Implements statement creates its ' parent incorrectly such that *existing* Code Model objects for its parent ("C") get a different ' NodeKey that makes the existing objects invalid. If the bug regresses, the line below will ' fail with an ArguementException when trying to use classC's NodeKey to lookup its node. ' (Essentially, its NodeKey will be {C,2} rather than {C,1}). Assert.Equal("C", classC.Name) ' Sanity: ensure that the NodeKeys are correct Dim member1 = ComAggregate.GetManagedObject(Of AbstractCodeMember)(parent) Dim member2 = ComAggregate.GetManagedObject(Of AbstractCodeMember)(classC) Assert.Equal("C", member1.NodeKey.Name) Assert.Equal(1, member1.NodeKey.Ordinal) Assert.Equal("C", member2.NodeKey.Name) Assert.Equal(1, member2.NodeKey.Ordinal) End Sub) End Sub <WorkItem(858153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858153")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestCodeElements_PropertyAccessor() Dim code = <code> Class C ReadOnly Property P As Integer Get End Get End Property End Class </code> TestOperation(code, Sub(fileCodeModel) Dim classC = TryCast(fileCodeModel.CodeElements.Item(1), EnvDTE.CodeClass) Assert.NotNull(classC) Assert.Equal("C", classC.Name) Dim propertyP = TryCast(classC.Members.Item(1), EnvDTE.CodeProperty) Assert.NotNull(propertyP) Assert.Equal("P", propertyP.Name) Dim getter = propertyP.Getter Assert.NotNull(getter) Dim searchedGetter = fileCodeModel.CodeElementFromPoint(getter.StartPoint, EnvDTE.vsCMElement.vsCMElementFunction) Dim parent = TryCast(getter.Collection.Parent, EnvDTE.CodeProperty) Assert.NotNull(parent) Assert.Equal("P", parent.Name) ' This assert is very important! ' ' We are testing that we don't regress a bug where a property accessor creates its ' parent incorrectly such that *existing* Code Model objects for its parent ("P") get a different ' NodeKey that makes the existing objects invalid. If the bug regresses, the line below will ' fail with an ArguementException when trying to use propertyP's NodeKey to lookup its node. ' (Essentially, its NodeKey will be {C.P As Integer,2} rather than {C.P As Integer,1}). Assert.Equal("P", propertyP.Name) ' Sanity: ensure that the NodeKeys are correct Dim member1 = ComAggregate.GetManagedObject(Of AbstractCodeMember)(parent) Dim member2 = ComAggregate.GetManagedObject(Of AbstractCodeMember)(propertyP) Assert.Equal("C.P As Integer", member1.NodeKey.Name) Assert.Equal(1, member1.NodeKey.Ordinal) Assert.Equal("C.P As Integer", member2.NodeKey.Name) Assert.Equal(1, member2.NodeKey.Ordinal) End Sub) End Sub <WorkItem(858153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858153")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestCodeElements_EventAccessor() Dim code = <code> Class C Custom Event E As System.EventHandler AddHandler(value As System.EventHandler) End AddHandler RemoveHandler(value As System.EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As System.EventArgs) End RaiseEvent End Event End Class </code> TestOperation(code, Sub(fileCodeModel) Dim classC = TryCast(fileCodeModel.CodeElements.Item(1), EnvDTE.CodeClass) Assert.NotNull(classC) Assert.Equal("C", classC.Name) Dim eventE = TryCast(classC.Members.Item(1), EnvDTE80.CodeEvent) Assert.NotNull(eventE) Assert.Equal("E", eventE.Name) Dim adder = eventE.Adder Assert.NotNull(adder) Dim searchedAdder = fileCodeModel.CodeElementFromPoint(adder.StartPoint, EnvDTE.vsCMElement.vsCMElementFunction) Dim parent = TryCast(adder.Collection.Parent, EnvDTE80.CodeEvent) Assert.NotNull(parent) Assert.Equal("E", parent.Name) ' This assert is very important! ' ' We are testing that we don't regress a bug where an event accessor creates its ' parent incorrectly such that *existing* Code Model objects for its parent ("E") get a different ' NodeKey that makes the existing objects invalid. If the bug regresses, the line below will ' fail with an ArguementException when trying to use propertyP's NodeKey to lookup its node. ' (Essentially, its NodeKey will be {C.E As System.EventHandler,2} rather than {C.E As System.EventHandler,1}). Assert.Equal("E", eventE.Name) ' Sanity: ensure that the NodeKeys are correct Dim member1 = ComAggregate.GetManagedObject(Of AbstractCodeMember)(parent) Dim member2 = ComAggregate.GetManagedObject(Of AbstractCodeMember)(eventE) Assert.Equal("C.E As System.EventHandler", member1.NodeKey.Name) Assert.Equal(1, member1.NodeKey.Ordinal) Assert.Equal("C.E As System.EventHandler", member2.NodeKey.Name) Assert.Equal(1, member2.NodeKey.Ordinal) End Sub) End Sub <WorkItem(31735, "https://github.com/dotnet/roslyn/issues/31735")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub RenameShouldWorkAndElementsShouldBeUsableAfter() Dim code = <code> Class C End Class </code> TestOperation(code, Sub(fileCodeModel) Dim codeElement = DirectCast(fileCodeModel.CodeElements(0), EnvDTE80.CodeElement2) Assert.Equal("C", codeElement.Name) codeElement.RenameSymbol("D") ' This not only asserts that the rename happened successfully, but that the element was correctly updated ' so the underlying node key is still valid. Assert.Equal("D", codeElement.Name) End Sub) End Sub Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.VisualBasic End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/Test/Resources/Core/MetadataTests/InterfaceAndClass/VBClasses02.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 Metadata Public Class A Public Sub SubAB(p As Byte) End Sub End Class Public Class B Inherits A Public Overloads Sub SubAB(p As SByte) End Sub End Class Public Class VBClass01 Public Overridable Sub Sub01(p1 As A, p2 As B) Console.Write("AB_OV ") End Sub Public Overridable Sub Sub01(p1 As B, p2 As A) Console.Write("BA_OV ") End Sub Protected Overridable Sub Sub01(p1 As A, p2 As A) Console.Write("PT_AA_OV ") End Sub Protected Overridable Sub Sub01(p1 As B, ByRef p2 As B) Console.Write("PT_BRefB_OV ") End Sub Friend Overridable Sub Sub01(ParamArray p1 As B()) Console.Write("FriendBAry_OV ") End Sub End Class Public Class VBClass02 Inherits VBClass01 Public NotOverridable Overrides Sub Sub01(p1 As B, p2 As A) Console.Write("(02)BA_Seal ") End Sub End Class Public Class VBBase ' members same as IMeth03.INested Public Overridable Sub NestedSub(p As UShort) Console.Write("VBaseSub (Virtual) ") End Sub Public Function NestedFunc(ByRef p As Object) As String Return "VBaseFunc (Non-Virtual) " End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Metadata Public Class A Public Sub SubAB(p As Byte) End Sub End Class Public Class B Inherits A Public Overloads Sub SubAB(p As SByte) End Sub End Class Public Class VBClass01 Public Overridable Sub Sub01(p1 As A, p2 As B) Console.Write("AB_OV ") End Sub Public Overridable Sub Sub01(p1 As B, p2 As A) Console.Write("BA_OV ") End Sub Protected Overridable Sub Sub01(p1 As A, p2 As A) Console.Write("PT_AA_OV ") End Sub Protected Overridable Sub Sub01(p1 As B, ByRef p2 As B) Console.Write("PT_BRefB_OV ") End Sub Friend Overridable Sub Sub01(ParamArray p1 As B()) Console.Write("FriendBAry_OV ") End Sub End Class Public Class VBClass02 Inherits VBClass01 Public NotOverridable Overrides Sub Sub01(p1 As B, p2 As A) Console.Write("(02)BA_Seal ") End Sub End Class Public Class VBBase ' members same as IMeth03.INested Public Overridable Sub NestedSub(p As UShort) Console.Write("VBaseSub (Virtual) ") End Sub Public Function NestedFunc(ByRef p As Object) As String Return "VBaseFunc (Non-Virtual) " End Function End Class End Namespace
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/AbstractRegionDataFlowPass.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 System.Collections.Generic Imports System.Collections.Immutable Imports System.Linq Imports System.Text Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ' Note: this code has a copy-and-paste sibling in AbstractRegionControlFlowPass. ' Any fix to one should be applied to the other. Friend MustInherit Class AbstractRegionDataFlowPass Inherits DataFlowPass Friend Sub New(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo, Optional initiallyAssignedVariables As HashSet(Of Symbol) = Nothing, Optional trackUnassignments As Boolean = False, Optional trackStructsWithIntrinsicTypedFields As Boolean = False) MyBase.New(info, region, False, initiallyAssignedVariables, trackUnassignments, trackStructsWithIntrinsicTypedFields) End Sub Public Overrides Function VisitLambda(node As BoundLambda) As BoundNode MakeSlots(node.LambdaSymbol.Parameters) Dim result = MyBase.VisitLambda(node) Return result End Function Private Sub MakeSlots(parameters As ImmutableArray(Of ParameterSymbol)) For Each parameter In parameters GetOrCreateSlot(parameter) Next End Sub Protected Overrides ReadOnly Property SuppressRedimOperandRvalueOnPreserve As Boolean Get Return False End Get End Property Public Overrides Function VisitParameter(node As BoundParameter) As BoundNode If node.ParameterSymbol.ContainingSymbol.IsQueryLambdaMethod Then Return Nothing End If Return MyBase.VisitParameter(node) End Function Protected Overrides Function CreateLocalSymbolForVariables(declarations As ImmutableArray(Of BoundLocalDeclaration)) As LocalSymbol If declarations.Length = 1 Then Return declarations(0).LocalSymbol End If Dim locals(declarations.Length - 1) As LocalSymbol For i = 0 To declarations.Length - 1 locals(i) = declarations(i).LocalSymbol Next Return AmbiguousLocalsPseudoSymbol.Create(locals.AsImmutableOrNull()) End Function Protected Overrides ReadOnly Property IgnoreOutSemantics As Boolean Get Return False End Get End Property Protected Overrides ReadOnly Property EnableBreakingFlowAnalysisFeatures As Boolean Get Return True End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Linq Imports System.Text Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ' Note: this code has a copy-and-paste sibling in AbstractRegionControlFlowPass. ' Any fix to one should be applied to the other. Friend MustInherit Class AbstractRegionDataFlowPass Inherits DataFlowPass Friend Sub New(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo, Optional initiallyAssignedVariables As HashSet(Of Symbol) = Nothing, Optional trackUnassignments As Boolean = False, Optional trackStructsWithIntrinsicTypedFields As Boolean = False) MyBase.New(info, region, False, initiallyAssignedVariables, trackUnassignments, trackStructsWithIntrinsicTypedFields) End Sub Public Overrides Function VisitLambda(node As BoundLambda) As BoundNode MakeSlots(node.LambdaSymbol.Parameters) Dim result = MyBase.VisitLambda(node) Return result End Function Private Sub MakeSlots(parameters As ImmutableArray(Of ParameterSymbol)) For Each parameter In parameters GetOrCreateSlot(parameter) Next End Sub Protected Overrides ReadOnly Property SuppressRedimOperandRvalueOnPreserve As Boolean Get Return False End Get End Property Public Overrides Function VisitParameter(node As BoundParameter) As BoundNode If node.ParameterSymbol.ContainingSymbol.IsQueryLambdaMethod Then Return Nothing End If Return MyBase.VisitParameter(node) End Function Protected Overrides Function CreateLocalSymbolForVariables(declarations As ImmutableArray(Of BoundLocalDeclaration)) As LocalSymbol If declarations.Length = 1 Then Return declarations(0).LocalSymbol End If Dim locals(declarations.Length - 1) As LocalSymbol For i = 0 To declarations.Length - 1 locals(i) = declarations(i).LocalSymbol Next Return AmbiguousLocalsPseudoSymbol.Create(locals.AsImmutableOrNull()) End Function Protected Overrides ReadOnly Property IgnoreOutSemantics As Boolean Get Return False End Get End Property Protected Overrides ReadOnly Property EnableBreakingFlowAnalysisFeatures As Boolean Get Return True End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/Operations/IndentBlockOption.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Formatting.Rules { /// <summary> /// Options for <see cref="IndentBlockOperation"/>. /// </summary> [Flags] internal enum IndentBlockOption { /// <summary> /// This indentation will be a delta to the first token in the line in which the base token is present /// </summary> RelativeToFirstTokenOnBaseTokenLine = 0x2, /// <summary> /// <see cref="IndentBlockOperation.IndentationDeltaOrPosition"/> will be interpreted as delta of its enclosing indentation /// </summary> RelativePosition = 0x4, /// <summary> /// <see cref="IndentBlockOperation.IndentationDeltaOrPosition"/> will be interpreted as absolute position /// </summary> AbsolutePosition = 0x8, /// <summary> /// Mask for relative position options /// </summary> RelativePositionMask = RelativeToFirstTokenOnBaseTokenLine | RelativePosition, /// <summary> /// Mask for position options. /// </summary> /// <remarks> /// Each <see cref="IndentBlockOperation"/> specifies one of the position options to indicate the primary /// behavior for the operation. /// </remarks> PositionMask = RelativeToFirstTokenOnBaseTokenLine | RelativePosition | AbsolutePosition, /// <summary> /// Increase the <see cref="IndentBlockOperation.IndentationDeltaOrPosition"/> if the block is part of a /// condition of the anchor token. For example: /// /// <code> /// if (value is /// { // This open brace token is part of a condition of the 'if' token. /// Length: 2 /// }) /// </code> /// </summary> IndentIfConditionOfAnchorToken = 0x10, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Formatting.Rules { /// <summary> /// Options for <see cref="IndentBlockOperation"/>. /// </summary> [Flags] internal enum IndentBlockOption { /// <summary> /// This indentation will be a delta to the first token in the line in which the base token is present /// </summary> RelativeToFirstTokenOnBaseTokenLine = 0x2, /// <summary> /// <see cref="IndentBlockOperation.IndentationDeltaOrPosition"/> will be interpreted as delta of its enclosing indentation /// </summary> RelativePosition = 0x4, /// <summary> /// <see cref="IndentBlockOperation.IndentationDeltaOrPosition"/> will be interpreted as absolute position /// </summary> AbsolutePosition = 0x8, /// <summary> /// Mask for relative position options /// </summary> RelativePositionMask = RelativeToFirstTokenOnBaseTokenLine | RelativePosition, /// <summary> /// Mask for position options. /// </summary> /// <remarks> /// Each <see cref="IndentBlockOperation"/> specifies one of the position options to indicate the primary /// behavior for the operation. /// </remarks> PositionMask = RelativeToFirstTokenOnBaseTokenLine | RelativePosition | AbsolutePosition, /// <summary> /// Increase the <see cref="IndentBlockOperation.IndentationDeltaOrPosition"/> if the block is part of a /// condition of the anchor token. For example: /// /// <code> /// if (value is /// { // This open brace token is part of a condition of the 'if' token. /// Length: 2 /// }) /// </code> /// </summary> IndentIfConditionOfAnchorToken = 0x10, } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/EditorFeatures/TestUtilities/BraceMatching/AbstractBraceMatcherTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.BraceMatching { [UseExportProvider] public abstract class AbstractBraceMatcherTests { protected abstract TestWorkspace CreateWorkspaceFromCode(string code, ParseOptions options); protected async Task TestAsync(string markup, string expectedCode, ParseOptions options = null) { using (var workspace = CreateWorkspaceFromCode(markup, options)) { var position = workspace.Documents.Single().CursorPosition.Value; var document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id); var braceMatcher = workspace.GetService<IBraceMatchingService>(); var foundSpan = await braceMatcher.FindMatchingSpanAsync(document, position, CancellationToken.None); MarkupTestFile.GetSpans(expectedCode, out var parsedExpectedCode, out ImmutableArray<TextSpan> expectedSpans); if (expectedSpans.Any()) { Assert.Equal(expectedSpans.Single(), foundSpan.Value); } else { Assert.False(foundSpan.HasValue); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.BraceMatching { [UseExportProvider] public abstract class AbstractBraceMatcherTests { protected abstract TestWorkspace CreateWorkspaceFromCode(string code, ParseOptions options); protected async Task TestAsync(string markup, string expectedCode, ParseOptions options = null) { using (var workspace = CreateWorkspaceFromCode(markup, options)) { var position = workspace.Documents.Single().CursorPosition.Value; var document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id); var braceMatcher = workspace.GetService<IBraceMatchingService>(); var foundSpan = await braceMatcher.FindMatchingSpanAsync(document, position, CancellationToken.None); MarkupTestFile.GetSpans(expectedCode, out var parsedExpectedCode, out ImmutableArray<TextSpan> expectedSpans); if (expectedSpans.Any()) { Assert.Equal(expectedSpans.Single(), foundSpan.Value); } else { Assert.False(foundSpan.HasValue); } } } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/EditorFeatures/Text/ExternalAccess/VSTypeScript/Api/VSTypeScriptTextBufferExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal static class VSTypeScriptTextBufferExtensions { public static SourceTextContainer AsTextContainer(this ITextBuffer buffer) => Text.Extensions.TextBufferContainer.From(buffer); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal static class VSTypeScriptTextBufferExtensions { public static SourceTextContainer AsTextContainer(this ITextBuffer buffer) => Text.Extensions.TextBufferContainer.From(buffer); } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/EventSymbolReferenceFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class EventSymbolReferenceFinder : AbstractMethodOrPropertyOrEventSymbolReferenceFinder<IEventSymbol> { protected override bool CanFind(IEventSymbol symbol) => true; protected override Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsAsync( IEventSymbol symbol, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var backingFields = symbol.ContainingType.GetMembers() .OfType<IFieldSymbol>() .Where(f => symbol.Equals(f.AssociatedSymbol)) .ToImmutableArray<ISymbol>(); var associatedNamedTypes = symbol.ContainingType.GetTypeMembers() .WhereAsArray(n => symbol.Equals(n.AssociatedSymbol)) .CastArray<ISymbol>(); return Task.FromResult(backingFields.Concat(associatedNamedTypes)); } protected override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IEventSymbol symbol, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var documentsWithName = await FindDocumentsAsync(project, documents, cancellationToken, symbol.Name).ConfigureAwait(false); var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false); return documentsWithName.Concat(documentsWithGlobalAttributes); } protected override ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IEventSymbol symbol, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { return FindReferencesInDocumentUsingSymbolNameAsync(symbol, document, semanticModel, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class EventSymbolReferenceFinder : AbstractMethodOrPropertyOrEventSymbolReferenceFinder<IEventSymbol> { protected override bool CanFind(IEventSymbol symbol) => true; protected override Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsAsync( IEventSymbol symbol, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var backingFields = symbol.ContainingType.GetMembers() .OfType<IFieldSymbol>() .Where(f => symbol.Equals(f.AssociatedSymbol)) .ToImmutableArray<ISymbol>(); var associatedNamedTypes = symbol.ContainingType.GetTypeMembers() .WhereAsArray(n => symbol.Equals(n.AssociatedSymbol)) .CastArray<ISymbol>(); return Task.FromResult(backingFields.Concat(associatedNamedTypes)); } protected override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IEventSymbol symbol, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var documentsWithName = await FindDocumentsAsync(project, documents, cancellationToken, symbol.Name).ConfigureAwait(false); var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false); return documentsWithName.Concat(documentsWithGlobalAttributes); } protected override ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IEventSymbol symbol, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { return FindReferencesInDocumentUsingSymbolNameAsync(symbol, document, semanticModel, cancellationToken); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/EditorFeatures/Core/SymbolSearch/IPatchService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.SymbolSearch { /// <summary> /// Used so we can mock out patching in unit tests. /// </summary> internal interface IPatchService { byte[] ApplyPatch(byte[] databaseBytes, byte[] patchBytes); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.SymbolSearch { /// <summary> /// Used so we can mock out patching in unit tests. /// </summary> internal interface IPatchService { byte[] ApplyPatch(byte[] databaseBytes, byte[] patchBytes); } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/Core/Portable/Operations/InstanceReferenceKind.cs
// Licensed to the .NET Foundation under one or more 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.Operations { /// <summary> /// Kind of reference for an <see cref="IInstanceReferenceOperation"/>. /// </summary> public enum InstanceReferenceKind { /// <summary> /// Reference to an instance of the containing type. Used for <code>this</code> and <code>base</code> in C# code, and <code>Me</code>, /// <code>MyClass</code>, <code>MyBase</code> in VB code. /// </summary> ContainingTypeInstance, /// <summary> /// Reference to the object being initialized in C# or VB object or collection initializer, /// anonymous type creation initializer, or to the object being referred to in a VB With statement, /// or the C# 'with' expression initializer. /// </summary> ImplicitReceiver, /// <summary> /// Reference to the value being matching in a property subpattern. /// </summary> PatternInput, } }
// Licensed to the .NET Foundation under one or more 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.Operations { /// <summary> /// Kind of reference for an <see cref="IInstanceReferenceOperation"/>. /// </summary> public enum InstanceReferenceKind { /// <summary> /// Reference to an instance of the containing type. Used for <code>this</code> and <code>base</code> in C# code, and <code>Me</code>, /// <code>MyClass</code>, <code>MyBase</code> in VB code. /// </summary> ContainingTypeInstance, /// <summary> /// Reference to the object being initialized in C# or VB object or collection initializer, /// anonymous type creation initializer, or to the object being referred to in a VB With statement, /// or the C# 'with' expression initializer. /// </summary> ImplicitReceiver, /// <summary> /// Reference to the value being matching in a property subpattern. /// </summary> PatternInput, } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Workspaces/Core/Portable/Workspace/Host/CompilationFactory/ICompilationFactoryService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Host { internal interface ICompilationFactoryService : ILanguageService { Compilation CreateCompilation(string assemblyName, CompilationOptions options); Compilation CreateSubmissionCompilation(string assemblyName, CompilationOptions options, Type? hostObjectType); CompilationOptions GetDefaultCompilationOptions(); GeneratorDriver CreateGeneratorDriver(ParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider optionsProvider, ImmutableArray<AdditionalText> additionalTexts); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Host { internal interface ICompilationFactoryService : ILanguageService { Compilation CreateCompilation(string assemblyName, CompilationOptions options); Compilation CreateSubmissionCompilation(string assemblyName, CompilationOptions options, Type? hostObjectType); CompilationOptions GetDefaultCompilationOptions(); GeneratorDriver CreateGeneratorDriver(ParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider optionsProvider, ImmutableArray<AdditionalText> additionalTexts); } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/CSharp/Test/Semantic/Semantics/LookupTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class GetSemanticInfoTests : SemanticModelTestBase { #region helpers internal List<string> GetLookupNames(string testSrc) { var parseOptions = TestOptions.Regular; var compilation = CreateCompilationWithMscorlib45(testSrc, parseOptions: parseOptions); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = testSrc.Contains("/*<bind>*/") ? GetPositionForBinding(tree) : GetPositionForBinding(testSrc); return model.LookupNames(position); } internal List<ISymbol> GetLookupSymbols(string testSrc, NamespaceOrTypeSymbol container = null, string name = null, int? arity = null, bool isScript = false, IEnumerable<string> globalUsings = null) { var tree = Parse(testSrc, options: isScript ? TestOptions.Script : TestOptions.Regular); var compilation = CreateCompilationWithMscorlib45(new[] { tree }, options: TestOptions.ReleaseDll.WithUsings(globalUsings)); var model = compilation.GetSemanticModel(tree); var position = testSrc.Contains("/*<bind>*/") ? GetPositionForBinding(tree) : GetPositionForBinding(testSrc); return model.LookupSymbols(position, container.GetPublicSymbol(), name).Where(s => !arity.HasValue || arity == s.GetSymbol().GetMemberArity()).ToList(); } #endregion helpers #region tests [Fact] public void LookupExpressionBodyProp01() { var text = @" class C { public int P => /*<bind>*/10/*</bind>*/; }"; var actual = GetLookupNames(text).ListToSortedString(); var expected_lookupNames = new List<string> { "C", "Equals", "Finalize", "GetHashCode", "GetType", "MemberwiseClone", "Microsoft", "P", "ReferenceEquals", "System", "ToString" }; Assert.Equal(expected_lookupNames.ListToSortedString(), actual); } [Fact] public void LookupExpressionBodiedMethod01() { var text = @" class C { public int M() => /*<bind>*/10/*</bind>*/; }"; var actual = GetLookupNames(text).ListToSortedString(); var expected_lookupNames = new List<string> { "C", "Equals", "Finalize", "GetHashCode", "GetType", "MemberwiseClone", "Microsoft", "M", "ReferenceEquals", "System", "ToString" }; Assert.Equal(expected_lookupNames.ListToSortedString(), actual); } [WorkItem(538262, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538262")] [Fact] public void LookupCompilationUnitSyntax() { var testSrc = @" /*<bind>*/ class Test { } /*</bind>*/ "; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupSymbols(testSrc); } [WorkItem(527476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527476")] [Fact] public void LookupConstrAndDestr() { var testSrc = @" class Test { Test() { } Test(int i) { } ~Test() { } static /*<bind>*/void/*</bind>*/Main() { } } "; List<string> expected_lookupNames = new List<string> { "Equals", "Finalize", "GetHashCode", "GetType", "Main", "MemberwiseClone", "Microsoft", "ReferenceEquals", "System", "Test", "ToString" }; List<string> expected_lookupSymbols = new List<string> { "Microsoft", "System", "System.Boolean System.Object.Equals(System.Object obj)", "System.Boolean System.Object.Equals(System.Object objA, System.Object objB)", "System.Boolean System.Object.ReferenceEquals(System.Object objA, System.Object objB)", "System.Int32 System.Object.GetHashCode()", "System.Object System.Object.MemberwiseClone()", "void System.Object.Finalize()", "System.String System.Object.ToString()", "System.Type System.Object.GetType()", "void Test.Finalize()", "void Test.Main()", "Test" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc); Assert.Equal(expected_lookupNames.ListToSortedString(), actual_lookupNames.ListToSortedString()); Assert.Equal(expected_lookupSymbols.ListToSortedString(), actual_lookupSymbols.ListToSortedString()); } [WorkItem(527477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527477")] [Fact] public void LookupNotYetDeclLocalVar() { var testSrc = @" class Test { static void Main() { int j = /*<bind>*/9/*</bind>*/ ; int k = 45; } } "; List<string> expected_in_lookupNames = new List<string> { "j", "k" }; List<string> expected_in_lookupSymbols = new List<string> { "j", "k" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); } [WorkItem(538301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538301")] [Fact] public void LookupByNameIncorrectArity() { var testSrc = @" class Test { public static void Main() { int i = /*<bind>*/10/*</bind>*/; } } "; // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupSymbols(testSrc, name: "i", arity: 1); var actual_lookupSymbols = GetLookupSymbols(testSrc, name: "i", arity: 1); Assert.Empty(actual_lookupSymbols); } [WorkItem(538310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538310")] [Fact] public void LookupInProtectedNonNestedType() { var testSrc = @" protected class MyClass { /*<bind>*/public static void Main()/*</bind>*/ {} } "; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupSymbols(testSrc); } [WorkItem(538311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538311")] [Fact] public void LookupClassContainsVolatileEnumField() { var testSrc = @" enum E{} class Test { static volatile E x; static /*<bind>*/int/*</bind>*/ Main() { return 1; } } "; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupSymbols(testSrc); } [WorkItem(538312, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538312")] [Fact] public void LookupUsingAlias() { var testSrc = @" using T2 = System.IO; namespace T1 { class Test { static /*<bind>*/void/*</bind>*/ Main() { } } } "; List<string> expected_in_lookupNames = new List<string> { "T1", "T2" }; List<string> expected_in_lookupSymbols = new List<string> { "T1", "T2" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); } [WorkItem(538313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538313")] [Fact] public void LookupUsingNameSpaceContSameTypeNames() { var testSrc = @" namespace T1 { using T2; public class Test { static /*<bind>*/int/*</bind>*/ Main() { return 1; } } } namespace T2 { public class Test { } } "; List<string> expected_in_lookupNames = new List<string> { "T1", "T2", "Test" }; List<string> expected_in_lookupSymbols = new List<string> { "T1", "T2", "T1.Test", //"T2.Test" this is hidden by T1.Test }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupNames[2], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[2], actual_lookupSymbols_as_string); } [WorkItem(527489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527489")] [Fact] public void LookupMustNotBeNonInvocableMember() { var testSrc = @" class Test { public void TestMeth(int i, int j) { int m = /*<bind>*/10/*</bind>*/; } } "; List<string> expected_in_lookupNames = new List<string> { "TestMeth", "i", "j", "m", "System", "Microsoft", "Test" }; List<string> expected_in_lookupSymbols = new List<string> { "void Test.TestMeth(System.Int32 i, System.Int32 j)", "System.Int32 i", "System.Int32 j", "System.Int32 m", "System", "Microsoft", "Test" }; var comp = CreateCompilation(testSrc); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var position = GetPositionForBinding(tree); var binder = ((CSharpSemanticModel)model).GetEnclosingBinder(position); // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var info = LookupSymbolsInfo.GetInstance(); binder.AddLookupSymbolsInfo(info, LookupOptions.MustBeInvocableIfMember); var actual_lookupNames = info.Names; // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = actual_lookupNames.SelectMany(name => { var lookupResult = LookupResult.GetInstance(); HashSet<DiagnosticInfo> useSiteDiagnostics = null; binder.LookupSymbolsSimpleName( lookupResult, qualifierOpt: null, plainName: name, arity: 0, basesBeingResolved: null, options: LookupOptions.MustBeInvocableIfMember, diagnose: false, useSiteDiagnostics: ref useSiteDiagnostics); Assert.Null(useSiteDiagnostics); Assert.True(lookupResult.IsMultiViable || lookupResult.Kind == LookupResultKind.NotReferencable); var result = lookupResult.Symbols.ToArray(); lookupResult.Free(); return result; }); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupNames[2], actual_lookupNames); Assert.Contains(expected_in_lookupNames[3], actual_lookupNames); Assert.Contains(expected_in_lookupNames[4], actual_lookupNames); Assert.Contains(expected_in_lookupNames[5], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[2], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[3], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[4], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[5], actual_lookupSymbols_as_string); info.Free(); } [WorkItem(538365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538365")] [Fact] public void LookupWithNameZeroArity() { var testSrc = @" class Test { private void F<T>(T i) { } private void F<T, U>(T i, U j) { } private void F(int i) { } private void F(int i, int j) { } public static /*<bind>*/void/*</bind>*/ Main() { } } "; List<string> expected_in_lookupNames = new List<string> { "F" }; List<string> expected_in_lookupSymbols = new List<string> { "void Test.F(System.Int32 i)", "void Test.F(System.Int32 i, System.Int32 j)" }; List<string> not_expected_in_lookupSymbols = new List<string> { "void Test.F<T>(T i)", "void Test.F<T, U>(T i, U j)" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc, name: "F", arity: 0); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Equal(2, actual_lookupSymbols.Count); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.DoesNotContain(not_expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.DoesNotContain(not_expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); } [WorkItem(538365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538365")] [Fact] public void LookupWithNameZeroArityAndLookupOptionsAllMethods() { var testSrc = @" class Test { public void F<T>(T i) { } public void F<T, U>(T i, U j) { } public void F(int i) { } public void F(int i, int j) { } public void Main() { return; } } "; List<string> expected_in_lookupNames = new List<string> { "F" }; List<string> expected_in_lookupSymbols = new List<string> { "void Test.F(System.Int32 i)", "void Test.F(System.Int32 i, System.Int32 j)", "void Test.F<T>(T i)", "void Test.F<T, U>(T i, U j)" }; // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var comp = CreateCompilation(testSrc); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var position = testSrc.IndexOf("return", StringComparison.Ordinal); var binder = ((CSharpSemanticModel)model).GetEnclosingBinder(position); var lookupResult = LookupResult.GetInstance(); HashSet<DiagnosticInfo> useSiteDiagnostics = null; binder.LookupSymbolsSimpleName(lookupResult, qualifierOpt: null, plainName: "F", arity: 0, basesBeingResolved: null, options: LookupOptions.AllMethodsOnArityZero, diagnose: false, useSiteDiagnostics: ref useSiteDiagnostics); Assert.Null(useSiteDiagnostics); Assert.True(lookupResult.IsMultiViable); var actual_lookupSymbols_as_string = lookupResult.Symbols.Select(e => e.ToTestDisplayString()).ToArray(); lookupResult.Free(); // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = model.LookupNames(position); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Equal(4, actual_lookupSymbols_as_string.Length); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[2], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[3], actual_lookupSymbols_as_string); } [WorkItem(539160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539160")] [Fact] public void LookupExcludeInAppropriateNS() { var testSrc = @" class Test { public static /*<bind>*/void/*</bind>*/ Main() { } } "; var srcTrees = new SyntaxTree[] { Parse(testSrc) }; var refs = new MetadataReference[] { SystemDataRef }; CSharpCompilation compilation = CSharpCompilation.Create("Test.dll", srcTrees, refs); var tree = srcTrees[0]; var model = compilation.GetSemanticModel(tree); List<string> not_expected_in_lookup = new List<string> { "<CrtImplementationDetails>", "<CppImplementationDetails>" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = model.LookupNames(GetPositionForBinding(tree), null).ToList(); var actual_lookupNames_ignoreAcc = model.LookupNames(GetPositionForBinding(tree), null).ToList(); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = model.LookupSymbols(GetPositionForBinding(tree)); var actual_lookupSymbols_ignoreAcc = model.LookupSymbols(GetPositionForBinding(tree)); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); var actual_lookupSymbols_ignoreAcc_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.DoesNotContain(not_expected_in_lookup[0], actual_lookupNames); Assert.DoesNotContain(not_expected_in_lookup[1], actual_lookupNames); Assert.DoesNotContain(not_expected_in_lookup[0], actual_lookupNames_ignoreAcc); Assert.DoesNotContain(not_expected_in_lookup[1], actual_lookupNames_ignoreAcc); Assert.DoesNotContain(not_expected_in_lookup[0], actual_lookupSymbols_as_string); Assert.DoesNotContain(not_expected_in_lookup[1], actual_lookupSymbols_as_string); Assert.DoesNotContain(not_expected_in_lookup[0], actual_lookupSymbols_ignoreAcc_as_string); Assert.DoesNotContain(not_expected_in_lookup[1], actual_lookupSymbols_ignoreAcc_as_string); } /// <summary> /// Verify that there's a way to look up only the members of the base type that are visible /// from the current type. /// </summary> [Fact] [WorkItem(539814, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539814")] public void LookupProtectedInBase() { var testSrc = @" class A { private void Hidden() { } protected void Goo() { } } class B : A { void Bar() { /*<bind>*/base/*</bind>*/.Goo(); } } "; var srcTrees = new SyntaxTree[] { Parse(testSrc) }; var refs = new MetadataReference[] { SystemDataRef }; CSharpCompilation compilation = CSharpCompilation.Create("Test.dll", srcTrees, refs); var tree = srcTrees[0]; var model = compilation.GetSemanticModel(tree); var baseExprNode = GetSyntaxNodeForBinding(GetSyntaxNodeList(tree)); Assert.Equal("base", baseExprNode.ToString()); var baseExprLocation = baseExprNode.SpanStart; Assert.NotEqual(0, baseExprLocation); var baseExprInfo = model.GetTypeInfo((ExpressionSyntax)baseExprNode); Assert.NotEqual(default, baseExprInfo); var baseExprType = (INamedTypeSymbol)baseExprInfo.Type; Assert.NotNull(baseExprType); Assert.Equal("A", baseExprType.Name); var symbols = model.LookupBaseMembers(baseExprLocation); Assert.Equal("void A.Goo()", symbols.Single().ToTestDisplayString()); var names = model.LookupNames(baseExprLocation, useBaseReferenceAccessibility: true); Assert.Equal("Goo", names.Single()); } [WorkItem(528263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528263")] [Fact] public void LookupStartOfScopeMethodBody() { var testSrc = @"public class start { static public void Main() /*pos*/{ int num=10; } "; List<string> expected_in_lookupNames = new List<string> { "Main", "start", "num" }; List<string> expected_in_lookupSymbols = new List<string> { "void start.Main()", "start", "System.Int32 num" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Equal('{', testSrc[GetPositionForBinding(testSrc)]); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupNames[2], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[2], actual_lookupSymbols_as_string); } [WorkItem(528263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528263")] [Fact] public void LookupEndOfScopeMethodBody() { var testSrc = @"public class start { static public void Main() { int num=10; /*pos*/} "; List<string> expected_in_lookupNames = new List<string> { "Main", "start" }; List<string> expected_in_lookupSymbols = new List<string> { "void start.Main()", "start" }; List<string> not_expected_in_lookupNames = new List<string> { "num" }; List<string> not_expected_in_lookupSymbols = new List<string> { "System.Int32 num" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Equal('}', testSrc[GetPositionForBinding(testSrc)]); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.DoesNotContain(not_expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.DoesNotContain(not_expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(540888, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540888")] [Fact] public void LookupLambdaParamInConstructorInitializer() { var testSrc = @" using System; class MyClass { public MyClass(Func<int, int> x) { } public MyClass(int j, int k) : this(lambdaParam => /*pos*/lambdaParam) { } } "; List<string> expected_in_lookupNames = new List<string> { "j", "k", "lambdaParam" }; List<string> expected_in_lookupSymbols = new List<string> { "System.Int32 j", "System.Int32 k", "System.Int32 lambdaParam" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupNames[2], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[2], actual_lookupSymbols_as_string); } [WorkItem(540893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540893")] [Fact] public void TestForLocalVarDeclLookupAtForKeywordInForStmt() { var testSrc = @" class MyClass { static void Main() { /*pos*/for (int forVar = 10; forVar < 10; forVar++) { } } } "; List<string> not_expected_in_lookupNames = new List<string> { "forVar" }; List<string> not_expected_in_lookupSymbols = new List<string> { "System.Int32 forVar", }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.DoesNotContain(not_expected_in_lookupNames[0], actual_lookupNames); Assert.DoesNotContain(not_expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(540894, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540894")] [Fact] public void TestForeachIterVarLookupAtForeachKeyword() { var testSrc = @" class MyClass { static void Main() { System.Collections.Generic.List<int> listOfNumbers = new System.Collections.Generic.List<int>(); /*pos*/foreach (int number in listOfNumbers) { } } } "; List<string> not_expected_in_lookupNames = new List<string> { "number" }; List<string> not_expected_in_lookupSymbols = new List<string> { "System.Int32 number", }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.DoesNotContain(not_expected_in_lookupNames[0], actual_lookupNames); Assert.DoesNotContain(not_expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(540912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540912")] [Fact] public void TestLookupInConstrInitIncompleteConstrDecl() { var testSrc = @" class MyClass { public MyClass(int x) { } public MyClass(int j, int k) :this(/*pos*/k) "; List<string> expected_in_lookupNames = new List<string> { "j", "k" }; List<string> expected_in_lookupSymbols = new List<string> { "System.Int32 j", "System.Int32 k", }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); } [WorkItem(541060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541060")] [Fact] public void TestLookupInsideIncompleteNestedLambdaBody() { var testSrc = @" class C { C() { D(() => { D(() => { }/*pos*/ "; List<string> expected_in_lookupNames = new List<string> { "C" }; List<string> expected_in_lookupSymbols = new List<string> { "C" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.NotEmpty(actual_lookupNames); Assert.NotEmpty(actual_lookupSymbols); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(541611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541611")] [Fact] public void LookupLambdaInsideAttributeUsage() { var testSrc = @" using System; class Program { [ObsoleteAttribute(x=>x/*pos*/ static void Main(string[] args) { } } "; List<string> expected_in_lookupNames = new List<string> { "x" }; List<string> expected_in_lookupSymbols = new List<string> { "? x" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [Fact] public void LookupInsideLocalFunctionAttribute() { var testSrc = @" using System; class Program { const int w = 0451; void M() { int x = 42; const int y = 123; [ObsoleteAttribute(/*pos*/ static void local1(int z) { } } } "; var lookupNames = GetLookupNames(testSrc); var lookupSymbols = GetLookupSymbols(testSrc).Select(e => e.ToTestDisplayString()).ToList(); Assert.Contains("w", lookupNames); Assert.Contains("y", lookupNames); Assert.Contains("System.Int32 Program.w", lookupSymbols); Assert.Contains("System.Int32 y", lookupSymbols); } [Fact] public void LookupInsideLambdaAttribute() { var testSrc = @" using System; class Program { const int w = 0451; void M() { int x = 42; const int y = 123; Action<int> a = [ObsoleteAttribute(/*pos*/ (int z) => { }; } } "; var lookupNames = GetLookupNames(testSrc); var lookupSymbols = GetLookupSymbols(testSrc).Select(e => e.ToTestDisplayString()).ToList(); Assert.Contains("w", lookupNames); Assert.Contains("y", lookupNames); Assert.Contains("System.Int32 Program.w", lookupSymbols); Assert.Contains("System.Int32 y", lookupSymbols); } [Fact] public void LookupInsideIncompleteStatementAttribute() { var testSrc = @" using System; class Program { const int w = 0451; void M() { int x = 42; const int y = 123; [ObsoleteAttribute(/*pos*/ int } } "; var lookupNames = GetLookupNames(testSrc); var lookupSymbols = GetLookupSymbols(testSrc).Select(e => e.ToTestDisplayString()).ToList(); Assert.Contains("w", lookupNames); Assert.Contains("y", lookupNames); Assert.Contains("System.Int32 Program.w", lookupSymbols); Assert.Contains("System.Int32 y", lookupSymbols); } [WorkItem(541909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541909")] [Fact] public void LookupFromRangeVariableAfterFromClause() { var testSrc = @" class Program { static void Main(string[] args) { var q = from i in new int[] { 4, 5 } where /*pos*/ } } "; List<string> expected_in_lookupNames = new List<string> { "i" }; List<string> expected_in_lookupSymbols = new List<string> { "? i" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(541921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541921")] [Fact] public void LookupFromRangeVariableInsideNestedFromClause() { var testSrc = @" class Program { static void Main(string[] args) { string[] strings = { }; var query = from s in strings from s1 in /*pos*/ } } "; List<string> expected_in_lookupNames = new List<string> { "s" }; List<string> expected_in_lookupSymbols = new List<string> { "? s" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(541919, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541919")] [Fact] public void LookupLambdaVariableInQueryExpr() { var testSrc = @" class Program { static void Main(string[] args) { Func<int, IEnumerable<int>> f1 = (x) => from n in /*pos*/ } } "; List<string> expected_in_lookupNames = new List<string> { "x" }; List<string> expected_in_lookupSymbols = new List<string> { "x" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.Name); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(541910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541910")] [Fact] public void LookupInsideQueryExprOutsideTypeDecl() { var testSrc = @"var q = from i in/*pos*/ f"; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.NotEmpty(actual_lookupNames); Assert.NotEmpty(actual_lookupSymbols_as_string); } [WorkItem(542203, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542203")] [Fact] public void LookupInsideQueryExprInMalformedFromClause() { var testSrc = @" using System; using System.Linq; class Program { static void Main(string[] args) { int[] numbers = new int[] { 4, 5 }; var q1 = from I<x/*pos*/ in numbers.Where(x1 => x1 > 2) select x; } } "; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.NotEmpty(actual_lookupNames); Assert.NotEmpty(actual_lookupSymbols_as_string); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void MultipleOverlappingInterfaceConstraints() { var testSrc = @"public interface IEntity { object Key { get; } } public interface INumberedProjectChild : IEntity { } public interface IAggregateRoot : IEntity { } public interface ISpecification<TCandidate> { void IsSatisfiedBy(TCandidate candidate); } public abstract class Specification<TCandidate> : ISpecification<TCandidate> { public abstract void IsSatisfiedBy(TCandidate candidate); } public class NumberSpecification<TCandidate> : Specification<TCandidate> where TCandidate : IAggregateRoot, INumberedProjectChild { public override void IsSatisfiedBy(TCandidate candidate) { var key = candidate.Key; } }"; CreateCompilation(testSrc).VerifyDiagnostics(); } [WorkItem(529406, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529406")] [Fact] public void FixedPointerInitializer() { var testSrc = @" class Program { static int num = 0; unsafe static void Main(string[] args) { fixed(int* p1 = /*pos*/&num, p2 = &num) { } } } "; List<string> expected_in_lookupNames = new List<string> { "p2" }; List<string> expected_in_lookupSymbols = new List<string> { "p2" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToString()).ToList(); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [Fact] public void LookupSymbolsAtEOF() { var source = @"class { }"; var tree = Parse(source); var comp = CreateCompilationWithMscorlib40(new[] { tree }); var model = comp.GetSemanticModel(tree); var eof = tree.GetCompilationUnitRoot().FullSpan.End; Assert.NotEqual(0, eof); var symbols = model.LookupSymbols(eof); CompilationUtils.CheckISymbols(symbols, "System", "Microsoft"); } [Fact, WorkItem(546523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546523")] public void TestLookupSymbolsNestedNamespacesNotImportedByUsings_01() { var source = @" using System; class Program { static void Main(string[] args) { /*pos*/ } } "; // Get the list of LookupSymbols at the location of the CSharpSyntaxNode var actual_lookupSymbols = GetLookupSymbols(source); // Verify nested namespaces *are not* imported. var systemNS = (INamespaceSymbol)actual_lookupSymbols.Where((sym) => sym.Name.Equals("System") && sym.Kind == SymbolKind.Namespace).Single(); INamespaceSymbol systemXmlNS = systemNS.GetNestedNamespace("Xml"); Assert.DoesNotContain(systemXmlNS, actual_lookupSymbols); } [Fact, WorkItem(546523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546523")] public void TestLookupSymbolsNestedNamespacesNotImportedByUsings_02() { var usings = new[] { "using X;" }; var source = @" using aliasY = X.Y; namespace X { namespace Y { public class InnerZ { } } public class Z { } public static class StaticZ { } } public class A { public class B { } } class Program { public static void Main() { /*pos*/ } } "; // Get the list of LookupSymbols at the location of the CSharpSyntaxNode var actual_lookupSymbols = GetLookupSymbols(usings.ToString() + source, isScript: false); TestLookupSymbolsNestedNamespaces(actual_lookupSymbols); actual_lookupSymbols = GetLookupSymbols(source, isScript: true, globalUsings: usings); TestLookupSymbolsNestedNamespaces(actual_lookupSymbols); Action<ModuleSymbol> validator = (module) => { NamespaceSymbol globalNS = module.GlobalNamespace; Assert.Equal(1, globalNS.GetMembers("X").Length); Assert.Equal(1, globalNS.GetMembers("A").Length); Assert.Equal(1, globalNS.GetMembers("Program").Length); Assert.Empty(globalNS.GetMembers("Y")); Assert.Empty(globalNS.GetMembers("Z")); Assert.Empty(globalNS.GetMembers("StaticZ")); Assert.Empty(globalNS.GetMembers("B")); }; CompileAndVerify(source, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] [WorkItem(530826, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530826")] public void TestAmbiguousInterfaceLookup() { var source = @"delegate void D(); interface I1 { void M(); } interface I2 { event D M; } interface I3 : I1, I2 { } public class P : I3 { event D I2.M { add { } remove { } } void I1.M() { } } class Q : P { static int Main(string[] args) { Q p = new Q(); I3 m = p; if (m.M is object) {} return 0; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ExpressionSyntax>().Where(n => n.ToString() == "m.M").Single(); var symbolInfo = model.GetSymbolInfo(node); Assert.Equal("void I1.M()", symbolInfo.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); var node2 = (ExpressionSyntax)SyntaxFactory.SyntaxTree(node).GetRoot(); symbolInfo = model.GetSpeculativeSymbolInfo(node.Position, node2, SpeculativeBindingOption.BindAsExpression); Assert.Equal("void I1.M()", symbolInfo.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); } [Fact] public void TestLookupVerbatimVar() { var source = "class C { public static void Main() { @var v = 1; } }"; CreateCompilation(source).VerifyDiagnostics( // (1,39): error CS0246: The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?) // class C { public static void Main() { @var v = 1; } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "@var").WithArguments("var").WithLocation(1, 39) ); } private void TestLookupSymbolsNestedNamespaces(List<ISymbol> actual_lookupSymbols) { var namespaceX = (INamespaceSymbol)actual_lookupSymbols.Where((sym) => sym.Name.Equals("X") && sym.Kind == SymbolKind.Namespace).Single(); // Verify nested namespaces within namespace X *are not* present in lookup symbols. INamespaceSymbol namespaceY = namespaceX.GetNestedNamespace("Y"); Assert.DoesNotContain(namespaceY, actual_lookupSymbols); INamedTypeSymbol typeInnerZ = namespaceY.GetTypeMembers("InnerZ").Single(); Assert.DoesNotContain(typeInnerZ, actual_lookupSymbols); // Verify nested types *are not* present in lookup symbols. var typeA = (INamedTypeSymbol)actual_lookupSymbols.Where((sym) => sym.Name.Equals("A") && sym.Kind == SymbolKind.NamedType).Single(); INamedTypeSymbol typeB = typeA.GetTypeMembers("B").Single(); Assert.DoesNotContain(typeB, actual_lookupSymbols); // Verify aliases to nested namespaces within namespace X *are* present in lookup symbols. var aliasY = (IAliasSymbol)actual_lookupSymbols.Where((sym) => sym.Name.Equals("aliasY") && sym.Kind == SymbolKind.Alias).Single(); Assert.Contains(aliasY, actual_lookupSymbols); } [Fact] public void ExtensionMethodCall() { var source = @"static class E { internal static void F(this object o) { } } class C { void M() { /*<bind>*/this.F/*</bind>*/(); } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); compilation.VerifyDiagnostics(); var exprs = GetExprSyntaxList(tree); var expr = GetExprSyntaxForBinding(exprs); var method = (IMethodSymbol)model.GetSymbolInfo(expr).Symbol; Assert.Equal("object.F()", method.ToDisplayString()); var reducedFrom = method.ReducedFrom; Assert.NotNull(reducedFrom); Assert.Equal("E.F(object)", reducedFrom.ToDisplayString()); } [WorkItem(3651, "https://github.com/dotnet/roslyn/issues/3651")] [Fact] public void ExtensionMethodDelegateCreation() { var source = @"static class E { internal static void F(this object o) { } } class C { void M() { (new System.Action<object>(/*<bind>*/E.F/*</bind>*/))(this); (new System.Action(/*<bind1>*/this.F/*</bind1>*/))(); } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); compilation.VerifyDiagnostics(); var exprs = GetExprSyntaxList(tree); var expr = GetExprSyntaxForBinding(exprs, index: 0); var method = (IMethodSymbol)model.GetSymbolInfo(expr).Symbol; Assert.Null(method.ReducedFrom); Assert.Equal("E.F(object)", method.ToDisplayString()); expr = GetExprSyntaxForBinding(exprs, index: 1); method = (IMethodSymbol)model.GetSymbolInfo(expr).Symbol; Assert.Equal("object.F()", method.ToDisplayString()); var reducedFrom = method.ReducedFrom; Assert.NotNull(reducedFrom); Assert.Equal("E.F(object)", reducedFrom.ToDisplayString()); } [WorkItem(7493, "https://github.com/dotnet/roslyn/issues/7493")] [Fact] public void GenericNameLookup() { var source = @"using A = List<int>;"; var compilation = CreateCompilation(source).VerifyDiagnostics( // (1,11): error CS0246: The type or namespace name 'List<>' could not be found (are you missing a using directive or an assembly reference?) // using A = List<int>; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "List<int>").WithArguments("List<>").WithLocation(1, 11), // (1,1): hidden CS8019: Unnecessary using directive. // using A = List<int>; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using A = List<int>;").WithLocation(1, 1)); } #endregion tests #region regressions [Fact] [WorkItem(552472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552472")] public void BrokenCode01() { var source = @"Dele<Str> d3 = delegate (Dele<Str> d2 = delegate () { returne<double> d1 = delegate () { return 1; }; { int result = 0; Dels Test : Base"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); SemanticModel imodel = model; var node = tree.GetRoot().DescendantNodes().Where(n => n.ToString() == "returne<double>").First(); imodel.GetSymbolInfo(node, default(CancellationToken)); } [Fact] [WorkItem(552472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552472")] public void BrokenCode02() { var source = @"public delegate D D(D d); class Program { public D d3 = delegate(D d2 = delegate { System.Object x = 3; return null; }) {}; public static void Main(string[] args) { } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); SemanticModel imodel = model; var node = tree.GetRoot().DescendantNodes().Where(n => n.ToString() == "System.Object").First(); imodel.GetSymbolInfo(node, default(CancellationToken)); } [Fact] public void InterfaceDiamondHiding() { var source = @" interface T { int P { get; set; } int Q { get; set; } } interface L : T { new int P { get; set; } } interface R : T { new int Q { get; set; } } interface B : L, R { } class Test { int M(B b) { return b.P + b.Q; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var interfaceT = global.GetMember<NamedTypeSymbol>("T"); var interfaceL = global.GetMember<NamedTypeSymbol>("L"); var interfaceR = global.GetMember<NamedTypeSymbol>("R"); var interfaceB = global.GetMember<NamedTypeSymbol>("B"); var propertyTP = interfaceT.GetMember<PropertySymbol>("P"); var propertyTQ = interfaceT.GetMember<PropertySymbol>("Q"); var propertyLP = interfaceL.GetMember<PropertySymbol>("P"); var propertyRQ = interfaceR.GetMember<PropertySymbol>("Q"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var syntaxes = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().ToArray(); Assert.Equal(2, syntaxes.Length); // The properties in T are hidden - we bind to the properties on more-derived interfaces Assert.Equal(propertyLP.GetPublicSymbol(), model.GetSymbolInfo(syntaxes[0]).Symbol); Assert.Equal(propertyRQ.GetPublicSymbol(), model.GetSymbolInfo(syntaxes[1]).Symbol); int position = source.IndexOf("return", StringComparison.Ordinal); // We do the right thing with diamond inheritance (i.e. member is hidden along all paths // if it is hidden along any path) because we visit base interfaces in topological order. Assert.Equal(propertyLP.GetPublicSymbol(), model.LookupSymbols(position, interfaceB.GetPublicSymbol(), "P").Single()); Assert.Equal(propertyRQ.GetPublicSymbol(), model.LookupSymbols(position, interfaceB.GetPublicSymbol(), "Q").Single()); } [Fact] public void SemanticModel_OnlyInvalid() { var source = @" public class C { void M() { return; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); int position = source.IndexOf("return", StringComparison.Ordinal); var symbols = model.LookupNamespacesAndTypes(position, name: "M"); Assert.Equal(0, symbols.Length); } [Fact] public void SemanticModel_InvalidHidingValid() { var source = @" public class C<T> { public class Inner { void T() { return; } } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var classC = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var methodT = classC.GetMember<NamedTypeSymbol>("Inner").GetMember<MethodSymbol>("T"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); int position = source.IndexOf("return", StringComparison.Ordinal); var symbols = model.LookupSymbols(position, name: "T"); Assert.Equal(methodT.GetPublicSymbol(), symbols.Single()); // Hides type parameter. symbols = model.LookupNamespacesAndTypes(position, name: "T"); Assert.Equal(classC.TypeParameters.Single().GetPublicSymbol(), symbols.Single()); // Ignore intervening method. } [Fact] public void SemanticModel_MultipleValid() { var source = @" public class Outer { void M(int x) { } void M() { return; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); int position = source.IndexOf("return", StringComparison.Ordinal); var symbols = model.LookupSymbols(position, name: "M"); Assert.Equal(2, symbols.Length); } [Fact, WorkItem(1078958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078958")] public void Bug1078958() { const string source = @" class C { static void Goo<T>() { /*<bind>*/T/*</bind>*/(); } static void T() { } }"; var symbols = GetLookupSymbols(source); Assert.True(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961() { const string source = @" class C { const int T = 42; static void Goo<T>(int x = /*<bind>*/T/*</bind>*/) { System.Console.Write(x); } static void Main() { Goo<object>(); } }"; var symbols = GetLookupSymbols(source); Assert.False(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_2() { const string source = @" class A : System.Attribute { public A(int i) { } } class C { const int T = 42; static void Goo<T>([A(/*<bind>*/T/*</bind>*/)] int x) { } }"; var symbols = GetLookupSymbols(source); Assert.False(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_3() { const string source = @" class A : System.Attribute { public A(int i) { } } class C { const int T = 42; [A(/*<bind>*/T/*</bind>*/)] static void Goo<T>(int x) { } }"; var symbols = GetLookupSymbols(source); Assert.False(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_4() { const string source = @" class A : System.Attribute { public A(int i) { } } class C { const int T = 42; static void Goo<[A(/*<bind>*/T/*</bind>*/)] T>(int x) { } }"; var symbols = GetLookupSymbols(source); Assert.False(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_5() { const string source = @" class C { class T { } static void Goo<T>(T x = default(/*<bind>*/T/*</bind>*/)) { System.Console.Write((object)x == null); } static void Main() { Goo<object>(); } }"; var symbols = GetLookupSymbols(source); Assert.True(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_6() { const string source = @" class C { class T { } static void Goo<T>(T x = default(/*<bind>*/T/*</bind>*/)) { System.Console.Write((object)x == null); } static void Main() { Goo<object>(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var position = GetPositionForBinding(tree); var symbols = model.LookupNamespacesAndTypes(position); Assert.True(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1091936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091936")] public void Bug1091936_1() { const string source = @" class Program { static object M(long l) { return null; } static object M(int i) { return null; } static void Main(string[] args) { (M(0))?.ToString(); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var ms = comp.GlobalNamespace.GetTypeMembers("Program").Single().GetMembers("M").OfType<MethodSymbol>(); var m = ms.Where(mm => mm.Parameters[0].Type.SpecialType == SpecialType.System_Int32).Single(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var call = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); var symbolInfo = model.GetSymbolInfo(call.Expression); Assert.NotEqual(default, symbolInfo); Assert.Equal(symbolInfo.Symbol.GetSymbol(), m); } [Fact, WorkItem(1091936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091936")] public void Bug1091936_2() { const string source = @" class Program { static object M = null; static void Main(string[] args) { M?.ToString(); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var m = comp.GlobalNamespace.GetTypeMembers("Program").Single().GetMembers("M").Single(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ConditionalAccessExpressionSyntax>().Single().Expression; var symbolInfo = model.GetSymbolInfo(node); Assert.NotEqual(default, symbolInfo); Assert.Equal(symbolInfo.Symbol.GetSymbol(), m); } [Fact, WorkItem(1091936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091936")] public void Bug1091936_3() { const string source = @" class Program { object M = null; static void Main(string[] args) { (new Program()).M?.ToString(); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var m = comp.GlobalNamespace.GetTypeMembers("Program").Single().GetMembers("M").Single(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ConditionalAccessExpressionSyntax>().Single().Expression; var symbolInfo = model.GetSymbolInfo(node); Assert.NotEqual(default, symbolInfo); Assert.Equal(symbolInfo.Symbol.GetSymbol(), m); } [Fact, WorkItem(1091936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091936")] public void Bug1091936_4() { const string source = @" class Program { static void Main(string[] args) { var y = (System.Linq.Enumerable.Select<string, int>(args, s => int.Parse(s)))?.ToString(); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<GenericNameSyntax>().Single(); var symbolInfo = model.GetSymbolInfo(node); Assert.NotEqual(default, symbolInfo); Assert.NotNull(symbolInfo.Symbol); } [Fact] public void GenericAttribute_LookupSymbols_01() { var source = @" using System; class Attr1<T> : Attribute { public Attr1(T t) { } } [Attr1<string>(""a"")] class C { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().Single(); var symbol = model.GetSymbolInfo(node); Assert.Equal("Attr1<System.String>..ctor(System.String t)", symbol.Symbol.ToTestDisplayString()); } [Fact] public void GenericAttribute_LookupSymbols_02() { var source = @" using System; class Attr1<T> : Attribute { public Attr1(T t) { } } [Attr1</*<bind>*/string/*</bind>*/>] class C { }"; var names = GetLookupNames(source); Assert.Contains("C", names); Assert.Contains("Attr1", names); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class GetSemanticInfoTests : SemanticModelTestBase { #region helpers internal List<string> GetLookupNames(string testSrc) { var parseOptions = TestOptions.Regular; var compilation = CreateCompilationWithMscorlib45(testSrc, parseOptions: parseOptions); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var position = testSrc.Contains("/*<bind>*/") ? GetPositionForBinding(tree) : GetPositionForBinding(testSrc); return model.LookupNames(position); } internal List<ISymbol> GetLookupSymbols(string testSrc, NamespaceOrTypeSymbol container = null, string name = null, int? arity = null, bool isScript = false, IEnumerable<string> globalUsings = null) { var tree = Parse(testSrc, options: isScript ? TestOptions.Script : TestOptions.Regular); var compilation = CreateCompilationWithMscorlib45(new[] { tree }, options: TestOptions.ReleaseDll.WithUsings(globalUsings)); var model = compilation.GetSemanticModel(tree); var position = testSrc.Contains("/*<bind>*/") ? GetPositionForBinding(tree) : GetPositionForBinding(testSrc); return model.LookupSymbols(position, container.GetPublicSymbol(), name).Where(s => !arity.HasValue || arity == s.GetSymbol().GetMemberArity()).ToList(); } #endregion helpers #region tests [Fact] public void LookupExpressionBodyProp01() { var text = @" class C { public int P => /*<bind>*/10/*</bind>*/; }"; var actual = GetLookupNames(text).ListToSortedString(); var expected_lookupNames = new List<string> { "C", "Equals", "Finalize", "GetHashCode", "GetType", "MemberwiseClone", "Microsoft", "P", "ReferenceEquals", "System", "ToString" }; Assert.Equal(expected_lookupNames.ListToSortedString(), actual); } [Fact] public void LookupExpressionBodiedMethod01() { var text = @" class C { public int M() => /*<bind>*/10/*</bind>*/; }"; var actual = GetLookupNames(text).ListToSortedString(); var expected_lookupNames = new List<string> { "C", "Equals", "Finalize", "GetHashCode", "GetType", "MemberwiseClone", "Microsoft", "M", "ReferenceEquals", "System", "ToString" }; Assert.Equal(expected_lookupNames.ListToSortedString(), actual); } [WorkItem(538262, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538262")] [Fact] public void LookupCompilationUnitSyntax() { var testSrc = @" /*<bind>*/ class Test { } /*</bind>*/ "; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupSymbols(testSrc); } [WorkItem(527476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527476")] [Fact] public void LookupConstrAndDestr() { var testSrc = @" class Test { Test() { } Test(int i) { } ~Test() { } static /*<bind>*/void/*</bind>*/Main() { } } "; List<string> expected_lookupNames = new List<string> { "Equals", "Finalize", "GetHashCode", "GetType", "Main", "MemberwiseClone", "Microsoft", "ReferenceEquals", "System", "Test", "ToString" }; List<string> expected_lookupSymbols = new List<string> { "Microsoft", "System", "System.Boolean System.Object.Equals(System.Object obj)", "System.Boolean System.Object.Equals(System.Object objA, System.Object objB)", "System.Boolean System.Object.ReferenceEquals(System.Object objA, System.Object objB)", "System.Int32 System.Object.GetHashCode()", "System.Object System.Object.MemberwiseClone()", "void System.Object.Finalize()", "System.String System.Object.ToString()", "System.Type System.Object.GetType()", "void Test.Finalize()", "void Test.Main()", "Test" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc); Assert.Equal(expected_lookupNames.ListToSortedString(), actual_lookupNames.ListToSortedString()); Assert.Equal(expected_lookupSymbols.ListToSortedString(), actual_lookupSymbols.ListToSortedString()); } [WorkItem(527477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527477")] [Fact] public void LookupNotYetDeclLocalVar() { var testSrc = @" class Test { static void Main() { int j = /*<bind>*/9/*</bind>*/ ; int k = 45; } } "; List<string> expected_in_lookupNames = new List<string> { "j", "k" }; List<string> expected_in_lookupSymbols = new List<string> { "j", "k" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); } [WorkItem(538301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538301")] [Fact] public void LookupByNameIncorrectArity() { var testSrc = @" class Test { public static void Main() { int i = /*<bind>*/10/*</bind>*/; } } "; // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupSymbols(testSrc, name: "i", arity: 1); var actual_lookupSymbols = GetLookupSymbols(testSrc, name: "i", arity: 1); Assert.Empty(actual_lookupSymbols); } [WorkItem(538310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538310")] [Fact] public void LookupInProtectedNonNestedType() { var testSrc = @" protected class MyClass { /*<bind>*/public static void Main()/*</bind>*/ {} } "; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupSymbols(testSrc); } [WorkItem(538311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538311")] [Fact] public void LookupClassContainsVolatileEnumField() { var testSrc = @" enum E{} class Test { static volatile E x; static /*<bind>*/int/*</bind>*/ Main() { return 1; } } "; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags GetLookupSymbols(testSrc); } [WorkItem(538312, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538312")] [Fact] public void LookupUsingAlias() { var testSrc = @" using T2 = System.IO; namespace T1 { class Test { static /*<bind>*/void/*</bind>*/ Main() { } } } "; List<string> expected_in_lookupNames = new List<string> { "T1", "T2" }; List<string> expected_in_lookupSymbols = new List<string> { "T1", "T2" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); } [WorkItem(538313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538313")] [Fact] public void LookupUsingNameSpaceContSameTypeNames() { var testSrc = @" namespace T1 { using T2; public class Test { static /*<bind>*/int/*</bind>*/ Main() { return 1; } } } namespace T2 { public class Test { } } "; List<string> expected_in_lookupNames = new List<string> { "T1", "T2", "Test" }; List<string> expected_in_lookupSymbols = new List<string> { "T1", "T2", "T1.Test", //"T2.Test" this is hidden by T1.Test }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupNames[2], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[2], actual_lookupSymbols_as_string); } [WorkItem(527489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527489")] [Fact] public void LookupMustNotBeNonInvocableMember() { var testSrc = @" class Test { public void TestMeth(int i, int j) { int m = /*<bind>*/10/*</bind>*/; } } "; List<string> expected_in_lookupNames = new List<string> { "TestMeth", "i", "j", "m", "System", "Microsoft", "Test" }; List<string> expected_in_lookupSymbols = new List<string> { "void Test.TestMeth(System.Int32 i, System.Int32 j)", "System.Int32 i", "System.Int32 j", "System.Int32 m", "System", "Microsoft", "Test" }; var comp = CreateCompilation(testSrc); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var position = GetPositionForBinding(tree); var binder = ((CSharpSemanticModel)model).GetEnclosingBinder(position); // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var info = LookupSymbolsInfo.GetInstance(); binder.AddLookupSymbolsInfo(info, LookupOptions.MustBeInvocableIfMember); var actual_lookupNames = info.Names; // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = actual_lookupNames.SelectMany(name => { var lookupResult = LookupResult.GetInstance(); HashSet<DiagnosticInfo> useSiteDiagnostics = null; binder.LookupSymbolsSimpleName( lookupResult, qualifierOpt: null, plainName: name, arity: 0, basesBeingResolved: null, options: LookupOptions.MustBeInvocableIfMember, diagnose: false, useSiteDiagnostics: ref useSiteDiagnostics); Assert.Null(useSiteDiagnostics); Assert.True(lookupResult.IsMultiViable || lookupResult.Kind == LookupResultKind.NotReferencable); var result = lookupResult.Symbols.ToArray(); lookupResult.Free(); return result; }); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupNames[2], actual_lookupNames); Assert.Contains(expected_in_lookupNames[3], actual_lookupNames); Assert.Contains(expected_in_lookupNames[4], actual_lookupNames); Assert.Contains(expected_in_lookupNames[5], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[2], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[3], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[4], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[5], actual_lookupSymbols_as_string); info.Free(); } [WorkItem(538365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538365")] [Fact] public void LookupWithNameZeroArity() { var testSrc = @" class Test { private void F<T>(T i) { } private void F<T, U>(T i, U j) { } private void F(int i) { } private void F(int i, int j) { } public static /*<bind>*/void/*</bind>*/ Main() { } } "; List<string> expected_in_lookupNames = new List<string> { "F" }; List<string> expected_in_lookupSymbols = new List<string> { "void Test.F(System.Int32 i)", "void Test.F(System.Int32 i, System.Int32 j)" }; List<string> not_expected_in_lookupSymbols = new List<string> { "void Test.F<T>(T i)", "void Test.F<T, U>(T i, U j)" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc, name: "F", arity: 0); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Equal(2, actual_lookupSymbols.Count); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.DoesNotContain(not_expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.DoesNotContain(not_expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); } [WorkItem(538365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538365")] [Fact] public void LookupWithNameZeroArityAndLookupOptionsAllMethods() { var testSrc = @" class Test { public void F<T>(T i) { } public void F<T, U>(T i, U j) { } public void F(int i) { } public void F(int i, int j) { } public void Main() { return; } } "; List<string> expected_in_lookupNames = new List<string> { "F" }; List<string> expected_in_lookupSymbols = new List<string> { "void Test.F(System.Int32 i)", "void Test.F(System.Int32 i, System.Int32 j)", "void Test.F<T>(T i)", "void Test.F<T, U>(T i, U j)" }; // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var comp = CreateCompilation(testSrc); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var position = testSrc.IndexOf("return", StringComparison.Ordinal); var binder = ((CSharpSemanticModel)model).GetEnclosingBinder(position); var lookupResult = LookupResult.GetInstance(); HashSet<DiagnosticInfo> useSiteDiagnostics = null; binder.LookupSymbolsSimpleName(lookupResult, qualifierOpt: null, plainName: "F", arity: 0, basesBeingResolved: null, options: LookupOptions.AllMethodsOnArityZero, diagnose: false, useSiteDiagnostics: ref useSiteDiagnostics); Assert.Null(useSiteDiagnostics); Assert.True(lookupResult.IsMultiViable); var actual_lookupSymbols_as_string = lookupResult.Symbols.Select(e => e.ToTestDisplayString()).ToArray(); lookupResult.Free(); // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = model.LookupNames(position); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Equal(4, actual_lookupSymbols_as_string.Length); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[2], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[3], actual_lookupSymbols_as_string); } [WorkItem(539160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539160")] [Fact] public void LookupExcludeInAppropriateNS() { var testSrc = @" class Test { public static /*<bind>*/void/*</bind>*/ Main() { } } "; var srcTrees = new SyntaxTree[] { Parse(testSrc) }; var refs = new MetadataReference[] { SystemDataRef }; CSharpCompilation compilation = CSharpCompilation.Create("Test.dll", srcTrees, refs); var tree = srcTrees[0]; var model = compilation.GetSemanticModel(tree); List<string> not_expected_in_lookup = new List<string> { "<CrtImplementationDetails>", "<CppImplementationDetails>" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = model.LookupNames(GetPositionForBinding(tree), null).ToList(); var actual_lookupNames_ignoreAcc = model.LookupNames(GetPositionForBinding(tree), null).ToList(); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = model.LookupSymbols(GetPositionForBinding(tree)); var actual_lookupSymbols_ignoreAcc = model.LookupSymbols(GetPositionForBinding(tree)); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); var actual_lookupSymbols_ignoreAcc_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.DoesNotContain(not_expected_in_lookup[0], actual_lookupNames); Assert.DoesNotContain(not_expected_in_lookup[1], actual_lookupNames); Assert.DoesNotContain(not_expected_in_lookup[0], actual_lookupNames_ignoreAcc); Assert.DoesNotContain(not_expected_in_lookup[1], actual_lookupNames_ignoreAcc); Assert.DoesNotContain(not_expected_in_lookup[0], actual_lookupSymbols_as_string); Assert.DoesNotContain(not_expected_in_lookup[1], actual_lookupSymbols_as_string); Assert.DoesNotContain(not_expected_in_lookup[0], actual_lookupSymbols_ignoreAcc_as_string); Assert.DoesNotContain(not_expected_in_lookup[1], actual_lookupSymbols_ignoreAcc_as_string); } /// <summary> /// Verify that there's a way to look up only the members of the base type that are visible /// from the current type. /// </summary> [Fact] [WorkItem(539814, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539814")] public void LookupProtectedInBase() { var testSrc = @" class A { private void Hidden() { } protected void Goo() { } } class B : A { void Bar() { /*<bind>*/base/*</bind>*/.Goo(); } } "; var srcTrees = new SyntaxTree[] { Parse(testSrc) }; var refs = new MetadataReference[] { SystemDataRef }; CSharpCompilation compilation = CSharpCompilation.Create("Test.dll", srcTrees, refs); var tree = srcTrees[0]; var model = compilation.GetSemanticModel(tree); var baseExprNode = GetSyntaxNodeForBinding(GetSyntaxNodeList(tree)); Assert.Equal("base", baseExprNode.ToString()); var baseExprLocation = baseExprNode.SpanStart; Assert.NotEqual(0, baseExprLocation); var baseExprInfo = model.GetTypeInfo((ExpressionSyntax)baseExprNode); Assert.NotEqual(default, baseExprInfo); var baseExprType = (INamedTypeSymbol)baseExprInfo.Type; Assert.NotNull(baseExprType); Assert.Equal("A", baseExprType.Name); var symbols = model.LookupBaseMembers(baseExprLocation); Assert.Equal("void A.Goo()", symbols.Single().ToTestDisplayString()); var names = model.LookupNames(baseExprLocation, useBaseReferenceAccessibility: true); Assert.Equal("Goo", names.Single()); } [WorkItem(528263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528263")] [Fact] public void LookupStartOfScopeMethodBody() { var testSrc = @"public class start { static public void Main() /*pos*/{ int num=10; } "; List<string> expected_in_lookupNames = new List<string> { "Main", "start", "num" }; List<string> expected_in_lookupSymbols = new List<string> { "void start.Main()", "start", "System.Int32 num" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Equal('{', testSrc[GetPositionForBinding(testSrc)]); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupNames[2], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[2], actual_lookupSymbols_as_string); } [WorkItem(528263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528263")] [Fact] public void LookupEndOfScopeMethodBody() { var testSrc = @"public class start { static public void Main() { int num=10; /*pos*/} "; List<string> expected_in_lookupNames = new List<string> { "Main", "start" }; List<string> expected_in_lookupSymbols = new List<string> { "void start.Main()", "start" }; List<string> not_expected_in_lookupNames = new List<string> { "num" }; List<string> not_expected_in_lookupSymbols = new List<string> { "System.Int32 num" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Equal('}', testSrc[GetPositionForBinding(testSrc)]); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.DoesNotContain(not_expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.DoesNotContain(not_expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(540888, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540888")] [Fact] public void LookupLambdaParamInConstructorInitializer() { var testSrc = @" using System; class MyClass { public MyClass(Func<int, int> x) { } public MyClass(int j, int k) : this(lambdaParam => /*pos*/lambdaParam) { } } "; List<string> expected_in_lookupNames = new List<string> { "j", "k", "lambdaParam" }; List<string> expected_in_lookupSymbols = new List<string> { "System.Int32 j", "System.Int32 k", "System.Int32 lambdaParam" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupNames[2], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[2], actual_lookupSymbols_as_string); } [WorkItem(540893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540893")] [Fact] public void TestForLocalVarDeclLookupAtForKeywordInForStmt() { var testSrc = @" class MyClass { static void Main() { /*pos*/for (int forVar = 10; forVar < 10; forVar++) { } } } "; List<string> not_expected_in_lookupNames = new List<string> { "forVar" }; List<string> not_expected_in_lookupSymbols = new List<string> { "System.Int32 forVar", }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.DoesNotContain(not_expected_in_lookupNames[0], actual_lookupNames); Assert.DoesNotContain(not_expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(540894, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540894")] [Fact] public void TestForeachIterVarLookupAtForeachKeyword() { var testSrc = @" class MyClass { static void Main() { System.Collections.Generic.List<int> listOfNumbers = new System.Collections.Generic.List<int>(); /*pos*/foreach (int number in listOfNumbers) { } } } "; List<string> not_expected_in_lookupNames = new List<string> { "number" }; List<string> not_expected_in_lookupSymbols = new List<string> { "System.Int32 number", }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.DoesNotContain(not_expected_in_lookupNames[0], actual_lookupNames); Assert.DoesNotContain(not_expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(540912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540912")] [Fact] public void TestLookupInConstrInitIncompleteConstrDecl() { var testSrc = @" class MyClass { public MyClass(int x) { } public MyClass(int j, int k) :this(/*pos*/k) "; List<string> expected_in_lookupNames = new List<string> { "j", "k" }; List<string> expected_in_lookupSymbols = new List<string> { "System.Int32 j", "System.Int32 k", }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupNames[1], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); Assert.Contains(expected_in_lookupSymbols[1], actual_lookupSymbols_as_string); } [WorkItem(541060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541060")] [Fact] public void TestLookupInsideIncompleteNestedLambdaBody() { var testSrc = @" class C { C() { D(() => { D(() => { }/*pos*/ "; List<string> expected_in_lookupNames = new List<string> { "C" }; List<string> expected_in_lookupSymbols = new List<string> { "C" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.NotEmpty(actual_lookupNames); Assert.NotEmpty(actual_lookupSymbols); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(541611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541611")] [Fact] public void LookupLambdaInsideAttributeUsage() { var testSrc = @" using System; class Program { [ObsoleteAttribute(x=>x/*pos*/ static void Main(string[] args) { } } "; List<string> expected_in_lookupNames = new List<string> { "x" }; List<string> expected_in_lookupSymbols = new List<string> { "? x" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [Fact] public void LookupInsideLocalFunctionAttribute() { var testSrc = @" using System; class Program { const int w = 0451; void M() { int x = 42; const int y = 123; [ObsoleteAttribute(/*pos*/ static void local1(int z) { } } } "; var lookupNames = GetLookupNames(testSrc); var lookupSymbols = GetLookupSymbols(testSrc).Select(e => e.ToTestDisplayString()).ToList(); Assert.Contains("w", lookupNames); Assert.Contains("y", lookupNames); Assert.Contains("System.Int32 Program.w", lookupSymbols); Assert.Contains("System.Int32 y", lookupSymbols); } [Fact] public void LookupInsideLambdaAttribute() { var testSrc = @" using System; class Program { const int w = 0451; void M() { int x = 42; const int y = 123; Action<int> a = [ObsoleteAttribute(/*pos*/ (int z) => { }; } } "; var lookupNames = GetLookupNames(testSrc); var lookupSymbols = GetLookupSymbols(testSrc).Select(e => e.ToTestDisplayString()).ToList(); Assert.Contains("w", lookupNames); Assert.Contains("y", lookupNames); Assert.Contains("System.Int32 Program.w", lookupSymbols); Assert.Contains("System.Int32 y", lookupSymbols); } [Fact] public void LookupInsideIncompleteStatementAttribute() { var testSrc = @" using System; class Program { const int w = 0451; void M() { int x = 42; const int y = 123; [ObsoleteAttribute(/*pos*/ int } } "; var lookupNames = GetLookupNames(testSrc); var lookupSymbols = GetLookupSymbols(testSrc).Select(e => e.ToTestDisplayString()).ToList(); Assert.Contains("w", lookupNames); Assert.Contains("y", lookupNames); Assert.Contains("System.Int32 Program.w", lookupSymbols); Assert.Contains("System.Int32 y", lookupSymbols); } [WorkItem(541909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541909")] [Fact] public void LookupFromRangeVariableAfterFromClause() { var testSrc = @" class Program { static void Main(string[] args) { var q = from i in new int[] { 4, 5 } where /*pos*/ } } "; List<string> expected_in_lookupNames = new List<string> { "i" }; List<string> expected_in_lookupSymbols = new List<string> { "? i" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(541921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541921")] [Fact] public void LookupFromRangeVariableInsideNestedFromClause() { var testSrc = @" class Program { static void Main(string[] args) { string[] strings = { }; var query = from s in strings from s1 in /*pos*/ } } "; List<string> expected_in_lookupNames = new List<string> { "s" }; List<string> expected_in_lookupSymbols = new List<string> { "? s" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(541919, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541919")] [Fact] public void LookupLambdaVariableInQueryExpr() { var testSrc = @" class Program { static void Main(string[] args) { Func<int, IEnumerable<int>> f1 = (x) => from n in /*pos*/ } } "; List<string> expected_in_lookupNames = new List<string> { "x" }; List<string> expected_in_lookupSymbols = new List<string> { "x" }; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.Name); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [WorkItem(541910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541910")] [Fact] public void LookupInsideQueryExprOutsideTypeDecl() { var testSrc = @"var q = from i in/*pos*/ f"; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.NotEmpty(actual_lookupNames); Assert.NotEmpty(actual_lookupSymbols_as_string); } [WorkItem(542203, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542203")] [Fact] public void LookupInsideQueryExprInMalformedFromClause() { var testSrc = @" using System; using System.Linq; class Program { static void Main(string[] args) { int[] numbers = new int[] { 4, 5 }; var q1 = from I<x/*pos*/ in numbers.Where(x1 => x1 > 2) select x; } } "; // Get the list of LookupNames at the location at the end of the /*pos*/ tag var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location at the end of the /*pos*/ tag var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToTestDisplayString()); Assert.NotEmpty(actual_lookupNames); Assert.NotEmpty(actual_lookupSymbols_as_string); } [WorkItem(543295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543295")] [Fact] public void MultipleOverlappingInterfaceConstraints() { var testSrc = @"public interface IEntity { object Key { get; } } public interface INumberedProjectChild : IEntity { } public interface IAggregateRoot : IEntity { } public interface ISpecification<TCandidate> { void IsSatisfiedBy(TCandidate candidate); } public abstract class Specification<TCandidate> : ISpecification<TCandidate> { public abstract void IsSatisfiedBy(TCandidate candidate); } public class NumberSpecification<TCandidate> : Specification<TCandidate> where TCandidate : IAggregateRoot, INumberedProjectChild { public override void IsSatisfiedBy(TCandidate candidate) { var key = candidate.Key; } }"; CreateCompilation(testSrc).VerifyDiagnostics(); } [WorkItem(529406, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529406")] [Fact] public void FixedPointerInitializer() { var testSrc = @" class Program { static int num = 0; unsafe static void Main(string[] args) { fixed(int* p1 = /*pos*/&num, p2 = &num) { } } } "; List<string> expected_in_lookupNames = new List<string> { "p2" }; List<string> expected_in_lookupSymbols = new List<string> { "p2" }; // Get the list of LookupNames at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupNames = GetLookupNames(testSrc); // Get the list of LookupSymbols at the location of the CSharpSyntaxNode enclosed within the <bind> </bind> tags var actual_lookupSymbols = GetLookupSymbols(testSrc); var actual_lookupSymbols_as_string = actual_lookupSymbols.Select(e => e.ToString()).ToList(); Assert.Contains(expected_in_lookupNames[0], actual_lookupNames); Assert.Contains(expected_in_lookupSymbols[0], actual_lookupSymbols_as_string); } [Fact] public void LookupSymbolsAtEOF() { var source = @"class { }"; var tree = Parse(source); var comp = CreateCompilationWithMscorlib40(new[] { tree }); var model = comp.GetSemanticModel(tree); var eof = tree.GetCompilationUnitRoot().FullSpan.End; Assert.NotEqual(0, eof); var symbols = model.LookupSymbols(eof); CompilationUtils.CheckISymbols(symbols, "System", "Microsoft"); } [Fact, WorkItem(546523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546523")] public void TestLookupSymbolsNestedNamespacesNotImportedByUsings_01() { var source = @" using System; class Program { static void Main(string[] args) { /*pos*/ } } "; // Get the list of LookupSymbols at the location of the CSharpSyntaxNode var actual_lookupSymbols = GetLookupSymbols(source); // Verify nested namespaces *are not* imported. var systemNS = (INamespaceSymbol)actual_lookupSymbols.Where((sym) => sym.Name.Equals("System") && sym.Kind == SymbolKind.Namespace).Single(); INamespaceSymbol systemXmlNS = systemNS.GetNestedNamespace("Xml"); Assert.DoesNotContain(systemXmlNS, actual_lookupSymbols); } [Fact, WorkItem(546523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546523")] public void TestLookupSymbolsNestedNamespacesNotImportedByUsings_02() { var usings = new[] { "using X;" }; var source = @" using aliasY = X.Y; namespace X { namespace Y { public class InnerZ { } } public class Z { } public static class StaticZ { } } public class A { public class B { } } class Program { public static void Main() { /*pos*/ } } "; // Get the list of LookupSymbols at the location of the CSharpSyntaxNode var actual_lookupSymbols = GetLookupSymbols(usings.ToString() + source, isScript: false); TestLookupSymbolsNestedNamespaces(actual_lookupSymbols); actual_lookupSymbols = GetLookupSymbols(source, isScript: true, globalUsings: usings); TestLookupSymbolsNestedNamespaces(actual_lookupSymbols); Action<ModuleSymbol> validator = (module) => { NamespaceSymbol globalNS = module.GlobalNamespace; Assert.Equal(1, globalNS.GetMembers("X").Length); Assert.Equal(1, globalNS.GetMembers("A").Length); Assert.Equal(1, globalNS.GetMembers("Program").Length); Assert.Empty(globalNS.GetMembers("Y")); Assert.Empty(globalNS.GetMembers("Z")); Assert.Empty(globalNS.GetMembers("StaticZ")); Assert.Empty(globalNS.GetMembers("B")); }; CompileAndVerify(source, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] [WorkItem(530826, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530826")] public void TestAmbiguousInterfaceLookup() { var source = @"delegate void D(); interface I1 { void M(); } interface I2 { event D M; } interface I3 : I1, I2 { } public class P : I3 { event D I2.M { add { } remove { } } void I1.M() { } } class Q : P { static int Main(string[] args) { Q p = new Q(); I3 m = p; if (m.M is object) {} return 0; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ExpressionSyntax>().Where(n => n.ToString() == "m.M").Single(); var symbolInfo = model.GetSymbolInfo(node); Assert.Equal("void I1.M()", symbolInfo.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); var node2 = (ExpressionSyntax)SyntaxFactory.SyntaxTree(node).GetRoot(); symbolInfo = model.GetSpeculativeSymbolInfo(node.Position, node2, SpeculativeBindingOption.BindAsExpression); Assert.Equal("void I1.M()", symbolInfo.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); } [Fact] public void TestLookupVerbatimVar() { var source = "class C { public static void Main() { @var v = 1; } }"; CreateCompilation(source).VerifyDiagnostics( // (1,39): error CS0246: The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?) // class C { public static void Main() { @var v = 1; } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "@var").WithArguments("var").WithLocation(1, 39) ); } private void TestLookupSymbolsNestedNamespaces(List<ISymbol> actual_lookupSymbols) { var namespaceX = (INamespaceSymbol)actual_lookupSymbols.Where((sym) => sym.Name.Equals("X") && sym.Kind == SymbolKind.Namespace).Single(); // Verify nested namespaces within namespace X *are not* present in lookup symbols. INamespaceSymbol namespaceY = namespaceX.GetNestedNamespace("Y"); Assert.DoesNotContain(namespaceY, actual_lookupSymbols); INamedTypeSymbol typeInnerZ = namespaceY.GetTypeMembers("InnerZ").Single(); Assert.DoesNotContain(typeInnerZ, actual_lookupSymbols); // Verify nested types *are not* present in lookup symbols. var typeA = (INamedTypeSymbol)actual_lookupSymbols.Where((sym) => sym.Name.Equals("A") && sym.Kind == SymbolKind.NamedType).Single(); INamedTypeSymbol typeB = typeA.GetTypeMembers("B").Single(); Assert.DoesNotContain(typeB, actual_lookupSymbols); // Verify aliases to nested namespaces within namespace X *are* present in lookup symbols. var aliasY = (IAliasSymbol)actual_lookupSymbols.Where((sym) => sym.Name.Equals("aliasY") && sym.Kind == SymbolKind.Alias).Single(); Assert.Contains(aliasY, actual_lookupSymbols); } [Fact] public void ExtensionMethodCall() { var source = @"static class E { internal static void F(this object o) { } } class C { void M() { /*<bind>*/this.F/*</bind>*/(); } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); compilation.VerifyDiagnostics(); var exprs = GetExprSyntaxList(tree); var expr = GetExprSyntaxForBinding(exprs); var method = (IMethodSymbol)model.GetSymbolInfo(expr).Symbol; Assert.Equal("object.F()", method.ToDisplayString()); var reducedFrom = method.ReducedFrom; Assert.NotNull(reducedFrom); Assert.Equal("E.F(object)", reducedFrom.ToDisplayString()); } [WorkItem(3651, "https://github.com/dotnet/roslyn/issues/3651")] [Fact] public void ExtensionMethodDelegateCreation() { var source = @"static class E { internal static void F(this object o) { } } class C { void M() { (new System.Action<object>(/*<bind>*/E.F/*</bind>*/))(this); (new System.Action(/*<bind1>*/this.F/*</bind1>*/))(); } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); compilation.VerifyDiagnostics(); var exprs = GetExprSyntaxList(tree); var expr = GetExprSyntaxForBinding(exprs, index: 0); var method = (IMethodSymbol)model.GetSymbolInfo(expr).Symbol; Assert.Null(method.ReducedFrom); Assert.Equal("E.F(object)", method.ToDisplayString()); expr = GetExprSyntaxForBinding(exprs, index: 1); method = (IMethodSymbol)model.GetSymbolInfo(expr).Symbol; Assert.Equal("object.F()", method.ToDisplayString()); var reducedFrom = method.ReducedFrom; Assert.NotNull(reducedFrom); Assert.Equal("E.F(object)", reducedFrom.ToDisplayString()); } [WorkItem(7493, "https://github.com/dotnet/roslyn/issues/7493")] [Fact] public void GenericNameLookup() { var source = @"using A = List<int>;"; var compilation = CreateCompilation(source).VerifyDiagnostics( // (1,11): error CS0246: The type or namespace name 'List<>' could not be found (are you missing a using directive or an assembly reference?) // using A = List<int>; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "List<int>").WithArguments("List<>").WithLocation(1, 11), // (1,1): hidden CS8019: Unnecessary using directive. // using A = List<int>; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using A = List<int>;").WithLocation(1, 1)); } #endregion tests #region regressions [Fact] [WorkItem(552472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552472")] public void BrokenCode01() { var source = @"Dele<Str> d3 = delegate (Dele<Str> d2 = delegate () { returne<double> d1 = delegate () { return 1; }; { int result = 0; Dels Test : Base"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); SemanticModel imodel = model; var node = tree.GetRoot().DescendantNodes().Where(n => n.ToString() == "returne<double>").First(); imodel.GetSymbolInfo(node, default(CancellationToken)); } [Fact] [WorkItem(552472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552472")] public void BrokenCode02() { var source = @"public delegate D D(D d); class Program { public D d3 = delegate(D d2 = delegate { System.Object x = 3; return null; }) {}; public static void Main(string[] args) { } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); SemanticModel imodel = model; var node = tree.GetRoot().DescendantNodes().Where(n => n.ToString() == "System.Object").First(); imodel.GetSymbolInfo(node, default(CancellationToken)); } [Fact] public void InterfaceDiamondHiding() { var source = @" interface T { int P { get; set; } int Q { get; set; } } interface L : T { new int P { get; set; } } interface R : T { new int Q { get; set; } } interface B : L, R { } class Test { int M(B b) { return b.P + b.Q; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var interfaceT = global.GetMember<NamedTypeSymbol>("T"); var interfaceL = global.GetMember<NamedTypeSymbol>("L"); var interfaceR = global.GetMember<NamedTypeSymbol>("R"); var interfaceB = global.GetMember<NamedTypeSymbol>("B"); var propertyTP = interfaceT.GetMember<PropertySymbol>("P"); var propertyTQ = interfaceT.GetMember<PropertySymbol>("Q"); var propertyLP = interfaceL.GetMember<PropertySymbol>("P"); var propertyRQ = interfaceR.GetMember<PropertySymbol>("Q"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var syntaxes = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().ToArray(); Assert.Equal(2, syntaxes.Length); // The properties in T are hidden - we bind to the properties on more-derived interfaces Assert.Equal(propertyLP.GetPublicSymbol(), model.GetSymbolInfo(syntaxes[0]).Symbol); Assert.Equal(propertyRQ.GetPublicSymbol(), model.GetSymbolInfo(syntaxes[1]).Symbol); int position = source.IndexOf("return", StringComparison.Ordinal); // We do the right thing with diamond inheritance (i.e. member is hidden along all paths // if it is hidden along any path) because we visit base interfaces in topological order. Assert.Equal(propertyLP.GetPublicSymbol(), model.LookupSymbols(position, interfaceB.GetPublicSymbol(), "P").Single()); Assert.Equal(propertyRQ.GetPublicSymbol(), model.LookupSymbols(position, interfaceB.GetPublicSymbol(), "Q").Single()); } [Fact] public void SemanticModel_OnlyInvalid() { var source = @" public class C { void M() { return; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); int position = source.IndexOf("return", StringComparison.Ordinal); var symbols = model.LookupNamespacesAndTypes(position, name: "M"); Assert.Equal(0, symbols.Length); } [Fact] public void SemanticModel_InvalidHidingValid() { var source = @" public class C<T> { public class Inner { void T() { return; } } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var classC = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var methodT = classC.GetMember<NamedTypeSymbol>("Inner").GetMember<MethodSymbol>("T"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); int position = source.IndexOf("return", StringComparison.Ordinal); var symbols = model.LookupSymbols(position, name: "T"); Assert.Equal(methodT.GetPublicSymbol(), symbols.Single()); // Hides type parameter. symbols = model.LookupNamespacesAndTypes(position, name: "T"); Assert.Equal(classC.TypeParameters.Single().GetPublicSymbol(), symbols.Single()); // Ignore intervening method. } [Fact] public void SemanticModel_MultipleValid() { var source = @" public class Outer { void M(int x) { } void M() { return; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); int position = source.IndexOf("return", StringComparison.Ordinal); var symbols = model.LookupSymbols(position, name: "M"); Assert.Equal(2, symbols.Length); } [Fact, WorkItem(1078958, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078958")] public void Bug1078958() { const string source = @" class C { static void Goo<T>() { /*<bind>*/T/*</bind>*/(); } static void T() { } }"; var symbols = GetLookupSymbols(source); Assert.True(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961() { const string source = @" class C { const int T = 42; static void Goo<T>(int x = /*<bind>*/T/*</bind>*/) { System.Console.Write(x); } static void Main() { Goo<object>(); } }"; var symbols = GetLookupSymbols(source); Assert.False(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_2() { const string source = @" class A : System.Attribute { public A(int i) { } } class C { const int T = 42; static void Goo<T>([A(/*<bind>*/T/*</bind>*/)] int x) { } }"; var symbols = GetLookupSymbols(source); Assert.False(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_3() { const string source = @" class A : System.Attribute { public A(int i) { } } class C { const int T = 42; [A(/*<bind>*/T/*</bind>*/)] static void Goo<T>(int x) { } }"; var symbols = GetLookupSymbols(source); Assert.False(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_4() { const string source = @" class A : System.Attribute { public A(int i) { } } class C { const int T = 42; static void Goo<[A(/*<bind>*/T/*</bind>*/)] T>(int x) { } }"; var symbols = GetLookupSymbols(source); Assert.False(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_5() { const string source = @" class C { class T { } static void Goo<T>(T x = default(/*<bind>*/T/*</bind>*/)) { System.Console.Write((object)x == null); } static void Main() { Goo<object>(); } }"; var symbols = GetLookupSymbols(source); Assert.True(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1078961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1078961")] public void Bug1078961_6() { const string source = @" class C { class T { } static void Goo<T>(T x = default(/*<bind>*/T/*</bind>*/)) { System.Console.Write((object)x == null); } static void Main() { Goo<object>(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var position = GetPositionForBinding(tree); var symbols = model.LookupNamespacesAndTypes(position); Assert.True(symbols.Any(s => s.Kind == SymbolKind.TypeParameter)); } [Fact, WorkItem(1091936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091936")] public void Bug1091936_1() { const string source = @" class Program { static object M(long l) { return null; } static object M(int i) { return null; } static void Main(string[] args) { (M(0))?.ToString(); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var ms = comp.GlobalNamespace.GetTypeMembers("Program").Single().GetMembers("M").OfType<MethodSymbol>(); var m = ms.Where(mm => mm.Parameters[0].Type.SpecialType == SpecialType.System_Int32).Single(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var call = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); var symbolInfo = model.GetSymbolInfo(call.Expression); Assert.NotEqual(default, symbolInfo); Assert.Equal(symbolInfo.Symbol.GetSymbol(), m); } [Fact, WorkItem(1091936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091936")] public void Bug1091936_2() { const string source = @" class Program { static object M = null; static void Main(string[] args) { M?.ToString(); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var m = comp.GlobalNamespace.GetTypeMembers("Program").Single().GetMembers("M").Single(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ConditionalAccessExpressionSyntax>().Single().Expression; var symbolInfo = model.GetSymbolInfo(node); Assert.NotEqual(default, symbolInfo); Assert.Equal(symbolInfo.Symbol.GetSymbol(), m); } [Fact, WorkItem(1091936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091936")] public void Bug1091936_3() { const string source = @" class Program { object M = null; static void Main(string[] args) { (new Program()).M?.ToString(); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var m = comp.GlobalNamespace.GetTypeMembers("Program").Single().GetMembers("M").Single(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<ConditionalAccessExpressionSyntax>().Single().Expression; var symbolInfo = model.GetSymbolInfo(node); Assert.NotEqual(default, symbolInfo); Assert.Equal(symbolInfo.Symbol.GetSymbol(), m); } [Fact, WorkItem(1091936, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091936")] public void Bug1091936_4() { const string source = @" class Program { static void Main(string[] args) { var y = (System.Linq.Enumerable.Select<string, int>(args, s => int.Parse(s)))?.ToString(); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<GenericNameSyntax>().Single(); var symbolInfo = model.GetSymbolInfo(node); Assert.NotEqual(default, symbolInfo); Assert.NotNull(symbolInfo.Symbol); } [Fact] public void GenericAttribute_LookupSymbols_01() { var source = @" using System; class Attr1<T> : Attribute { public Attr1(T t) { } } [Attr1<string>(""a"")] class C { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().Single(); var symbol = model.GetSymbolInfo(node); Assert.Equal("Attr1<System.String>..ctor(System.String t)", symbol.Symbol.ToTestDisplayString()); } [Fact] public void GenericAttribute_LookupSymbols_02() { var source = @" using System; class Attr1<T> : Attribute { public Attr1(T t) { } } [Attr1</*<bind>*/string/*</bind>*/>] class C { }"; var names = GetLookupNames(source); Assert.Contains("C", names); Assert.Contains("Attr1", names); } #endregion } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VSPackage.zh-Hans.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="zh-Hans" original="../VSPackage.resx"> <body> <trans-unit id="110"> <source>Roslyn Diagnostics</source> <target state="translated">Roslyn 诊断</target> <note /> </trans-unit> <trans-unit id="112"> <source>Roslyn Diagnostics</source> <target state="translated">Roslyn 诊断</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hans" original="../VSPackage.resx"> <body> <trans-unit id="110"> <source>Roslyn Diagnostics</source> <target state="translated">Roslyn 诊断</target> <note /> </trans-unit> <trans-unit id="112"> <source>Roslyn Diagnostics</source> <target state="translated">Roslyn 诊断</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/Core/MSBuildTaskTests/MapSourceRootTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests { public sealed class MapSourceRootsTests { private string InspectSourceRoot(ITaskItem sourceRoot) => $"'{sourceRoot.ItemSpec}'" + $" SourceControl='{sourceRoot.GetMetadata("SourceControl")}'" + $" RevisionId='{sourceRoot.GetMetadata("RevisionId")}'" + $" NestedRoot='{sourceRoot.GetMetadata("NestedRoot")}'" + $" ContainingRoot='{sourceRoot.GetMetadata("ContainingRoot")}'" + $" MappedPath='{sourceRoot.GetMetadata("MappedPath")}'" + $" SourceLinkUrl='{sourceRoot.GetMetadata("SourceLinkUrl")}'"; [Fact] public void BasicMapping() { var engine = new MockEngine(); var task = new MapSourceRoots { BuildEngine = engine, SourceRoots = new[] { new TaskItem(@"c:\packages\SourcePackage1\"), new TaskItem(@"/packages/SourcePackage2/"), new TaskItem(@"c:\MyProjects\MyProject\", new Dictionary<string, string> { { "SourceControl", "Git" }, }), new TaskItem(@"c:\MyProjects\MyProject\a\b\", new Dictionary<string, string> { { "SourceControl", "Git" }, { "NestedRoot", "a/b" }, { "ContainingRoot", @"c:\MyProjects\MyProject\" }, { "some metadata", "some value" }, }), }, Deterministic = true }; bool result = task.Execute(); AssertEx.AssertEqualToleratingWhitespaceDifferences("", engine.Log); RoslynDebug.Assert(task.MappedSourceRoots is object); Assert.Equal(4, task.MappedSourceRoots.Length); Assert.Equal(Utilities.FixFilePath(@"c:\packages\SourcePackage1\"), task.MappedSourceRoots[0].ItemSpec); Assert.Equal(@"/_1/", task.MappedSourceRoots[0].GetMetadata("MappedPath")); Assert.Equal(Utilities.FixFilePath(@"/packages/SourcePackage2/"), task.MappedSourceRoots[1].ItemSpec); Assert.Equal(@"/_2/", task.MappedSourceRoots[1].GetMetadata("MappedPath")); Assert.Equal(Utilities.FixFilePath(@"c:\MyProjects\MyProject\"), task.MappedSourceRoots[2].ItemSpec); Assert.Equal(@"/_/", task.MappedSourceRoots[2].GetMetadata("MappedPath")); Assert.Equal(@"Git", task.MappedSourceRoots[2].GetMetadata("SourceControl")); Assert.Equal(Utilities.FixFilePath(@"c:\MyProjects\MyProject\a\b\"), task.MappedSourceRoots[3].ItemSpec); Assert.Equal(@"/_/a/b/", task.MappedSourceRoots[3].GetMetadata("MappedPath")); Assert.Equal(@"Git", task.MappedSourceRoots[3].GetMetadata("SourceControl")); Assert.Equal(@"some value", task.MappedSourceRoots[3].GetMetadata("some metadata")); Assert.True(result); } [Fact] public void InvalidChars() { var engine = new MockEngine(); var task = new MapSourceRoots { BuildEngine = engine, SourceRoots = new[] { new TaskItem(@"!@#:;$%^&*()_+|{}\"), new TaskItem(@"****/", new Dictionary<string, string> { { "SourceControl", "Git" }, }), new TaskItem(@"****\|||:;\", new Dictionary<string, string> { { "SourceControl", "Git" }, { "NestedRoot", "|||:;" }, { "ContainingRoot", @"****/" }, }), }, Deterministic = true }; bool result = task.Execute(); AssertEx.AssertEqualToleratingWhitespaceDifferences("", engine.Log); RoslynDebug.Assert(task.MappedSourceRoots is object); Assert.Equal(3, task.MappedSourceRoots.Length); Assert.Equal(Utilities.FixFilePath(@"!@#:;$%^&*()_+|{}\"), task.MappedSourceRoots[0].ItemSpec); Assert.Equal(@"/_1/", task.MappedSourceRoots[0].GetMetadata("MappedPath")); Assert.Equal(Utilities.FixFilePath("****/"), task.MappedSourceRoots[1].ItemSpec); Assert.Equal(@"/_/", task.MappedSourceRoots[1].GetMetadata("MappedPath")); Assert.Equal(@"Git", task.MappedSourceRoots[1].GetMetadata("SourceControl")); Assert.Equal(Utilities.FixFilePath(@"****\|||:;\"), task.MappedSourceRoots[2].ItemSpec); Assert.Equal(@"/_/|||:;/", task.MappedSourceRoots[2].GetMetadata("MappedPath")); Assert.Equal(@"Git", task.MappedSourceRoots[2].GetMetadata("SourceControl")); Assert.True(result); } [Fact] public void SourceRootPaths_EndWithSeparator() { var engine = new MockEngine(); var task = new MapSourceRoots { BuildEngine = engine, SourceRoots = new[] { new TaskItem(@"C:\"), new TaskItem(@"C:/"), new TaskItem(@"C:"), new TaskItem(@"C"), }, Deterministic = true }; bool result = task.Execute(); AssertEx.AssertEqualToleratingWhitespaceDifferences($@" ERROR : {string.Format(ErrorString.MapSourceRoots_PathMustEndWithSlashOrBackslash, "SourceRoot", "C:")} ERROR : {string.Format(ErrorString.MapSourceRoots_PathMustEndWithSlashOrBackslash, "SourceRoot", "C")} ", engine.Log); Assert.False(result); } [Fact] public void NestedRoots_Separators() { var engine = new MockEngine(); var task = new MapSourceRoots { BuildEngine = engine, SourceRoots = new[] { new TaskItem(@"c:\MyProjects\MyProject\"), new TaskItem(@"c:\MyProjects\MyProject\a\a\", new Dictionary<string, string> { { "NestedRoot", @"a/a/" }, { "ContainingRoot", @"c:\MyProjects\MyProject\" }, }), new TaskItem(@"c:\MyProjects\MyProject\a\b\", new Dictionary<string, string> { { "NestedRoot", @"a/b\" }, { "ContainingRoot", @"c:\MyProjects\MyProject\" }, }), new TaskItem(@"c:\MyProjects\MyProject\a\c\", new Dictionary<string, string> { { "NestedRoot", @"a\c" }, { "ContainingRoot", @"c:\MyProjects\MyProject\" }, }), }, Deterministic = true }; bool result = task.Execute(); AssertEx.AssertEqualToleratingWhitespaceDifferences("", engine.Log); RoslynDebug.Assert(task.MappedSourceRoots is object); Assert.Equal(4, task.MappedSourceRoots.Length); Assert.Equal(Utilities.FixFilePath(@"c:\MyProjects\MyProject\"), task.MappedSourceRoots[0].ItemSpec); Assert.Equal(@"/_/", task.MappedSourceRoots[0].GetMetadata("MappedPath")); Assert.Equal(Utilities.FixFilePath(@"c:\MyProjects\MyProject\a\a\"), task.MappedSourceRoots[1].ItemSpec); Assert.Equal(@"/_/a/a/", task.MappedSourceRoots[1].GetMetadata("MappedPath")); Assert.Equal(Utilities.FixFilePath(@"c:\MyProjects\MyProject\a\b\"), task.MappedSourceRoots[2].ItemSpec); Assert.Equal(@"/_/a/b/", task.MappedSourceRoots[2].GetMetadata("MappedPath")); Assert.Equal(Utilities.FixFilePath(@"c:\MyProjects\MyProject\a\c\"), task.MappedSourceRoots[3].ItemSpec); Assert.Equal(@"/_/a/c/", task.MappedSourceRoots[3].GetMetadata("MappedPath")); Assert.True(result); } [Fact] public void SourceRootCaseSensitive() { var engine = new MockEngine(); var task = new MapSourceRoots { BuildEngine = engine, SourceRoots = new[] { new TaskItem(@"c:\packages\SourcePackage1\"), new TaskItem(@"C:\packages\SourcePackage1\"), new TaskItem(@"c:\packages\SourcePackage2\"), }, Deterministic = true }; bool result = task.Execute(); AssertEx.AssertEqualToleratingWhitespaceDifferences("", engine.Log); RoslynDebug.Assert(task.MappedSourceRoots is object); Assert.Equal(3, task.MappedSourceRoots.Length); Assert.Equal(Utilities.FixFilePath(@"c:\packages\SourcePackage1\"), task.MappedSourceRoots[0].ItemSpec); Assert.Equal(@"/_/", task.MappedSourceRoots[0].GetMetadata("MappedPath")); Assert.Equal(Utilities.FixFilePath(@"C:\packages\SourcePackage1\"), task.MappedSourceRoots[1].ItemSpec); Assert.Equal(@"/_1/", task.MappedSourceRoots[1].GetMetadata("MappedPath")); Assert.Equal(Utilities.FixFilePath(@"c:\packages\SourcePackage2\"), task.MappedSourceRoots[2].ItemSpec); Assert.Equal(@"/_2/", task.MappedSourceRoots[2].GetMetadata("MappedPath")); Assert.True(result); } [Fact] public void Error_Recursion() { var engine = new MockEngine(); var path1 = Utilities.FixFilePath(@"c:\MyProjects\MyProject\a\1\"); var path2 = Utilities.FixFilePath(@"c:\MyProjects\MyProject\a\2\"); var path3 = Utilities.FixFilePath(@"c:\MyProjects\MyProject\"); var task = new MapSourceRoots { BuildEngine = engine, SourceRoots = new[] { new TaskItem(path1, new Dictionary<string, string> { { "ContainingRoot", path2 }, { "NestedRoot", "a/1" }, }), new TaskItem(path2, new Dictionary<string, string> { { "ContainingRoot", path1 }, { "NestedRoot", "a/2" }, }), new TaskItem(path3), }, Deterministic = true }; bool result = task.Execute(); AssertEx.AssertEqualToleratingWhitespaceDifferences( "ERROR : " + string.Format(task.Log.FormatResourceString( "MapSourceRoots.NoSuchTopLevelSourceRoot", "SourceRoot.ContainingRoot", "SourceRoot", path2)) + Environment.NewLine + "ERROR : " + string.Format(task.Log.FormatResourceString( "MapSourceRoots.NoSuchTopLevelSourceRoot", "SourceRoot.ContainingRoot", "SourceRoot", path1)) + Environment.NewLine, engine.Log); Assert.Null(task.MappedSourceRoots); Assert.False(result); } [Theory] [InlineData(new object[] { true })] [InlineData(new object[] { false })] public void MetadataMerge1(bool deterministic) { var engine = new MockEngine(); var path1 = Utilities.FixFilePath(@"c:\packages\SourcePackage1\"); var path2 = Utilities.FixFilePath(@"c:\packages\SourcePackage2\"); var path3 = Utilities.FixFilePath(@"c:\packages\SourcePackage3\"); var task = new MapSourceRoots { BuildEngine = engine, SourceRoots = new[] { new TaskItem(path1, new Dictionary<string, string> { { "NestedRoot", @"NR1A" }, { "ContainingRoot", path3 }, { "RevisionId", "RevId1" }, { "SourceControl", "git" }, { "MappedPath", "MP1" }, { "SourceLinkUrl", "URL1" }, }), new TaskItem(path1, new Dictionary<string, string> { { "NestedRoot", @"NR1B" }, { "ContainingRoot", @"CR" }, { "RevisionId", "RevId2" }, { "SourceControl", "tfvc" }, { "MappedPath", "MP2" }, { "SourceLinkUrl", "URL2" }, }), new TaskItem(path2, new Dictionary<string, string> { { "NestedRoot", @"NR2" }, { "SourceControl", "git" }, }), new TaskItem(path2, new Dictionary<string, string> { { "ContainingRoot", path3 }, { "SourceControl", "git" }, }), new TaskItem(path3), }, Deterministic = deterministic }; bool result = task.Execute(); AssertEx.AssertEqualToleratingWhitespaceDifferences( "WARNING : " + string.Format(task.Log.FormatResourceString( "MapSourceRoots.ContainsDuplicate", "SourceRoot", path1, "SourceControl", "git", "tfvc")) + Environment.NewLine + "WARNING : " + string.Format(task.Log.FormatResourceString( "MapSourceRoots.ContainsDuplicate", "SourceRoot", path1, "RevisionId", "RevId1", "RevId2")) + Environment.NewLine + "WARNING : " + string.Format(task.Log.FormatResourceString( "MapSourceRoots.ContainsDuplicate", "SourceRoot", path1, "NestedRoot", "NR1A", "NR1B")) + Environment.NewLine + "WARNING : " + string.Format(task.Log.FormatResourceString( "MapSourceRoots.ContainsDuplicate", "SourceRoot", path1, "ContainingRoot", path3, "CR")) + Environment.NewLine + "WARNING : " + string.Format(task.Log.FormatResourceString( "MapSourceRoots.ContainsDuplicate", "SourceRoot", path1, "MappedPath", "MP1", "MP2")) + Environment.NewLine + "WARNING : " + string.Format(task.Log.FormatResourceString( "MapSourceRoots.ContainsDuplicate", "SourceRoot", path1, "SourceLinkUrl", "URL1", "URL2")) + Environment.NewLine, engine.Log); AssertEx.NotNull(task.MappedSourceRoots); AssertEx.Equal(new[] { $"'{path1}' SourceControl='git' RevisionId='RevId1' NestedRoot='NR1A' ContainingRoot='{path3}' MappedPath='{(deterministic ? "/_/NR1A/" : path1)}' SourceLinkUrl='URL1'", $"'{path2}' SourceControl='git' RevisionId='' NestedRoot='NR2' ContainingRoot='{path3}' MappedPath='{(deterministic ? "/_/NR2/" : path2)}' SourceLinkUrl=''", $"'{path3}' SourceControl='' RevisionId='' NestedRoot='' ContainingRoot='' MappedPath='{(deterministic ? "/_/" : path3)}' SourceLinkUrl=''", }, task.MappedSourceRoots.Select(InspectSourceRoot)); Assert.True(result); } [Fact] public void Error_MissingContainingRoot() { var engine = new MockEngine(); var task = new MapSourceRoots { BuildEngine = engine, SourceRoots = new[] { new TaskItem(@"c:\MyProjects\MYPROJECT\"), new TaskItem(@"c:\MyProjects\MyProject\a\b\", new Dictionary<string, string> { { "SourceControl", "Git" }, { "NestedRoot", "a/b" }, { "ContainingRoot", @"c:\MyProjects\MyProject\" }, }), }, Deterministic = true }; bool result = task.Execute(); AssertEx.AssertEqualToleratingWhitespaceDifferences("ERROR : " + string.Format(task.Log.FormatResourceString( "MapSourceRoots.NoSuchTopLevelSourceRoot", "SourceRoot.ContainingRoot", "SourceRoot", @"c:\MyProjects\MyProject\")) + Environment.NewLine, engine.Log); Assert.Null(task.MappedSourceRoots); Assert.False(result); } [Fact] public void Error_NoContainingRootSpecified() { var engine = new MockEngine(); var task = new MapSourceRoots { BuildEngine = engine, SourceRoots = new[] { new TaskItem(@"c:\MyProjects\MyProject\"), new TaskItem(@"c:\MyProjects\MyProject\a\b\", new Dictionary<string, string> { { "SourceControl", "Git" }, { "NestedRoot", "a/b" }, }), }, Deterministic = true }; bool result = task.Execute(); AssertEx.AssertEqualToleratingWhitespaceDifferences("ERROR : " + string.Format(task.Log.FormatResourceString( "MapSourceRoots.NoSuchTopLevelSourceRoot", "SourceRoot.ContainingRoot", "SourceRoot", @"")) + Environment.NewLine, engine.Log); Assert.Null(task.MappedSourceRoots); Assert.False(result); } [Theory] [InlineData(new object[] { true })] [InlineData(new object[] { false })] public void Error_NoTopLevelSourceRoot(bool deterministic) { var engine = new MockEngine(); var path1 = Utilities.FixFilePath(@"c:\MyProjects\MyProject\a\b\"); var task = new MapSourceRoots { BuildEngine = engine, SourceRoots = new[] { new TaskItem(path1, new Dictionary<string, string> { { "ContainingRoot", path1 }, { "NestedRoot", "a/b" }, }), }, Deterministic = deterministic }; bool result = task.Execute(); if (deterministic) { AssertEx.AssertEqualToleratingWhitespaceDifferences("ERROR : " + string.Format(task.Log.FormatResourceString( "MapSourceRoots.NoTopLevelSourceRoot", "SourceRoot", "DeterministicSourcePaths")) + Environment.NewLine, engine.Log); Assert.Null(task.MappedSourceRoots); Assert.False(result); } else { AssertEx.NotNull(task.MappedSourceRoots); AssertEx.Equal(new[] { $"'{path1}' SourceControl='' RevisionId='' NestedRoot='a/b' ContainingRoot='{path1}' MappedPath='{path1}' SourceLinkUrl=''", }, task.MappedSourceRoots.Select(InspectSourceRoot)); Assert.True(result); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests { public sealed class MapSourceRootsTests { private string InspectSourceRoot(ITaskItem sourceRoot) => $"'{sourceRoot.ItemSpec}'" + $" SourceControl='{sourceRoot.GetMetadata("SourceControl")}'" + $" RevisionId='{sourceRoot.GetMetadata("RevisionId")}'" + $" NestedRoot='{sourceRoot.GetMetadata("NestedRoot")}'" + $" ContainingRoot='{sourceRoot.GetMetadata("ContainingRoot")}'" + $" MappedPath='{sourceRoot.GetMetadata("MappedPath")}'" + $" SourceLinkUrl='{sourceRoot.GetMetadata("SourceLinkUrl")}'"; [Fact] public void BasicMapping() { var engine = new MockEngine(); var task = new MapSourceRoots { BuildEngine = engine, SourceRoots = new[] { new TaskItem(@"c:\packages\SourcePackage1\"), new TaskItem(@"/packages/SourcePackage2/"), new TaskItem(@"c:\MyProjects\MyProject\", new Dictionary<string, string> { { "SourceControl", "Git" }, }), new TaskItem(@"c:\MyProjects\MyProject\a\b\", new Dictionary<string, string> { { "SourceControl", "Git" }, { "NestedRoot", "a/b" }, { "ContainingRoot", @"c:\MyProjects\MyProject\" }, { "some metadata", "some value" }, }), }, Deterministic = true }; bool result = task.Execute(); AssertEx.AssertEqualToleratingWhitespaceDifferences("", engine.Log); RoslynDebug.Assert(task.MappedSourceRoots is object); Assert.Equal(4, task.MappedSourceRoots.Length); Assert.Equal(Utilities.FixFilePath(@"c:\packages\SourcePackage1\"), task.MappedSourceRoots[0].ItemSpec); Assert.Equal(@"/_1/", task.MappedSourceRoots[0].GetMetadata("MappedPath")); Assert.Equal(Utilities.FixFilePath(@"/packages/SourcePackage2/"), task.MappedSourceRoots[1].ItemSpec); Assert.Equal(@"/_2/", task.MappedSourceRoots[1].GetMetadata("MappedPath")); Assert.Equal(Utilities.FixFilePath(@"c:\MyProjects\MyProject\"), task.MappedSourceRoots[2].ItemSpec); Assert.Equal(@"/_/", task.MappedSourceRoots[2].GetMetadata("MappedPath")); Assert.Equal(@"Git", task.MappedSourceRoots[2].GetMetadata("SourceControl")); Assert.Equal(Utilities.FixFilePath(@"c:\MyProjects\MyProject\a\b\"), task.MappedSourceRoots[3].ItemSpec); Assert.Equal(@"/_/a/b/", task.MappedSourceRoots[3].GetMetadata("MappedPath")); Assert.Equal(@"Git", task.MappedSourceRoots[3].GetMetadata("SourceControl")); Assert.Equal(@"some value", task.MappedSourceRoots[3].GetMetadata("some metadata")); Assert.True(result); } [Fact] public void InvalidChars() { var engine = new MockEngine(); var task = new MapSourceRoots { BuildEngine = engine, SourceRoots = new[] { new TaskItem(@"!@#:;$%^&*()_+|{}\"), new TaskItem(@"****/", new Dictionary<string, string> { { "SourceControl", "Git" }, }), new TaskItem(@"****\|||:;\", new Dictionary<string, string> { { "SourceControl", "Git" }, { "NestedRoot", "|||:;" }, { "ContainingRoot", @"****/" }, }), }, Deterministic = true }; bool result = task.Execute(); AssertEx.AssertEqualToleratingWhitespaceDifferences("", engine.Log); RoslynDebug.Assert(task.MappedSourceRoots is object); Assert.Equal(3, task.MappedSourceRoots.Length); Assert.Equal(Utilities.FixFilePath(@"!@#:;$%^&*()_+|{}\"), task.MappedSourceRoots[0].ItemSpec); Assert.Equal(@"/_1/", task.MappedSourceRoots[0].GetMetadata("MappedPath")); Assert.Equal(Utilities.FixFilePath("****/"), task.MappedSourceRoots[1].ItemSpec); Assert.Equal(@"/_/", task.MappedSourceRoots[1].GetMetadata("MappedPath")); Assert.Equal(@"Git", task.MappedSourceRoots[1].GetMetadata("SourceControl")); Assert.Equal(Utilities.FixFilePath(@"****\|||:;\"), task.MappedSourceRoots[2].ItemSpec); Assert.Equal(@"/_/|||:;/", task.MappedSourceRoots[2].GetMetadata("MappedPath")); Assert.Equal(@"Git", task.MappedSourceRoots[2].GetMetadata("SourceControl")); Assert.True(result); } [Fact] public void SourceRootPaths_EndWithSeparator() { var engine = new MockEngine(); var task = new MapSourceRoots { BuildEngine = engine, SourceRoots = new[] { new TaskItem(@"C:\"), new TaskItem(@"C:/"), new TaskItem(@"C:"), new TaskItem(@"C"), }, Deterministic = true }; bool result = task.Execute(); AssertEx.AssertEqualToleratingWhitespaceDifferences($@" ERROR : {string.Format(ErrorString.MapSourceRoots_PathMustEndWithSlashOrBackslash, "SourceRoot", "C:")} ERROR : {string.Format(ErrorString.MapSourceRoots_PathMustEndWithSlashOrBackslash, "SourceRoot", "C")} ", engine.Log); Assert.False(result); } [Fact] public void NestedRoots_Separators() { var engine = new MockEngine(); var task = new MapSourceRoots { BuildEngine = engine, SourceRoots = new[] { new TaskItem(@"c:\MyProjects\MyProject\"), new TaskItem(@"c:\MyProjects\MyProject\a\a\", new Dictionary<string, string> { { "NestedRoot", @"a/a/" }, { "ContainingRoot", @"c:\MyProjects\MyProject\" }, }), new TaskItem(@"c:\MyProjects\MyProject\a\b\", new Dictionary<string, string> { { "NestedRoot", @"a/b\" }, { "ContainingRoot", @"c:\MyProjects\MyProject\" }, }), new TaskItem(@"c:\MyProjects\MyProject\a\c\", new Dictionary<string, string> { { "NestedRoot", @"a\c" }, { "ContainingRoot", @"c:\MyProjects\MyProject\" }, }), }, Deterministic = true }; bool result = task.Execute(); AssertEx.AssertEqualToleratingWhitespaceDifferences("", engine.Log); RoslynDebug.Assert(task.MappedSourceRoots is object); Assert.Equal(4, task.MappedSourceRoots.Length); Assert.Equal(Utilities.FixFilePath(@"c:\MyProjects\MyProject\"), task.MappedSourceRoots[0].ItemSpec); Assert.Equal(@"/_/", task.MappedSourceRoots[0].GetMetadata("MappedPath")); Assert.Equal(Utilities.FixFilePath(@"c:\MyProjects\MyProject\a\a\"), task.MappedSourceRoots[1].ItemSpec); Assert.Equal(@"/_/a/a/", task.MappedSourceRoots[1].GetMetadata("MappedPath")); Assert.Equal(Utilities.FixFilePath(@"c:\MyProjects\MyProject\a\b\"), task.MappedSourceRoots[2].ItemSpec); Assert.Equal(@"/_/a/b/", task.MappedSourceRoots[2].GetMetadata("MappedPath")); Assert.Equal(Utilities.FixFilePath(@"c:\MyProjects\MyProject\a\c\"), task.MappedSourceRoots[3].ItemSpec); Assert.Equal(@"/_/a/c/", task.MappedSourceRoots[3].GetMetadata("MappedPath")); Assert.True(result); } [Fact] public void SourceRootCaseSensitive() { var engine = new MockEngine(); var task = new MapSourceRoots { BuildEngine = engine, SourceRoots = new[] { new TaskItem(@"c:\packages\SourcePackage1\"), new TaskItem(@"C:\packages\SourcePackage1\"), new TaskItem(@"c:\packages\SourcePackage2\"), }, Deterministic = true }; bool result = task.Execute(); AssertEx.AssertEqualToleratingWhitespaceDifferences("", engine.Log); RoslynDebug.Assert(task.MappedSourceRoots is object); Assert.Equal(3, task.MappedSourceRoots.Length); Assert.Equal(Utilities.FixFilePath(@"c:\packages\SourcePackage1\"), task.MappedSourceRoots[0].ItemSpec); Assert.Equal(@"/_/", task.MappedSourceRoots[0].GetMetadata("MappedPath")); Assert.Equal(Utilities.FixFilePath(@"C:\packages\SourcePackage1\"), task.MappedSourceRoots[1].ItemSpec); Assert.Equal(@"/_1/", task.MappedSourceRoots[1].GetMetadata("MappedPath")); Assert.Equal(Utilities.FixFilePath(@"c:\packages\SourcePackage2\"), task.MappedSourceRoots[2].ItemSpec); Assert.Equal(@"/_2/", task.MappedSourceRoots[2].GetMetadata("MappedPath")); Assert.True(result); } [Fact] public void Error_Recursion() { var engine = new MockEngine(); var path1 = Utilities.FixFilePath(@"c:\MyProjects\MyProject\a\1\"); var path2 = Utilities.FixFilePath(@"c:\MyProjects\MyProject\a\2\"); var path3 = Utilities.FixFilePath(@"c:\MyProjects\MyProject\"); var task = new MapSourceRoots { BuildEngine = engine, SourceRoots = new[] { new TaskItem(path1, new Dictionary<string, string> { { "ContainingRoot", path2 }, { "NestedRoot", "a/1" }, }), new TaskItem(path2, new Dictionary<string, string> { { "ContainingRoot", path1 }, { "NestedRoot", "a/2" }, }), new TaskItem(path3), }, Deterministic = true }; bool result = task.Execute(); AssertEx.AssertEqualToleratingWhitespaceDifferences( "ERROR : " + string.Format(task.Log.FormatResourceString( "MapSourceRoots.NoSuchTopLevelSourceRoot", "SourceRoot.ContainingRoot", "SourceRoot", path2)) + Environment.NewLine + "ERROR : " + string.Format(task.Log.FormatResourceString( "MapSourceRoots.NoSuchTopLevelSourceRoot", "SourceRoot.ContainingRoot", "SourceRoot", path1)) + Environment.NewLine, engine.Log); Assert.Null(task.MappedSourceRoots); Assert.False(result); } [Theory] [InlineData(new object[] { true })] [InlineData(new object[] { false })] public void MetadataMerge1(bool deterministic) { var engine = new MockEngine(); var path1 = Utilities.FixFilePath(@"c:\packages\SourcePackage1\"); var path2 = Utilities.FixFilePath(@"c:\packages\SourcePackage2\"); var path3 = Utilities.FixFilePath(@"c:\packages\SourcePackage3\"); var task = new MapSourceRoots { BuildEngine = engine, SourceRoots = new[] { new TaskItem(path1, new Dictionary<string, string> { { "NestedRoot", @"NR1A" }, { "ContainingRoot", path3 }, { "RevisionId", "RevId1" }, { "SourceControl", "git" }, { "MappedPath", "MP1" }, { "SourceLinkUrl", "URL1" }, }), new TaskItem(path1, new Dictionary<string, string> { { "NestedRoot", @"NR1B" }, { "ContainingRoot", @"CR" }, { "RevisionId", "RevId2" }, { "SourceControl", "tfvc" }, { "MappedPath", "MP2" }, { "SourceLinkUrl", "URL2" }, }), new TaskItem(path2, new Dictionary<string, string> { { "NestedRoot", @"NR2" }, { "SourceControl", "git" }, }), new TaskItem(path2, new Dictionary<string, string> { { "ContainingRoot", path3 }, { "SourceControl", "git" }, }), new TaskItem(path3), }, Deterministic = deterministic }; bool result = task.Execute(); AssertEx.AssertEqualToleratingWhitespaceDifferences( "WARNING : " + string.Format(task.Log.FormatResourceString( "MapSourceRoots.ContainsDuplicate", "SourceRoot", path1, "SourceControl", "git", "tfvc")) + Environment.NewLine + "WARNING : " + string.Format(task.Log.FormatResourceString( "MapSourceRoots.ContainsDuplicate", "SourceRoot", path1, "RevisionId", "RevId1", "RevId2")) + Environment.NewLine + "WARNING : " + string.Format(task.Log.FormatResourceString( "MapSourceRoots.ContainsDuplicate", "SourceRoot", path1, "NestedRoot", "NR1A", "NR1B")) + Environment.NewLine + "WARNING : " + string.Format(task.Log.FormatResourceString( "MapSourceRoots.ContainsDuplicate", "SourceRoot", path1, "ContainingRoot", path3, "CR")) + Environment.NewLine + "WARNING : " + string.Format(task.Log.FormatResourceString( "MapSourceRoots.ContainsDuplicate", "SourceRoot", path1, "MappedPath", "MP1", "MP2")) + Environment.NewLine + "WARNING : " + string.Format(task.Log.FormatResourceString( "MapSourceRoots.ContainsDuplicate", "SourceRoot", path1, "SourceLinkUrl", "URL1", "URL2")) + Environment.NewLine, engine.Log); AssertEx.NotNull(task.MappedSourceRoots); AssertEx.Equal(new[] { $"'{path1}' SourceControl='git' RevisionId='RevId1' NestedRoot='NR1A' ContainingRoot='{path3}' MappedPath='{(deterministic ? "/_/NR1A/" : path1)}' SourceLinkUrl='URL1'", $"'{path2}' SourceControl='git' RevisionId='' NestedRoot='NR2' ContainingRoot='{path3}' MappedPath='{(deterministic ? "/_/NR2/" : path2)}' SourceLinkUrl=''", $"'{path3}' SourceControl='' RevisionId='' NestedRoot='' ContainingRoot='' MappedPath='{(deterministic ? "/_/" : path3)}' SourceLinkUrl=''", }, task.MappedSourceRoots.Select(InspectSourceRoot)); Assert.True(result); } [Fact] public void Error_MissingContainingRoot() { var engine = new MockEngine(); var task = new MapSourceRoots { BuildEngine = engine, SourceRoots = new[] { new TaskItem(@"c:\MyProjects\MYPROJECT\"), new TaskItem(@"c:\MyProjects\MyProject\a\b\", new Dictionary<string, string> { { "SourceControl", "Git" }, { "NestedRoot", "a/b" }, { "ContainingRoot", @"c:\MyProjects\MyProject\" }, }), }, Deterministic = true }; bool result = task.Execute(); AssertEx.AssertEqualToleratingWhitespaceDifferences("ERROR : " + string.Format(task.Log.FormatResourceString( "MapSourceRoots.NoSuchTopLevelSourceRoot", "SourceRoot.ContainingRoot", "SourceRoot", @"c:\MyProjects\MyProject\")) + Environment.NewLine, engine.Log); Assert.Null(task.MappedSourceRoots); Assert.False(result); } [Fact] public void Error_NoContainingRootSpecified() { var engine = new MockEngine(); var task = new MapSourceRoots { BuildEngine = engine, SourceRoots = new[] { new TaskItem(@"c:\MyProjects\MyProject\"), new TaskItem(@"c:\MyProjects\MyProject\a\b\", new Dictionary<string, string> { { "SourceControl", "Git" }, { "NestedRoot", "a/b" }, }), }, Deterministic = true }; bool result = task.Execute(); AssertEx.AssertEqualToleratingWhitespaceDifferences("ERROR : " + string.Format(task.Log.FormatResourceString( "MapSourceRoots.NoSuchTopLevelSourceRoot", "SourceRoot.ContainingRoot", "SourceRoot", @"")) + Environment.NewLine, engine.Log); Assert.Null(task.MappedSourceRoots); Assert.False(result); } [Theory] [InlineData(new object[] { true })] [InlineData(new object[] { false })] public void Error_NoTopLevelSourceRoot(bool deterministic) { var engine = new MockEngine(); var path1 = Utilities.FixFilePath(@"c:\MyProjects\MyProject\a\b\"); var task = new MapSourceRoots { BuildEngine = engine, SourceRoots = new[] { new TaskItem(path1, new Dictionary<string, string> { { "ContainingRoot", path1 }, { "NestedRoot", "a/b" }, }), }, Deterministic = deterministic }; bool result = task.Execute(); if (deterministic) { AssertEx.AssertEqualToleratingWhitespaceDifferences("ERROR : " + string.Format(task.Log.FormatResourceString( "MapSourceRoots.NoTopLevelSourceRoot", "SourceRoot", "DeterministicSourcePaths")) + Environment.NewLine, engine.Log); Assert.Null(task.MappedSourceRoots); Assert.False(result); } else { AssertEx.NotNull(task.MappedSourceRoots); AssertEx.Equal(new[] { $"'{path1}' SourceControl='' RevisionId='' NestedRoot='a/b' ContainingRoot='{path1}' MappedPath='{path1}' SourceLinkUrl=''", }, task.MappedSourceRoots.Select(InspectSourceRoot)); Assert.True(result); } } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Features/Core/Portable/Workspace/ProjectCacheService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// This service will implicitly cache previous Compilations used by each supported Workspace implementation. /// The number of Compilations cached is determined by <see cref="ImplicitCacheSize"/>. For now, we'll only /// support implicit caching for VS Workspaces (<see cref="WorkspaceKind.Host"/>), as caching is known to /// reduce latency in designer scenarios using the VS workspace. For other Workspace kinds, the cost of the /// cache is likely to outweigh the benefit (for example, in Misc File Workspace cases, we can end up holding /// onto a lot of memory even after a file is closed). We can opt in other kinds of Workspaces as needed. /// </summary> internal partial class ProjectCacheService : IProjectCacheHostService { internal const int ImplicitCacheSize = 3; private readonly object _gate = new(); private readonly Workspace _workspace; private readonly Dictionary<ProjectId, Cache> _activeCaches = new(); private readonly SimpleMRUCache? _implicitCache; private readonly ImplicitCacheMonitor? _implicitCacheMonitor; public ProjectCacheService(Workspace workspace) => _workspace = workspace; public ProjectCacheService(Workspace workspace, TimeSpan implicitCacheTimeout) { _workspace = workspace; _implicitCache = new SimpleMRUCache(); _implicitCacheMonitor = new ImplicitCacheMonitor(this, implicitCacheTimeout); } public bool IsImplicitCacheEmpty { get { lock (_gate) { return _implicitCache?.IsEmpty ?? false; } } } public void ClearImplicitCache() { lock (_gate) { _implicitCache?.Clear(); } } public void ClearExpiredImplicitCache(DateTime expirationTime) { lock (_gate) { _implicitCache?.ClearExpiredItems(expirationTime); } } public IDisposable EnableCaching(ProjectId key) { lock (_gate) { if (!_activeCaches.TryGetValue(key, out var cache)) { cache = new Cache(this, key); _activeCaches.Add(key, cache); } cache.Count++; return cache; } } [return: NotNullIfNotNull("instance")] public T? CacheObjectIfCachingEnabledForKey<T>(ProjectId key, object owner, T? instance) where T : class { lock (_gate) { if (_activeCaches.TryGetValue(key, out var cache)) { cache.CreateStrongReference(owner, instance); } else if (_implicitCache != null && !PartOfP2PReferences(key)) { RoslynDebug.Assert(_implicitCacheMonitor != null); _implicitCache.Touch(instance); _implicitCacheMonitor.Touch(); } return instance; } } private bool PartOfP2PReferences(ProjectId key) { if (_activeCaches.Count == 0 || _workspace == null) { return false; } var solution = _workspace.CurrentSolution; var graph = solution.GetProjectDependencyGraph(); foreach (var projectId in _activeCaches.Keys) { // this should be cheap. graph is cached every time project reference is updated. var p2pReferences = (ImmutableHashSet<ProjectId>)graph.GetProjectsThatThisProjectTransitivelyDependsOn(projectId); if (p2pReferences.Contains(key)) { return true; } } return false; } [return: NotNullIfNotNull("instance")] public T? CacheObjectIfCachingEnabledForKey<T>(ProjectId key, ICachedObjectOwner owner, T? instance) where T : class { lock (_gate) { if (owner.CachedObject == null && _activeCaches.TryGetValue(key, out var cache)) { owner.CachedObject = instance; cache.CreateOwnerEntry(owner); } return instance; } } private void DisableCaching(ProjectId key, Cache cache) { lock (_gate) { cache.Count--; if (cache.Count == 0) { _activeCaches.Remove(key); cache.FreeOwnerEntries(); } } } private sealed class Cache : IDisposable { internal int Count; private readonly ProjectCacheService _cacheService; private readonly ProjectId _key; private ConditionalWeakTable<object, object?>? _cache = new(); private readonly List<WeakReference<ICachedObjectOwner>> _ownerObjects = new(); public Cache(ProjectCacheService cacheService, ProjectId key) { _cacheService = cacheService; _key = key; } public void Dispose() => _cacheService.DisableCaching(_key, this); internal void CreateStrongReference(object key, object? instance) { if (_cache == null) { throw new ObjectDisposedException(nameof(Cache)); } if (!_cache.TryGetValue(key, out _)) { _cache.Add(key, instance); } } internal void CreateOwnerEntry(ICachedObjectOwner owner) => _ownerObjects.Add(new WeakReference<ICachedObjectOwner>(owner)); internal void FreeOwnerEntries() { foreach (var entry in _ownerObjects) { if (entry.TryGetTarget(out var owner)) { owner.CachedObject = null; } } // Explicitly free our ConditionalWeakTable to make sure it's released. We have a number of places in the codebase // (in both tests and product code) that do using (service.EnableCaching), which implicitly returns a disposable instance // this type. The runtime in many cases disposes, but does not unroot, the underlying object after the the using block is exited. // This means the cache could still be rooting objects we don't expect it to be rooting by that point. By explicitly clearing // these out, we get the expected behavior. _cache = null; _ownerObjects.Clear(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// This service will implicitly cache previous Compilations used by each supported Workspace implementation. /// The number of Compilations cached is determined by <see cref="ImplicitCacheSize"/>. For now, we'll only /// support implicit caching for VS Workspaces (<see cref="WorkspaceKind.Host"/>), as caching is known to /// reduce latency in designer scenarios using the VS workspace. For other Workspace kinds, the cost of the /// cache is likely to outweigh the benefit (for example, in Misc File Workspace cases, we can end up holding /// onto a lot of memory even after a file is closed). We can opt in other kinds of Workspaces as needed. /// </summary> internal partial class ProjectCacheService : IProjectCacheHostService { internal const int ImplicitCacheSize = 3; private readonly object _gate = new(); private readonly Workspace _workspace; private readonly Dictionary<ProjectId, Cache> _activeCaches = new(); private readonly SimpleMRUCache? _implicitCache; private readonly ImplicitCacheMonitor? _implicitCacheMonitor; public ProjectCacheService(Workspace workspace) => _workspace = workspace; public ProjectCacheService(Workspace workspace, TimeSpan implicitCacheTimeout) { _workspace = workspace; _implicitCache = new SimpleMRUCache(); _implicitCacheMonitor = new ImplicitCacheMonitor(this, implicitCacheTimeout); } public bool IsImplicitCacheEmpty { get { lock (_gate) { return _implicitCache?.IsEmpty ?? false; } } } public void ClearImplicitCache() { lock (_gate) { _implicitCache?.Clear(); } } public void ClearExpiredImplicitCache(DateTime expirationTime) { lock (_gate) { _implicitCache?.ClearExpiredItems(expirationTime); } } public IDisposable EnableCaching(ProjectId key) { lock (_gate) { if (!_activeCaches.TryGetValue(key, out var cache)) { cache = new Cache(this, key); _activeCaches.Add(key, cache); } cache.Count++; return cache; } } [return: NotNullIfNotNull("instance")] public T? CacheObjectIfCachingEnabledForKey<T>(ProjectId key, object owner, T? instance) where T : class { lock (_gate) { if (_activeCaches.TryGetValue(key, out var cache)) { cache.CreateStrongReference(owner, instance); } else if (_implicitCache != null && !PartOfP2PReferences(key)) { RoslynDebug.Assert(_implicitCacheMonitor != null); _implicitCache.Touch(instance); _implicitCacheMonitor.Touch(); } return instance; } } private bool PartOfP2PReferences(ProjectId key) { if (_activeCaches.Count == 0 || _workspace == null) { return false; } var solution = _workspace.CurrentSolution; var graph = solution.GetProjectDependencyGraph(); foreach (var projectId in _activeCaches.Keys) { // this should be cheap. graph is cached every time project reference is updated. var p2pReferences = (ImmutableHashSet<ProjectId>)graph.GetProjectsThatThisProjectTransitivelyDependsOn(projectId); if (p2pReferences.Contains(key)) { return true; } } return false; } [return: NotNullIfNotNull("instance")] public T? CacheObjectIfCachingEnabledForKey<T>(ProjectId key, ICachedObjectOwner owner, T? instance) where T : class { lock (_gate) { if (owner.CachedObject == null && _activeCaches.TryGetValue(key, out var cache)) { owner.CachedObject = instance; cache.CreateOwnerEntry(owner); } return instance; } } private void DisableCaching(ProjectId key, Cache cache) { lock (_gate) { cache.Count--; if (cache.Count == 0) { _activeCaches.Remove(key); cache.FreeOwnerEntries(); } } } private sealed class Cache : IDisposable { internal int Count; private readonly ProjectCacheService _cacheService; private readonly ProjectId _key; private ConditionalWeakTable<object, object?>? _cache = new(); private readonly List<WeakReference<ICachedObjectOwner>> _ownerObjects = new(); public Cache(ProjectCacheService cacheService, ProjectId key) { _cacheService = cacheService; _key = key; } public void Dispose() => _cacheService.DisableCaching(_key, this); internal void CreateStrongReference(object key, object? instance) { if (_cache == null) { throw new ObjectDisposedException(nameof(Cache)); } if (!_cache.TryGetValue(key, out _)) { _cache.Add(key, instance); } } internal void CreateOwnerEntry(ICachedObjectOwner owner) => _ownerObjects.Add(new WeakReference<ICachedObjectOwner>(owner)); internal void FreeOwnerEntries() { foreach (var entry in _ownerObjects) { if (entry.TryGetTarget(out var owner)) { owner.CachedObject = null; } } // Explicitly free our ConditionalWeakTable to make sure it's released. We have a number of places in the codebase // (in both tests and product code) that do using (service.EnableCaching), which implicitly returns a disposable instance // this type. The runtime in many cases disposes, but does not unroot, the underlying object after the the using block is exited. // This means the cache could still be rooting objects we don't expect it to be rooting by that point. By explicitly clearing // these out, we get the expected behavior. _cache = null; _ownerObjects.Clear(); } } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/EditorFeatures/Core/Implementation/EditAndContinue/EditAndContinueUIContext.cs
// Licensed to the .NET Foundation under one or more 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.Implementation.EditAndContinue { internal static class EditAndContinueUIContext { /// <summary> /// Context id that indicates that primary workspace contains a project that supports Edit and Continue. /// </summary> internal const string EncCapableProjectExistsInWorkspaceUIContextString = "0C89AE24-6D19-474C-A3AA-DC3B66FDBB5F"; } }
// Licensed to the .NET Foundation under one or more 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.Implementation.EditAndContinue { internal static class EditAndContinueUIContext { /// <summary> /// Context id that indicates that primary workspace contains a project that supports Edit and Continue. /// </summary> internal const string EncCapableProjectExistsInWorkspaceUIContextString = "0C89AE24-6D19-474C-A3AA-DC3B66FDBB5F"; } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/Test/Core/FX/ProcessResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Text; namespace Roslyn.Test.Utilities { /// <summary> /// Encapsulates exit code and output/error streams of a process. /// </summary> public sealed class ProcessResult { public int ExitCode { get; } public string Output { get; } public string Errors { get; } public ProcessResult(int exitCode, string output, string errors) { ExitCode = exitCode; Output = output; Errors = errors; } public override string ToString() { return "EXIT CODE: " + this.ExitCode + Environment.NewLine + "OUTPUT STREAM:" + Environment.NewLine + this.Output + Environment.NewLine + "ERRORS:" + Environment.NewLine + this.Errors; } public bool ContainsErrors { get { return this.ExitCode != 0 || !string.IsNullOrEmpty(this.Errors); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Text; namespace Roslyn.Test.Utilities { /// <summary> /// Encapsulates exit code and output/error streams of a process. /// </summary> public sealed class ProcessResult { public int ExitCode { get; } public string Output { get; } public string Errors { get; } public ProcessResult(int exitCode, string output, string errors) { ExitCode = exitCode; Output = output; Errors = errors; } public override string ToString() { return "EXIT CODE: " + this.ExitCode + Environment.NewLine + "OUTPUT STREAM:" + Environment.NewLine + this.Output + Environment.NewLine + "ERRORS:" + Environment.NewLine + this.Errors; } public bool ContainsErrors { get { return this.ExitCode != 0 || !string.IsNullOrEmpty(this.Errors); } } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Features/Core/Portable/IntroduceVariable/AbstractIntroduceVariableService.CodeAction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.IntroduceVariable { internal partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax, TNameSyntax> { private class IntroduceVariableCodeAction : AbstractIntroduceVariableCodeAction { internal IntroduceVariableCodeAction( TService service, SemanticDocument document, TExpressionSyntax expression, bool allOccurrences, bool isConstant, bool isLocal, bool isQueryLocal) : base(service, document, expression, allOccurrences, isConstant, isLocal, isQueryLocal) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.IntroduceVariable { internal partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax, TNameSyntax> { private class IntroduceVariableCodeAction : AbstractIntroduceVariableCodeAction { internal IntroduceVariableCodeAction( TService service, SemanticDocument document, TExpressionSyntax expression, bool allOccurrences, bool isConstant, bool isLocal, bool isQueryLocal) : base(service, document, expression, allOccurrences, isConstant, isLocal, isQueryLocal) { } } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Scripting/CSharp/xlf/CSharpScriptingResources.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="../CSharpScriptingResources.resx"> <body> <trans-unit id="LogoLine1"> <source>Microsoft (R) Visual C# Interactive Compiler version {0}</source> <target state="translated">Versão {0} do Compilador C# Interativo do Microsoft (R) Visual</target> <note /> </trans-unit> <trans-unit id="LogoLine2"> <source>Copyright (C) Microsoft Corporation. All rights reserved.</source> <target state="translated">Copyright (C) Microsoft Corporation. Todos os direitos reservados.</target> <note /> </trans-unit> <trans-unit id="InteractiveHelp"> <source>Usage: csi [option] ... [script-file.csx] [script-argument] ... Executes script-file.csx if specified, otherwise launches an interactive REPL (Read Eval Print Loop). Options: /help Display this usage message (alternative form: /?) /version Display the version and exit /i Drop to REPL after executing the specified script. /r:&lt;file&gt; Reference metadata from the specified assembly file (alternative form: /reference) /r:&lt;file list&gt; Reference metadata from the specified assembly files (alternative form: /reference) /lib:&lt;path list&gt; List of directories where to look for libraries specified by #r directive. (alternative forms: /libPath /libPaths) /u:&lt;namespace&gt; Define global namespace using (alternative forms: /using, /usings, /import, /imports) /langversion:? Display the allowed values for language version and exit /langversion:&lt;string&gt; Specify language version such as `latest` (latest version, including minor versions), `default` (same as `latest`), `latestmajor` (latest version, excluding minor versions), `preview` (latest version, including features in unsupported preview), or specific versions like `6` or `7.1` @&lt;file&gt; Read response file for more options -- Indicates that the remaining arguments should not be treated as options. </source> <target state="translated">Uso: csi [option] ... [script-file.csx] [script-argument] ... Executa script-file.csx se especificado; caso contrário, iniciará um interativo REPL (Read Eval Print Loop). Opções: /help Exibir esta mensagem de uso (formato alternativo: /?) /version Exibir a versão e sair /i Solte para REPL depois de executar o script especificado. /r:&lt;file&gt; Metadados de referência do arquivo do assembly especificado (formato alternativo: /reference) /r:&lt;file list&gt; Metadados de referência dos arquivos do assembly especificados (formato alternativo: /reference) /lib:&lt;path list&gt; Lista de diretórios nos quais procurar bibliotecas especificadas pela diretiva #r. (formatos alternativos: /libPath /libPaths) /u:&lt;namespace&gt; Definir o namespace global usando (formatos alternativos: /using, /usings, /import, /imports) /langversion:? Exibir os valores permitidos para versão do idioma e sair /langversion:&lt;string&gt; Especificar a versão do idioma, como 'latest' (versão mais recente, incluindo versões secundárias), 'default' (igual a 'latest'), 'latestmajor' (versão mais recente, excluindo versões secundárias), 'preview' (versão mais recente, incluindo recursos de versão prévia sem suporte), ou versões específicas como '6' ou '7.1' @&lt;file&gt; Leia o arquivo de resposta para obter mais opções -- Indica que os argumentos restantes não devem ser tratados como opções. </target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="pt-BR" original="../CSharpScriptingResources.resx"> <body> <trans-unit id="LogoLine1"> <source>Microsoft (R) Visual C# Interactive Compiler version {0}</source> <target state="translated">Versão {0} do Compilador C# Interativo do Microsoft (R) Visual</target> <note /> </trans-unit> <trans-unit id="LogoLine2"> <source>Copyright (C) Microsoft Corporation. All rights reserved.</source> <target state="translated">Copyright (C) Microsoft Corporation. Todos os direitos reservados.</target> <note /> </trans-unit> <trans-unit id="InteractiveHelp"> <source>Usage: csi [option] ... [script-file.csx] [script-argument] ... Executes script-file.csx if specified, otherwise launches an interactive REPL (Read Eval Print Loop). Options: /help Display this usage message (alternative form: /?) /version Display the version and exit /i Drop to REPL after executing the specified script. /r:&lt;file&gt; Reference metadata from the specified assembly file (alternative form: /reference) /r:&lt;file list&gt; Reference metadata from the specified assembly files (alternative form: /reference) /lib:&lt;path list&gt; List of directories where to look for libraries specified by #r directive. (alternative forms: /libPath /libPaths) /u:&lt;namespace&gt; Define global namespace using (alternative forms: /using, /usings, /import, /imports) /langversion:? Display the allowed values for language version and exit /langversion:&lt;string&gt; Specify language version such as `latest` (latest version, including minor versions), `default` (same as `latest`), `latestmajor` (latest version, excluding minor versions), `preview` (latest version, including features in unsupported preview), or specific versions like `6` or `7.1` @&lt;file&gt; Read response file for more options -- Indicates that the remaining arguments should not be treated as options. </source> <target state="translated">Uso: csi [option] ... [script-file.csx] [script-argument] ... Executa script-file.csx se especificado; caso contrário, iniciará um interativo REPL (Read Eval Print Loop). Opções: /help Exibir esta mensagem de uso (formato alternativo: /?) /version Exibir a versão e sair /i Solte para REPL depois de executar o script especificado. /r:&lt;file&gt; Metadados de referência do arquivo do assembly especificado (formato alternativo: /reference) /r:&lt;file list&gt; Metadados de referência dos arquivos do assembly especificados (formato alternativo: /reference) /lib:&lt;path list&gt; Lista de diretórios nos quais procurar bibliotecas especificadas pela diretiva #r. (formatos alternativos: /libPath /libPaths) /u:&lt;namespace&gt; Definir o namespace global usando (formatos alternativos: /using, /usings, /import, /imports) /langversion:? Exibir os valores permitidos para versão do idioma e sair /langversion:&lt;string&gt; Especificar a versão do idioma, como 'latest' (versão mais recente, incluindo versões secundárias), 'default' (igual a 'latest'), 'latestmajor' (versão mais recente, excluindo versões secundárias), 'preview' (versão mais recente, incluindo recursos de versão prévia sem suporte), ou versões específicas como '6' ou '7.1' @&lt;file&gt; Leia o arquivo de resposta para obter mais opções -- Indica que os argumentos restantes não devem ser tratados como opções. </target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./docs/wiki/images/walkthrough-vb-syntax-figure1.png
PNG  IHDRnwVsRGBgAMA a pHYsodIDATx^_%u 泞'a)YJbG-K!ʘC\ {CִPYFQ{X[<kO Ji [@€b{yyw߼yQY'ND/oĉ_uw;;ĥyOa?r9BvSߺc} qQ#pblEn/]?VP56~)'Kx6[$^g߸x l.[wP.E*x! t!ȅ׿\7N.1VW!^kDYވ0z,%O5o\Y_| -y> #nwq ,jFγ?z!|5vx 0?{Y BI U$b<Xn -:w!fà'^/= e \;Յh۬o{BX#*Е <B Y+* O~ [o{B|,w'.D quFrXd[RaN 8ȃ\Raxo<,ʈ~8F^ON%000&,Jrڑc)0}v`|XdA)ΰ3qv/Vjx#q{[Ìb߁8gZ!߂]kg߿o/, }h 'D<=~eG3˅0۩ x'I7Gc-Po.w6b/c$blu ^ o5"^Bx~2Dhy)e@ "AQ#Äm~+BM5PՈY//6 /oo SOb# 9^ S]?`g.籅QA{ X q _]ކV/Oй Əߖ[)*-zꯊm^O a>qg{9yƬG$yT ۽Sf/&G [q:a❿7Ӆ ۽au"J`;<ʰAͅ[Lܟ=G8Dq&y!5Bl^Y:gINZ'R& G~؁ !w.-;rq8y!~6w^-r!`{)J4(_vY^ʸQ{ d4vB^yaV0P"d<M|]d2m^^B^UA`J яFqPzEb5JvJGNٱ OQF "|$ dFDvBpSD)į* 5B;)rBImٱ q5FP XuñA`G8B4FDvBܼy[nL{`=a]t+tb\FP/PPSJxBǡ0Vԋrٙ ytGpȌxtBi88B:prƱف QlY@@EL}r"^#";s!t:.pDPlO/vjŸ}B,4@ ؏׆$P͓F+v/ϏXtV)U,Xnp<杼`b}ϳb)vv*Hg\u ,BvPY2"D|؉lB _i>j@ܧH&-lB;]B_#IW7’3;P`+5b\6 È#|([Z/&dEd-kDNzg'/:h]QDk_e2)bs{:ݽf:i|/)$"gPmy/D{Rn X#Xq`ckmx!^hDXAISmh5ijAʄm^ng,s]؂n~ ѩ5oif :VB$3 ѭu%^y/J.ӃQx<*"P]FMpc ҹ /Vv/D9\gdɿ7aψj"s.6/D,Յҧg"~W_٘W_}|j%dw<[;/?faɗWYA$r@_|+_O<c?#ߊB޶r]gae Ӏk~Y݋7AleyٳϞ,`vUH>l]廎 #:d,uj}|٫KzeyD5_ _Wᩧ–P|*Gv񹶝^ 4`?uaO3*,@^rXkVU#.  }; BU7?. [d_7koʗ}ݫ eZYǝ[@V,<, H8NWo.9h R_}{ypZv.jP/TeE\&DL .ñ՘@ÓRߊ@b99l$O}j2 ŒW]o"#S8? [xh F| "QϯN?._kO#R? ,ph˳cVITyx>؜8^8a?|YVfD*r+< aÔ'm 3 <goqgt.O%nƒ>v[#^lօ U({ BM_K䳳KWa}t*Dg1za"FuAUڧ"-|~0^^: 5fU 5'Kj5u΋uA_#A|[$l%F. Nx #LݫU%* #kw\^^~)0n :>?t낰KWR@ 5 yR7ʒ*P\o^ R—w~ PY$>,3ۂa7.rБ7pM $\̅W \FkTyX=LD #uAإ71xti# J'3x]v*5<CE97rK Ž]ׯcnQXzNuj^ 2,*aǮ]օz4JmIs.}FsOj. َa'.ͳ``&t _ulOx]v.Aj5>+ǁ5낰KW<.?#'2L_8i2#$Ix]{x 8 7Z?ȹ ,^_Du6,DPSEaeAI/uAإ@sMY&!v*@W^aǮ U%##낰WAޤwX= &O. ƄۅY٥<~vz@#C N UiNGL~H $.낰cW9% M VF N^>on Ո b U(eJq] ؅; a%O! U};/._@UpA[;o{ ng낰3WwV?"^ݸ -Sz]X . >kHa#`o5Z.ݽ \C ``a uAU`h ~=Dy8/ݽ d7 ;嗆s}:'!: Ryz]~o<] |f?/ )PH?V U~~rѷ?7r.?o|lσ|lΝĝ䓌YgO|'u$O6˟;w'^F;w$3(!#/:6ҵ|+O =S&-@ gX@KwOԆ.^.x#tK"A]?ˠxH'_'=FϾ!#ξ!_'꒏ۃ ?ZdRG@ |g[ ubm׿.ZoAm@%РLԆچܐH^<{ً7@>zvqRnܸx zZ*[p6ďV^yi._!.0| / 3k ͭA8H9TKXl\l3m`%XZЇ fUv,֌3j=O/[O *F?w;׷ v&aSBax 9DLŸ66<7ԉ[d$cW:zI|mmۆ: ղ|gWgC}/x1Ьaa$m3׆" EFmE- v'+]L m(_ke'nQ [6YYVde9?G(D}( 3:"9q'2ʲe>bmֆS nc;ֆUΝ;`$r `.ߎTRBg!wYM)Oun`ddAlF`X՛M#0Imxaavks^$:RtqgBJȊk! }dXX D۷؆D@ r(H̃DFamRVdf)$j|kQZo *Ʀ 8}WO[ m,cՏqڻ6 6+J[qZf KBBGfC7ɵz=:Nݡۆ: kbA{%=0s尼5@맼8(#YcH4G$X|"E@bZmۆ:Ǥ} q*D!Vk/~c}$ ?rPkÊO8(`>AqG nQ\ rD҆b*ϡO4QdMkCq0 ZNj[  A9q"=:~@sNk^` #]RaG-<t@EۄFp`_k {ֆbpj̋<XYNV"rCk\'prOq\f,O{.^'j8Ro6?.Նy Vc@~y j@Br F&6CLE9R {[>~C 3|vɾA9Y"%-5]ۆ:^΋ f ]qI Mb<ڼߩՆG6Uֆj~p7#xr!!ᎃ%6N~Y^Òۍ_= JkC;'N{[>4nAFDʡ -0*/eō|r(0{ rti(KEHʤ%<=! TrIֆ6,*Jm Lm@m]VGE!)O\`hxXy@`0 e}$A?,( B;ȉ/?㵡+WW^sNA7[M0NM>Ƥмd"P b3^1^V},Yd"tC@m#Pcd3s68c6_䬖 B9w9IE *_@|ty~*ɏV{zmX/w B=3!aKպ!x=$Jfjzmpxm/b N _BR#2!A*6$^1^K2 #f <V/sf=c 0` U{m:Sxm("΃},PJ+6t.adkpB׸:,S=^/$: +kC'P?n㶼 dmݨ$6C';k? nym=g?6l<h@2ljgqp&nZc(B ^HK&6]/8M߀-$  `F_>ݶvsiUDy 0L +`}&ڰt48|&)TS_qu*GmЌ#yxm&t 낿48̀I0 V9\80l|haa6l\k2˙,A"H;\HgֆM!AVGCͱH$uQ'"ֆimXp<,7RPfzm 6ea4YWi=*#k!K$5vHu >&xmX;\}6^6Dh#8=EtضqBg;J_cOköOxmX/'tğ0 #܊(<Ԩn.}@ {[6]:ZZ63NbGwy+1ɍS9gr-$%SڰvX{[:uTȍÑ|N,}n w]Do167rbhq,FIkÜ_N0w6ֆMU[6}x8Z(?ސ2pkXrK>Iim-~ZGԆwr_ ` ' x#`uaT08a߼e|k/S= On6gaL؆i q۰^jnkmx|AE$p/Ph[>);U&ӟx1d#d%3>1۰CxmX]p3JAQ@ #j/KjZ>D$̌Jo.6׆@qpDkg M=Hr14HJ= 6m0/]XCz6|l!|??緰Ѳkf?en |\qhCvoC-eۃh@KᡵԆ]gokGg ؾM"d|fȯ?YJA]!7gJr.GB"{Z:sm6<8km+6׆:^~7~XKe۟1j*?74dsO|'^7ȲΝ}"ZAYZcP w;sw@e ࿗s~/?2~r|?;c=ƤŸw *D调@U@8xI@U@r k@qZ D^vV|p[?EU.0i1*4`A0q3ZA5=#O#КEP?e*xג?~gW_D&<{oxsNлxc,]g/RmYߍg/޾鼳k"oyG t_2 ϞJ UpK$-o\<{, ot*hU= S#Ky{;|B .یP߸JCP˔OYp\$ajdUxB[%sj}KS g'5YgWOMR귯B^<{b}l/bwFP/X]v);WzOdDQJ-vݨ FMBcUh?jW*oyž^_ ="Јҍc[0-UA_ߎ.~t&fACM @Sz}JUx l 7odA~IJ0܃S ql]hUzߙ*џ۸|U=^Y Ņ%:|E\QUaLV"@辂e*<s13X/X*qUx{{ϖ~ԃWg◞A  _e$̲CLT>aKU`KݳHTwV=QU{WIcaxU(sUF+㪀:.K̅rZK!w[o˟} ?(w^ߤ>Uc`W~ Za|̚' 1׆߼o %bɪyq\Gc\la1n ѮE i*Ī~?N/QgtYԉGAWލW81 ťN y,GWW_MʳÄ\y{)_}ʈI,U`O0wUxꩧ.?E!4'~Q +GH|6]ew>V83V|PB93" 1z@s #Kc]D$CqKj5&`@  &" Ea`h$ςcU,2Uaa}N {XKsta{!YwPЊPH چHXhm(V޵@]Bl*'W Z9؞ &{Apɪf\Cz ]}B<Ah]G*$<8nYeU2+ x>"TgF,3 t&TcU,_`WbaZWO1 e T>x |y)y,GA_/:BX*7ɵ7%$vy<=,8BЫ@UVu5(Pb*|ӈ0:]BWxU8 V*9( ЃTS i zP d_"RP*㽟@p%UŖOCB8X- 7"H:Z_4q&~B ,3UTR82(N@mxU8 SR?RlaZ2Sh] ξT,{I;~*h;Ë:Lt`N{* {G`*b':ˤUXKUuҪOM"W@Uw>ǫ‰쥯O"@`qZAn&klU}U.Dۅ(3TS w NīŠ_/p(^ *7&pȱy;IA?.VEpUEU fay5@w8_1e( QP'* lp({UX ^VӟBЫūB3q @vE?fIq@&愛I-y5V 9zùЀ]_Ge=Ϗ?*rV Ƒ0>+?|FJ&g>VO B ,Y `0w&MgANH$ 80<wT"ДUXߙOKrHU0oFfLX:[īD*.VΟ?Hf"YXs| " c;ѭ<.(8<G scW(cDžTAA9RWB%<=dFlUx 7Aˀg/`07(YG n CvPG#H<ytOApdd[gU4WuC#]U>OjGDG9*8 NīL3`aTc|␅ uB7˪ @8cU?ʤ聓 /-CH snU] AX*8 QH3g0`_Ķљ]07:Qjm]:UEonLѤUQeUzUxUX]_A<o?M)I53 <%v}PWA:<$S* [>f:q*|B,^H9(?2D.emt\&1`B\1 r#8 ̂Pa. C(抢˪"@p) !zFaV7F@<( W2(d^V&ΰxZ ^Nf+Ua.n Nd? \kU;l>9"§ѯ& C")G  R~D&K@ QkH(a^EC> ="СOp{ ^$jt@W*P.iTlpH*¼-U?9WeU?FpU||aW!G(zぼC' ὉG"ǧa^V."'VoϚ:AN~u"jO +cUaD*,W|5؉Չa5 dac}j·C 'ևWE.hctErL &lBE.RGD ɫŠYU ^W5"ɂ&q! E@(wM ;7*,Wu_E8~_ : 8J@(e-K s^W !,[K@ իQe9W *I>$!?m$⠂umUv#0D`xUp"^W+` k;|H"sբ>*X`[(XPMJ&! ׁ,<$hT"HUxUp"^K#z+!`c۞_u \ /:,9ͫI|d/U.nA5Wq! pkU`@%UaebwD*lz@YP^S?jWD2xUZ*]KURR8!|  ҅kvD*l f Qu&ǘ!шRBm| xU:!ǏDQ]d1`;N* s)ߛī}` ^ey >4џ$2C'Uak\~v?[}w$Rgvx^t*˚ Nī2ՠޘ.:>e`qJ/'HJK ^ 9??$I]6'BIm9O?:D*WXEVdCβj+밚JccU͛z>[&`?*i zWXWXU]*8 3޳Uը@8*=.@$(rYū^_DjI5* + _X!0$#^eVAY߽&D*,._|@]N]]&"PrQCj83[H>6®$G!3< Kaxq]E]9@!Ԁ(TjY&ْYF*BoD*n8nGD:\@IQH*:J'E#*<x0ū*6ZgN SD?@4H+"T ˯;-g3xUAX*w&Ǫɯ꺍d׾Cb$tZ{$1TB<^6~ԡ]T}NIUISeW -W'UzUxU"dF mHuY# D*|n*`W:NrWr#lUa)[v Nd»>( +W%Y/xI*ll_v[Q|\a>[v xB ApUA+мs2Sce $>zR e Ua$ߙ~T @-~x'H`ī²l*]@D*lW?U.@aq#Ig|Bqk>%<Ǫ|­X>J {\a>n`*8 ŭA"6{U8{F;W'UaIt}!j'؅ G&q( kdL$,L>E[S@U Rm*nocQ 6D*@p[U\l"a%Z{݅ }O2^ ?A[cU x?-8-gTSEs>Su tuH$5^_Z@o[gU8@}W_İ<J88,ݬxf#;BK<`P N7.$;*8ndWN_?joǏ'ʮ}"gvHD,8^Vv瓛d?§ t_Ua U?-fe_^\cUӟBpV+?BXpB9B*r>$zU8.TUeUx!@dU0gpVg @cW2wUUP&[*M=RTO~#2oݕ?(Uae* Nīe7]H8ȍG H%29 ,eG@7U$+ iiV PEl!G UAG&)_*deUO"@"ƺW'Uae1}u'2K ~]z._[[_A+Pn*|B,^^V~٫īa8Y+ Q|3Щ'TOM".#еY8Ǫ5UdƯ>֞k᧕R*9?Fe U!䒽Ԫ@(S} o#zaD*|sT f:*;I@rb?{E9B ϣl"?:?}xU*Q xVaFHdP!T eUD`bl˪p`8 O y5`-2AP CT .¨Jأaɪ0mV,T qT@.CD*4bE$JZ_x]-XvnSUgU 0fşf٥,! 6#-$>=<7p)O0 4 yBngt)%̵*<1Q$2$UAo~W Rqn ~~$EXcYL*2#F2 NīB҆BϪQg o:7zAOw>3L}rpϟ_?W lN4'xUh~o g_qU87v9ބh& V>QeUxhD*!^,^W'Uᗎ!{c#'F}S6(k0}q!vṃΝxΝxl9vB:,)خp,N(z%Ν{[?勑؍ pb8d/E"Tv<;73&4".HH?1 pL!]`PD)?p/d*\4?%_p?@[b{[3l? D.8s1nk_uӧ'aΆ98'\[p̼K ^?Miv>؅wah ҅/HkG;WakA҅ /]@!䯽ڥK(G*yrv/˿c-qz~b #.9DԹEF# L&Q ]'6BJRCL eyƜ"S^V`Yn̂ iw9.x7n_}6~tjcNٳP7qvٳ!)֤7.ܾډ݇vڅ# n>B-:gupc3XCN 8N„]׿cnbg%3;SAr﨣Șv.0,`r.c=cjT]pyir]͖Tm ql.$;8.tp|ًv W c͋7)<= cYz 9_bP[0C]8wܙ3g=x1,rI-DjM%jưILŖ_O&ghZ*ٝٙ>X[šP+P3څ@ dS z="0.8}b'4i~*0W~>XYxlrt & vܷO^b ~͛7 -|sqx2"ɷGӌEBy!CFbl. ] ,c^ko[~t1a]gv.uۅ_фUft!BX]ءp!h t@ .b>P bvϿ,m]3|gC^nPOs^uWmمI%څy;gD1 MA0_@3~W)_Esk deGodW!$h 2vxN튭nenw|T2#Xr3 3b[Y/$Duvaͣ0Am lm]M“|_~xv7/8'2eqHah$TIkM埉Z?e$?LȂp,';Wbv+c&]H;9wEK(-M}3CƏȇ%2l.ׯX uM1?(em bHE R@̅u6|I8Jq$N}cb|aFY9mv{u1zڅqaYPʫe!Ad8v # v|E!Iaa&x\#Rg^Z6fa5_dmO|L@ATKg:ڿ~+ZO}aMvaaЄ`dКڼn&::-# (\`*av[xj.`Ҹr*Ą]X4[w5>sI ^ZB W1Eh6Z \_X W6 ^D]`h]g rX1x+g2 6V+aMS3 L]l`GhUOEh⯠>ο:%w,|R[s0 o X.p!p]aniKbT"<Y1/Q5 ]: !m8&mG8(߈v:y ä-_M3i }#v3q5@cT c;Jֳ 2cń=zEgB 5l~UN-5*%loLb$tH-$U4au # Œt.\tɸ33,̢I﹇:?~73ȷ_oI=c[#\>w_:t.vw66١q;{sՏ'$e?G]29:l寉%uo 7ل0QuV۠8햡,_-[?V,Ćw֭&{/M[fv!  hQAߕ!}["A!<8 M|0m[$vs!j ՔJ _=EliqФ[1Ə,BWՠE6;\L :Av.^;r(z nz`FzJBh `覿0bFΉB+UI5BDTlW;ICk 9O?Cq& x'>*$K + 0U n5a ; ]٭f~ nY] Na1 B, 2^Ύ&FO(uIBQ{$<WSip:B"h\+8. j]UBE a+#(2j@# ;+.|a?#hb'|pw5PM{sA9"r J8.$ ;tva2BX ATP 0ߧvUEشCԁfAVZ W'R4mv}d]h\ d[(ʈpB_"Ɯ?\]}#ZЦ>;4.q/]'م?bpۅK0}`AC ' T@o~bt9}lIY#I|lv޼yv~!>arnB 6TO"MX6|Ƣ*#;ZSg]xchS fNq+6ojR4<3Br$kw993ypJsnzźB}F=n4Qm" lNGoӦy+sN1>I HP0p"Dj%q+Z?Űj6(8'vW.8Bh   ۿO.o%_LvgAXc^:nzE]xڌߧ\vk8B <fL`}'nzNvavhYvW]pVۅ^YCj5 0+vYFhiv^̡fTއu.VP0l.4 ,f3"NmRgfż! C><ʱm\R 6D]ľC!AyG6υۅ^ba+va39΅fgh W0s"nzEgBQoO ; `)=[3Bh f¶QG@ +6 ً#9^-vWt.2 ۅ^YnzEB^13,z VΩVj_~ẑۅ^f>i5م$^|MZߘ@; I'.-jP5FBh am @wp+Z»>_pNB!#!΂f1>3vWt.h~!M] PxD]] ]@[ĝ=Bh 2s"nzE] ݷ ex+۸Th+\|!/h7I:/{OfC]hN|8x?v<;uͅ䛴LUvW]X q+ZB2s"nz>؅K =U(z w&O,_dQBQhҍ"6Noa.􊽲 Ogٟfa1DG\F ۃLŖ-Z"e  ڰ*BN@i۷XhVC+Ӏv* 6 R#Ɇq+‡>'va$V`_pVg%]vs = tI]\@+$3-ۅ^WvAᵽHgPyqK4vW]X+jV . .>v9 .oc닏:g9APnX>@%yiB#LJNFX9f6ۅ^jaW삾ˀ&W a *`(7 _6D$ڎ D ؖE8=vW.lp"nvW.pqhV:Qȵxa8L=QD%=ZBEP_-,(,Y1mcB,.*Br4VdaGQu]mDswq+v.t Q.8+BOgurt9qq'P$@AQvT)R}R av8@Rמn]` U- l" &C4kIFP0 F`$~0 *#ѵnz>mva_p˾gM]` [hs2| [%kcaIeD9EgD ̲_)"&)ݵ{. dd&&û6H`RU.م͠M}hΎvW]pVۅ^ovW^zlqPオKG_ӯÑu^#ރL+ (ltj$m b~z0,b[;:nMa*Zxm U^S,#scw#nzڅvahtFp+.8+Bs3g~>A"q! ae*g[H}ѥTy;.􊽲 @mjDj@[, C0΁ r,[r5%P/@A4Snz^مyLcS /8킳. ` /'䇲vCB^- vȻOK|~)ҕ. 籽y&w;H͗{<`5+2HKX rle/P~y lCDF8ܴO#2w/\]n_=V /8k킳. $f|Pfի 1R@5POb^FTۅ^vA/e4ߤ@qIlK?kL=t ’ߌkKj/ô·ۅ^vY nzۅ/܀=o"@e.l07A;. ,g#AYWaTЃ]4S0#v Bg٭q 킳. 3/x O.ݻ(>- Khl)DV1?Bp0;v|$kh[ U fv풍PrRb8n=bY~~ۅ^va}$pFhS_Bp vByk+ӐרowrGQ+ԏ;$ ՗7 % Bt*Ig^V.م2 yYZY!pk +)Dq8۪YmAvU+C 0-:A*8(J3)[.vW.,І /8v nz}*t@2hTz H%X<dvWt.WCFUeb6Eę<GkeZe- ZN=.65 W%p7-NǕw vD:r_pS] x0*k`BPB5`%!Buwp+v.?3vvmE1 t /)4>ض}aP`!rU"<FqB _X/}h]h’YBp b]+,xϟF[Yh"<3{ v>HkݲU@[email protected]Ōӧ3KԁpFC5a#QixTa{FW28JB؝6vW. []YY nzE]/8'vWم}OvEu*2)Ofyhlg:q,F].s =@#DM OrA6~~ƥ5|bI.= ĝvW]pVۅ^j>cgeG( p6Qꒄ"68p ZB]'?(ӵeNBpvh}LB_!޸c55R8J~o +*re@VjkBh ,G̅6ep&nvWڅGdv`B(mQ텅 vW؅w}Q ݟ"(ԙ녅 vW], M*nzg%]mv2.^IjTHGiTV+8vWڅ0]rn, ImkVؤUM54 (ىq+gf'ZjQ 4Cqgp+.8+Bp!89 әgAgF+uIJ{Au6l .a]>(\}(24n VmQ:,mw+E[2nl .ާ>BP /8vY nzŞۅ2mܟ>$2!xA'SS"7T S!lۅ^WvaK MOHH0 3t&)$&m ʥ!Xh\qBjm9H46ۅ^j ǎ;va_pVg%]mvNJZH,H]ÏbeĤvFID ۅ^b'vÖ͆U "TNʡ2ն=YPgP.PTv\b J`+]څ%Q jefBh  nq+.,g7c۱3)۳$Ө-'NtɖW'(OW߰Xlۅ^vaw"eŖ-XaSy $ɮy?YVew+ :2(1lMBpnao jN0]pNBh b]Hc^]i] hO,˾0h!v3/۱h_KZE ,ۅ^b~>bc]Xeq b´逜p)vҞ&,0PI-0dڒ:'Ӹ]mv}İP[A[#ؖfHwT/Tva5MɏMJ ?!˦>]uȶތ^-nzEgBѦ 5qgq+.8+BQLChzPTOsyI#@~y:Kq.VIn 6 *ҒG ã[4dW`"k$8+S D,Bq+Z;IG$i, Ni I_pNBQ/۸P矷k_&Puq:;j_ jlFhj> u]pVۅ^)2Of%w9wIdwHLX IvWم~aMvHm!p|6uٝyH}A+Y?NߛU"vW؅ ~1 5@[wv .<v9 va0HQԇ Nˆx(;=GG#L{' v.څc{Mma, PW[|8[iCF[d&"t)YK༩al |قۅ^Y,0Q26mv||9 b}7"  c?:e]4ava}j@//h#ĮV-utaMH0z'TGٿ "6z|<j$} Ϊp+[`N}a'^2k0I5T+l%y9de7Pj9:,8+[`מXJ2Fq]-m}afYloV#0ܮYMx!5;#6I/9\):*#I#<BʁΥ"QeMR P4ۅ^v.ڰg$u؅w}WQ.ذ&pAnw>3'wy!gFo:7?G\䪖dOR%Io<#ȓlQJTDpW9nzFb lxCeX]`DۓHKaU;gBD7$MJ^FsϟɨDC0UۅdBۅ^G|9 "62]pNBHl nq+[`[C Ή]-3;nzEb lۅ_:7υBAvl} 4 3GnXu9¿C=Q8xA#ga+;/?,ܹ/߉;MF5 ;wp计O33|;_Ɲh|XBv914 O<wgVPHeD F̕5 , c|N(";8-Z9ﷱM_~CF b+EF\A)(h\] l!dC[K kй?4/" !iÉLDSZ2/7AA+o}+w) QۍǟgvbWF[F7vqiP-@.AwFp:4-8Rem{=U&ًKpgv2(@9 z qgL;(vX,{$ÅCVp(rvm'"u.['FgI0FW7ƚxkq.⎳Q:7 hա;; v~kk/AKE!sȱ$l.IN OzڍZvZ A?pA3C/Éq4xDQCI'F! @F0dgWp+ ?S)4s1 _YK/\cM g<[:8c΢Ǘ F# QuQpo(JxVWo޸|3$Qnm4 86j.dQ\$_͇@w!QppQ(Ki(- h[Oq_YiU| D(vZ7 3FYf଄FAC! F`Ɉ  a! o_Eip0/h ۇQHލaFAY9jyy{/h9} $3;nzE47 ( ܜ|{2ԍf b8Sj:;O,oiE:^Ԍjd;Bb 4,cb(v3RdSwTnTr:,l³"$bXrqFN0 !r3NCm(xk< (l@Gǖ^'!7o,=ZmJb 40CT<cܶ,lGFhihlHBD'J0yՌVH%0p8ǧlRTD|Bә/Jw)1Όl FE5lnJ KDX&O0s*z> Rs(Yj/XбFa[ݲak([KH]D 4nS [ f?b4u= iPebhd|<QPhVWqkZkf4 {@(6[&IҪw(7(Hd7hASD,XS=:>O\wMؖ?#4qǙ9}[Fnzś=E@؀QpzܡǘS5QpeQ<`F8uW^y%'7|w"ĭ-N^<U2ձ`:8O]BI!>S+Z[0CT]kyr< La3+(¤0aB6ZJ ˼IgYڟ\]>glp)ц3O4}(nd_cU3c-ь $ٶcL Z~qѤ–FI4>fy :9%qIF!1 !CT]kYh0P!7ڀ%'(Ajҏ-[Ye2vq\=MeShaPg)0 lqgؖvϳL;;gy:nzgy(uIRLr^Oa')hD^y@ec[c^46LX8%k|‚ōBXQؕy a*|&dЍBh5 ek/l5  nzgy(.gi6 ?޳<Lܙ{~(ni6 W^+\!DYlϿwKb;."Th\D̳8k(<Q 潁O,lbD# G; F`"ҨC;n+ajK:+H)&׫X8keFܹsO=TܩZ #6y Pԍ>CQaQ?K+(P[uVZ(CTX3g4u !;^4c[p\lsPBT>Ole}Fڵk>Sf1 /l{VӖUvOFWS6qQpq+(8#F!.Q!e0.l+˟!;k(|!:Q`l21P M<44BFA5k,_ko~ow!Gwj|;GDY~+_x_~q)9 7 D/+h8n @@ ?(T&CF%C}Os4u ASBHknGKM埕kLr٢Q zEFqǘԜV9<dAKihQc])@I!(pQ`niلQ("z Q(}sn?QaZ 7 EpWǟhƎY.ad∨ GD$U-)aXc")- Q` /.ѤxVG(OZXx7Ylo޼]ٲsFcD [plEx}Jha/X k~8آKN" '@( 6+I_wVv`Q}rH?4ik'Ae"8 \/GѼ%1 A0.܅2I9}dFY-mFycmc3c=1?l(F.vZY(<eꕦIoQS~#ޫ7b]y|EU3/ZIW3h5 g3=@\!4oa%ѕoDsW_SF|g>ɦ}i'*$$y-Gi:'e>d,v&[zv<c6A#akh-i4'NE*Tf& |z\Q.βl\X8$8QBiC9,XbMN+Q-F>UW ,?wFw"[u:ܲqʲ NmK.6HR`gɅ@4.T_h4 #Q\ƍBؖQ{O~Mmq4T7d#9CW-cC!-fԅ؀ֆb@YBM-]MqO{eO$/V?sm0- ìrQU<)lh;ڋHS~<E1ӣ<{‰7\Ex'[u#s:P(8˳QQ/ѬZ.h~A1TjZ<0PQ39LEQ>zm M5 +KDiEk 4d+a&5 mn7تkF!d!mP$q6;1$5ޝXF!l9^MS-gȸ5<bB36!F[ii@-E>D͚Q4mCOV,HB`P7 ԴgHlVh3 }!nbF۝c w",CzvTfTL`[_h8VvY~0<1nVKC@]hiA(ns]Hg*8 RQ*R32[}FYnF/6~;(0(jB9drG`)=nzEB#Gms+ <6Bg#^JNmU*ȂN@nƖOĴYe:Wp;33mC5y_/q}Go~󷟗 N$}ǡ.=)={), B 7v>>E\Jq#q+:|'}SX?F<#_}yFj}|Uc猂A6gd3 ~I\1Y[5 _N*hEV(daN!GhيQnFF´V~C^7 h#eK9v?hز|u`QQpgF!j0;?p}ß`\(M%FC>9 u@ABӖ6f5b=dR7 hU9_|ۏ˝V'2 ֗QpgsF~B#j!Qwě ,i @j hwK$nPMkfA5 hp`SMq(Kj5@B~$qSQh`Duo,:YMH6gvA綋Fea`"5&"%G\yV) =p+Z'jgh`vhilϡJkd v,&#ԕOa$( F~!vFNn)Tiakl6)j &i=97pV.?>-uh#(6`3%oV[} ,gyV)ئ?5CV(8˳"OaSlJa6"eQ߉Ud[E$ l5XI~xzYt>4K~N:+y }?$JYgv}iz(Džr8SA"' @qv4<|3zxlR~E0ԱYh$~\h[b%($Fu'jU:I${G<%6;8&C#8J=YIAL)QX94 qg6|L!eAѤ_7aݸQpgQ3>(k2!V5# Hh7 )V8eij9$lY7 z '>@l$"^ a(hNZ,oLHPܿf(mF}d]zi{]0ZX,]OqvxP׳m(pQExN-~%*9cSV? /(>np pgPmƔkB6)Ȩ)h!b)ĶA݊1gE5b/(('?bڎ37 (7 Jpzi^y طTC8:X>@.i\apQy_t)X@WRm8Y@y{hTY"A_YdA}dT % G "fvɁMTBes&(\~=* 7-B|P(`zu\rDdQopE%(ۖ F]gE4 \I! ;Iaꦅn1h AlH;.zX)6 &W(t ɘQpǍBh3 ?Ug nzgy( y_WC yF}&][p+mΝ;SOŝh2<!7$.ICg̋68TI+&w)p+j`Μ9S3 %t1ڤPU4f]A;s'(5 r,&"8'FW(\v<uT(Vg۹.@םk"HeS\=(UHJ( k0;nzEQ>0;nzE( 7 QF!:(NPBK2F`w[;YY!P`^]P|!#hiY.Sǭ9@,6kC%s"(DL qڌi|C1 O ؍jFMZv׈y_$=D(olt BؖQl8hJ8G6Q&9@mXխ6{FX&Vh%8'87 b[FaWP1;>6nq+(8FWQpǍBQ!/,2]T:q˕T\- >aDP+fG2$Hl{^j q7 n/8H&,<`kxd9;bp(5<.q9`5/8QZ#-|TGe.0c(. hlh]ãɆ<4< kS9<$#fc+y\leVp9(Sʻ@\Q5 7H=.B/UmCwP@cgrÂM7&őX9)r9MugX7 )8DQx ;l?#gco|޷ՍFW+LBp,^YP75r(', Twbe@qXڻM?qQ5 lÜn -2DQ>I$' /GFf%R٤wBL@Q@;i I"Hv FWO3DՍS&I6 -[;[ TPR4 (>$1O*,b^M]ᡃFWt() s!Y-yRki([ Hx2Q6Y(pN$ Ģht(t 1gWq,^FY7 <nzEBDO˓vD?٠ ]=\gq(wl[i3 *̪os"Xa]=)MXTAkdWd^7 (| QuԿV_ӭ@,q9@cP#D~ց=3 nzEQ CT])}?|;]6(]6uʵk$2H{ FWl(l5 c sFWw}3 QqFWQpǍBp,^+Fcx(JՑB΂g UdF%(s=Sq'U[4?Xy<QB܅Z,}Sv>@h8,[sMRP8Q Jޟ24 gΜFhFB5qhZ>m0| Zwer\%ZNq+:h]:ujS W؆Tiab l[r+'tY%)8JBwP>*FQ8Sp+(8FW>Ug nzE??=0zzsdѢZ$_$f XٍBQ.P[Y,] ~<.q`5>E܇QeQQ([[cQ/ o(]4 11OВ)̃mͻ8@2*KQh8GȳIO1GR H>]$fd>,FWQh^A h @?/Bk ?,h#18o¦O0G4@< O?(;gVEς5 3c b>U{}hÍBh5 e37 <nzEBY_h}[1Q8,OwodѦXZ;se ?`{)ǜExLB=t9q+(fOӃ\ #i2y p}$]2Y4P<_'ѓ>$BGvHQ," F qn) &4x?d3vh9lr nij5'"hcLm8VE!¦$lѤـqXgb}ry\*% hRI@rh0 @MFW}!&lln|:4HtiZ<4"p ۱Q"CY"ƅM*3;"j}:&4`D%d^M8lSpFa3h]!(, ʆq+(uBp,^FY7 (|!,;$I yM8LdXB+s:@[')㔘 4I#n'}3 [&$! TnUY BCb:I.j@0F2IQ{ht.s9I%(Pyd#)8+`º&BQbĝFWQXuBh1 1DUǙ^FY7 (jbY_}Z cvX[HKM)eX'+8QFj_Xр[ " WvVi CPVHU2bC.24#V<+; k=Q1 h0aiEVǖYEl|"ڂ*b?16 <"H 4P'5 4U7 ?F}FՍBm$|BbRfQ1~c <u`V$EQSpgy( 7 Qnq+a.Y.yaބvaYޕnVĈ fwAjnuF"lUFWQxb,m MmOwûh Dwmg]b3~UД heJ|PGQebU/d:^F;ВI#.M7dvnџ&2{fBmՌFR#<L@]Q;gS7]zptlm]qmՌj`TCDdEv(tm@wv7 <nzgy( 7 Q`O|IIk:[卓ar nT:!ʲkVQ7 mXvAw&MCx\jq15|YHښd;\[AߪV O6t7 bPB\\OYL!`tBnC(X%AKPnzE@-H %vMm/7 1ԕBXʁX[ FAos0O { `ƹ-(,)8kč<nzžgQnq+zoh oFE̴JUFKudzQK"3 Ν{ꩧNհ~4@̲v7CY|oI71S(k40$T ReVSƍBQE8sLbd,˰P nVCʠLBG5iF٣Q` i(>k׮=N{ gXɮn2oFtiX%ԁwpO }2 D2E(8FWQpǍBp,^WFa0HJ(jtPR4Aj.&XyxS:h^WFW^;"+m`aJ$Id$W :s#5]敗&Cïȴ _f@Q2Ij5(}3 ޼yn6,.aEXuªV--<dTK˂V:S r)m!1* nzžk%hKҢ8Q0<<dWJg*-EA.,}T-5FWQxcèQXSpg&( 7 Qnq+(~0<aL<IBQh< 8 Pg,< %N2ÍQy#7 bߌ<cmuiGR.ա5BΦ]>"d<5p 9$|rl#U{FUT@Uvv+("<qM 5!lh܅@cFwm[:\c ZbA*U7 b½{*lh-FmN6NaVXΡPF:+ F=geQXzׄe;BpB?p+(8FWQpǍBp+1VQ_mW'ʐa9ʎ%wӲWjNCm7 % Ci,0"?("+cj Ym5 ]\VIm$NfQn,ׯ_=,p>[u(`2.F(`+hVБOQn"H^ t,YMD~X硉GҶM1 7 lCDFSpV;c3z|LY n~DGZq+(8FWQpǍBpB9[opZQ~I!$2w"QnsU=؅(e_glp&Оvûұ7F=}LXͳbRp+(X3g$Fa6Ϟ\BPJh1e{;-`x8Kht7 vڃ>x)k "1 sm]M[q=s-ڧ]--IҕSpֈe#cAhO& SpֈAdnzgy( 7 Qnfa0H;CSur+A$c -L&5R-u *FWQ_z5lH=͇HbS>*QF5ȶ*eg#YS 7 ,(`k?c4q5͌І""Qy2SI ]W2A#rpKFWQk63+m4ElUJIY|4Fa^ ;4BpA|7 <nzgy( 7 PmvICy 8B;7Lm JNBukp+(B}>MDvXȃCډ6<lC}lI D21ƒIR r0WٱGPԨxP99JQnf>OMr(V{]N4@ckP"U4ca|Ti'&hv͂8 A.EvDtnBEQ0΂^Fah3rUi Յ丅_Sb]"n# #BycD&0#c5Qnfay I<#ژc7 -`%zøQnq+(8FW($yky+~F=$R$kԃ,F·÷dhPKiōBQ.1$wii IGPdrX%c< :z~F/W$:*As=X7nzE/|(] 2$)IA!B}v!-th/0 0LQQP+ t7 FZƉ-.3Z>vi$ryD Ц[s5 Ͳ(L$2}R4Vbiʟ(ଏFa|LY#nq+(8FWQpǍB`YyP<hRhYpЌ@(l) (sM|j'|W- I Ү2yɬA Q(f-]iRelz YX۹F@PRoo1V+s+Q4 gΜi4 -I˺Kte*c4(v)fgSn2E1`(FAû\`^Apڵ|ԩSF!4$iKt:q43֕\LեbE2vQ`gj}+Q+e:hfDa`;;B3wv7 <nz;Qnq+a8}M',vP-.oDŚUuU$^F4jWLHȫNJb;,$ ,,DROOb PB %ȃl(]4 ?p xzBUcBFE,f8[:*kiʏ%W}Uדnz{T xl{F˱\@<N.UK6$UwCe#MIDM8Jm@ģQpOY;g6%a;_SpֈYQ%nzgy( 7 Q7 6OfA_Iơ{ӱA:,v<Ub%X)icnzEB}!!Tk, B3[V,5 dD$-%X}I8䑄FZ9`W :ȹOyFW(b ]J<4*74gYOJHt2$Iʔl+mϏ=7 OFy!Cfu-+2J\vTb*S:QeLs`z-yF$]*6*Te#dq+d@AgYj;_h nzEQCT#c֊^FY nzEQLB+0 bb<6Ki玳, w̴D䱦o7 (CT}Ο?ո`c#D8Hhc p&BX8Ԋ#$͘8q؇)8i6^oFۛ7or]=F;1rn q;'QE(dD.+Q'l7 bߌ@jx? BP 9VȞߦb6G\rHʱYDuN8a(2 zu5 c + 7 <nzEQ,CTu)Q{n<l'juYdN#J]08ʎÁra~P0#Gtn $kQnE#,Kɬ@$+P%Um[Rs_FZlEö!*8((!貜 a:Ϫ˸QneE_(cIaL Pfi0 o dDItd r$lw7 (| Qۇ>IUXn ภQfe&tYSpƞFa|L&nq+(8FWQpǍBh5 2Dg'S{PDu"R^ଞ>UwXO!j)upz|-SpȾl;h ( g)8kdߌNRUQ5WFSXnz^gMQnq+ڌe37 bB9[;VX! Z&PTgXO,7 (|!ΝK>E/OaZ<z\ãDPr! "S,HfC$25rxt90:Y gX)sKFW("9s&1 |f[]Mb̶}$qD5urAHPGVmǍBQvڃ>x)kvl:1^:&2II֦Bqdl:@®-"NFW(Z]ɯ @k+Q{h'}*C(=4 q+(8FWQ(ꈫWGwuIkQ{dfԕ]AVFWQ`p4 lfpf46nG>(K `bߌȏoFPgߌp+Z;?GR14"ˎC<IЇxh֔E*moFh ؤoFX+7 (|!4o4-40Z $ρ5 l27#b3Bu7#(6{f}M.leql(.nzgy( 7 Q{n`:}'d1/Mqn^kb׾Oau($7Ym7 bߌ<cml|O1YRBƆ 9.v4]$B^Ծ `W[|!ߘ έBrx^b9< FWQExN3mҞ j!ФنJ5캥-HtvQ`,Y 4^FWQ{O~Ӯq`lkf ! .6 [$Bk(n_#>u(u"]`{ β!bg#ڂ;čBpF5[FWQpǍBp,^f_0D=Fkga3bq;#2 'g:Չޥ>p+((#Є-7#b{D b9"T)fx$AU8ϣt%t("VwU9 wmDVj:8%c9גv+Z/ji`nٖe($ )f4{XDDm46R#UҒXp#.KPYOǎQnF`^:pv]4K7lq7|Bg6`v&\&*iRGh$Nqh^(>Fay8΢hC]c {e@KA_UFW8Sp+(8FWQX <8˨SN.֞%YUKF ~jeYэBp\YZ]{vP`+MrB$fa*+oIT!ҟPS3 pV.t<QX4WUaݲr֥B('_H%YlP'![C/7 b(c֭mҸx%rlJM%Y*`F0"団SaV$7 ]`a|Li5 3'/P^FY7 (|!:(2 A:'8cro Q? L"@]'ìčB+pWƝmiq=<)D#QR skHqPdрDh8@pVD|$plo޼]4`6Ka[Dؤ%9ɌnC,0ѠqY L4X7 (O1DFZdoҤKLZ$I9Ɍ(,<рr;-@SpV^_=: yYSpe&( 7 Qnq+v(V&뎆UVI! f|zхUmu̻b7q+ڌ!nW$"aXC-jBE5fS-9|y!.rBMYI @X\1]It4C̵nr7. i_a`;캶7]=[G8~-6h> [-I$j7 ш-pwq+:hP5hҤyo4E-H0lٌuWIǖr+Ԉ&iV?GSpF®Fa|Lnq+(8FWQpǍBEP_BLu慅0"Z/McKs:עnºq+v(ԗEHVh eU _+,DըZ %-;$ad+t7 (|!v(p-+O!rZlހ[صHQF:d+t7 (}d,BQ+#(@* `SC-I'kB *f]T,aFWQXɲpblf/)8]('jbjqY7 b?Z( 7 Qh``%c<m'haFiBlA<Z)ȶRш?}p:͎l÷&Bhn`4@y NQXi0],Ja}sputV |Bp+v(,SX-nz~gQnq+:ezbݬI3nw~MT[&Nit+ڌ{?U<cmZd; !! j˴Cfƭ9KYtv ?B<U :W[4 ?p $m [6m-1g@Pk W`SROuX-pGq+eSHh0l?h6kMCT >`-sß~x8էN=S QթFa|LF8Sp+(8FWQpǍBQxWb,w$N3(|)D #$<ҷ ;{Q5 m\pM^.8Oa͕P^fv,K*: hU!aq)%KRY9>eep+l_cjKhR(l-r4N rl%WmF!_p]B,AL8"<=BQ4.v 0m[hJ5,h!flʏ:\ P=gQX 5 c W^;gݸQmFLBp,^+F,\a Ivテg!"O:PΡGr1hҠ3mߞMQ5 Ν{ꩧNlA"F6& P~Tu6oԧ$SFWv,™3gjF3Gh0_gHO?0UgR&Cu17GӳnzEb 4l(\v<uT(c\7б~Au? bAGPc%:8=$@N}!mvwN 7 FW$@>x Ϊp+[3;nzEb 41m.eSmRY_t2\JlK,:ʥLF4qFgt&TGTB>׍^ ;jr.,; :!IluPhRG/>=iw2'C. E~M"Z#hȈrp,rD`(u7 "(<1mYK#z`m@\J0 1f+˴SǦ"v$"F!}Xi4 6)p(hi@ic=qZF{qz.2qtnGK9G]HDxزSS:u ;gvmc κHl7 Q-а&/*8čBHl7 Q-а&gd4-{rlDz V$ 6u$ `*ТQFW$@C0 e@[DY!Oḧ3LCtn\BvSSSޒVO (LW^ 0 ha%FA3Fs?jf%WlÕZ sAvPƿjq+[aF qB71GTb 9M$'jĖwyn_%z,nzEb 4(m7h;_&ōBHl>Q lAp^ k2 N/q+[Aƒe37 "(8FW$@gv(hp̎^ (!CTu)Q-F7 "(8FW$@gv(hp̎^ Fᗎӄ^ n k7 ۸l[$@q賯۟0M  㬉+y ;x7;w^~",;㤕-Y`Ja i_i^v"ILkΝ|=/|ՕH$AD9+?7q`qgWx 87u &)94^'>ug!v} .h_ >?WpW8Y) :lElr(*;PB_ 3=I} ܟ_͇4`U (&1E UČ*GUli0?ql; qO/!N :D8 l#-? 㬃ƮD?zH0Gc4m 8`XuS3&Ӏ}TI}U gN>"񏊝wՄ8Q!㤃笰NQBL"悰ҔtĻ,uq CyԨ0wH0rr+@b{IOྂ8 m=mM;LUW#"IF}SjtNhYW "1 b U^4DLL?_E<JCϱ(?zNBY}~7o/+"zF?{}wI,k/]Kܽ#^{Yx#!Yx/+8ůYW_dDv"I/0 QX_a)Q2SJ8:`_zWyVTg^com{q*C5--*3$qVOE8N_j҅G؅ ]|ŧ >iX\[Z+p7/."8:p_q:JGo/O9 OnƾקC{gd޸xcWg+.ވҙ)C8++<7o<I*B>}8cL $$1W\ >ՋCիѫw=o\r)eRGۢlkuBG?`r* # (ɓ`pEܽpV |l oyG̸8H}9ʕp]9O`u5 zVX4WDN+ű7K QHQd:,6_!qWpgIV0pp.G 8*x 6xϡПKG@S  Wp֊ ?o>8Zc$DwΝԩ+y ?_GHRfbqgƾB.A_A 4>x=o}qZ|q¼}qց Qn~uྂ8`_bk|ʀco}> Ȥ(m9iyyV&Zh3$~,A||$ f,hơͳZ-B$&LA $%|*r/K>h{+V׭1w t2AW8i}W.LܯIpZvA^x*%*SA2>Y@zUPyt%W8wSO=w&A{P 7qa[YHXZѥw/ zwjڸՑ]S㬕 ‰L$d; 'C@ȹ8) fTx<I6L=OԨ {,_4g%D|/8sT_7M hC$x3;BcP 'h$AhLJzZrR4$w6=㬏 {BP=&ǵ疜gᑦ^Y'9I"iNC]xP$.<n7QP5jWIv"K!Y^Áy7kO6,D;x"dT-:js yP>`93L8+g-sQ? _wu+;W>b FvE,dvxt")ve\< ?I {t$h[x5 4<}qVȾ rsZ:N- "Aw__!>; ΦX8߿G  t﷾?ˍ}qBx_Y aOpTsvxY+16okjN#Ht䉆v4Iҿk4/ }mgNWKB (gQ،|}>@Nou_W^}W~u ,qҀtEҢ SWEQU}MS |__diɱGu,+='a#<4sg}3{A9P5C0\0)C]okD*zH^O`*QDQXx Y)5)_p}WI}8'~_WTLDžIخp7oR# =qO?ގL+ |("lz͒'{٦Ԑ[vPϘ  3+0zӘbD2ޠ(@},+<Iؖp…i^IqFED!AؐW\L{Ъ+B M7 ngbB!p-D+ /Bϟ*QWvWX!IGWoWgh%G⎂3S}q t8NGp_q:ʮ J?g>qqiX9A%̔t캯+KQWJ$>4Wk'6V8 +8NG遯05K8F5BzJYNROv QWp_WeBz^JOӈWhjr}( M¶|__a">[{Tۅ'q<$C/]uA&$渎cq_q:ʮ +DOT=z|QQp㾂t+8NGq_q0Pʗ}Uyҕ4 V{φ\qqXWxI謯mMKf0DiHApz=8šz21\q!P8{\+3 pb<x#V>xWFC{a4&g bA΀:!9+u+;w;Wh nN/^وM$E>љμ #n 7@gLwƾ$ Y:qqv|=$lW9sD___)jN' KL$%7qWpz fbWO?о Eѿ?3Óq QvWI:NgW`"$stP.Ћ(+8NG齯0;73&GqG}[Bk,+|, =.c__:# * y>#f{D_qȸ?3e/<k?/'8NGW@wȳ GbUfW"&4['||W6}_/CJ&K%d;W 懿vJ4{+160 s3C[h fѐI ,yVdK4< E_n~q sDžͅBZ;g_a28}EI]^W0۱K>I1 A LxWDWpV ϟkn_+$fR?j 9<$_{ƟtY};:iV"qx@|8 a"0D!3}PໍnAj̮yPϾ#<C$hfju[<a.w&d, IBl.ܑCY%p{_vóOT: c_S" h.9xeĜFz gOX.[D t .l=_>i1>)nOm}^˧E7EjR 0)Bċ!r4%^; Irچ0W dځ}`0mqͰ… y D;)Hqk/g>oAJP| TLrS현T3j|4+A3v!O, p\D8rq ,+XvWX! "5Vb?3{}c«{bNsl8fp_qe_}~|gʕ+aNjdH$4pᬐq6Ǔྂ8Km_o}]IK$OPS[3"utEbW_q4v}MՂk!ũKQӈ?)Z7JiKkqUި12gY1vgNo'PO:)Ĭ=$xx5X{+;wұ|{qn%Wh9C$%ﴓi?Vo>A{oj5E9[6:NG[_A?i+ dE鮢\$iV xnyفL a}ryM7Ƥ95s0fq=C?_,6 QDi*l< $Ƒ$e&x9Kl]g[8e1_>Kx8p{tcwUZhҴx"mz{9cm<6+;(b>S~q?_a&Yoq+iW@jrڶ-WpŒ$:iYyI@5g}?kgF;VCv36fĩ&SJ}MXrárgQRIKF9Ӈ%1L kbZ]LhU"XG<5aEtd̶⡷xqIEa 3*7RtC.fp?q_rG០>͚n0+0V_=PR۬[@ģU[|0(u4 î*Py*T,l%H`Z"UBϗ8~h Ì&DhWw3Ʈ*dd,pB^tj!+8R__Nu.3n+PzC,]5c<[.\j xUH"WˤHȋĨĥ/hMrAILwۋȧqǐ(OQg?x鈽2Jpq_qqjwܼxKqGþt˱`Q_aV&hbTGx`7E:OG/2w$E-+ Ro k": sqiJq8 }Mc\HsФ"L`0}r⢅k\'No|b>LJ='}"h |TPHWh[k7qgo|]HM`%>K˭H-a􉱯.4ЕӋ; @ΣnqQ0/'.̐ I8QIKQMfap\H6 nIWTCoI٣ĵ%wྂtfgօ+m?_#A8D1LK\PI`J)ْNop_q: k"֏;uO<Cϭ;0P:]լr2Jdv8}µ7WpߓWʽZ/_܇He8YYq:k|Q/s^xq>Wy=E/<2ȿ|ufȏ%'qgfZ^'oL GG v WpV{t/BO顯P~&_с`^?“wPVlZϠ+LLHo ҵTA=tvjU 2ü†%ntA,|Эf|6_aZWh.<tQ~Imvۑ.8NG衯\kO?;a8}zÀ2yߘW2}TBx.ԱG$SDB OHJ@J%i[hl_,<;< X`]i٧}/?dA_!\x1q_qqyۮ.<v+(*lu_AʜfPk7SM@g3=0u,OёcԳ/+L)Į4 ҧ1:6^'xZ>%Bq֓I+k1xBˣ@#1nsytΤyWe IDw1(w:mtΙ, W^}W~ t1.А&>#, "3;YWDW8 Ld޾]5= 7Q,4?Y}$mkUzD́n⾂t|wIp_D+\~͛$hg&jw|`XfV ]^=큜n⾂t$ V}Ÿp4/f~rzesz0MsIWej, ba&גUEsZOHZt $ V}gB#5!]; B;jGbS--PW# ] X' lj+'ྂ8K]_!ѣcJԧ›H4 ~'8:`Us_qu;BIXx ڱPf}@20S6X5քze҈ ˕*ãq&()$UR.<h? >q:ušH: ?=Nsw[gV+ij1 %uZt& ?._u Q6X5D)PYq\DD($ʠ%W,R=nOK=鯄TӝWya$.<L o=!p_qu|O&}ݶV ʁ+iٹkreaL9Jԗ^_ q4 rdK;d-=z*G/wz-p" j4[NC"wzsDSl=d`|hLjL98$c 6X5Щ7cn_!}AvͮG9"äQtb?8:XֳU`:Me+03`t$ V}qz| ONX !)PfT&x JƾBLNqušIڟ?VNņU㌰P-s&-a^+.v7 v~>32}sX' lj+,ùsz꩸3J|FeK* {wī%Xi$:nKd&+8NGN@`Wx'‰KxΜ9sG(MFdJ=Z?Yh ӹjjV$Iq0 i<pP$ԧ |Вul]L,pgX' lj+̋z NF w|`:M9xxؚf\$3&Y LWnmӉv:A8k-:`U[[dWX OqoVǍO8 P~0Msဋ Y@+H|XRb:]iH2J4q>n⾂t8$ V- `քO(tsY' lj+8Wpg?8:p_q:[u†y7bl a~y kp\ȇ##l!~„ƯMeΐ$˹=䃙dUeN⾂t8$ V} sW+qJ|FY2.\JzwçdjHt]FWpgX' lj+l Lc 4rz ]2<"S-~P' MTtТґ/^Ƥ)%'8 QRc^;P5gH]ǖ\uL8:`Us_aW~͛7)IОL: }sdU]Z I$IpNz>2 I_A1qLtDZؒΚp_q:u†p4/]fx_{Y郫GGPw6i-fnÔDg;U$G׼4$ #&Ŧ~@8p_q:u澂B>1q Fp_q:u&O%}q}( H X' lj+%k tw괤V/ d*—K3Cx;F~+¯;͛OQ4J g8:`U렯pܹ7?#4c޻ؗ3I9ڤ,YM'. t09}( HZ|s.=HbwT'Մ:EbIJJIrg׏;'ݚϯB$+0;AJZrKܪQ}ڡgyWpb?uWP/zp<Q=?:KS#¤賳?>nS!8}<2ܚğ '5b˱U;, Q6X5T5p"73=܄<мD!X#)x\k·'Ujjݸ娄E1b55cG S)ܟA8k}( Hn =ǽf(8k}( H X' lj+8Wpb?_ m]_I$#=>Ot0gnS;5Q2X' lj}:0b0Z!G0q|{] SX' lj+ ;+tya[=6P+:V7!.=,|IM ȻSN5O?EIX' lj+ta8뗱JBʍ!01*ڼ8av r%Q&ƎZ@Np_q:u֏qIK&䡗 Oǝh-ǚPaL)0CwTEu74->[{TwYQ-6 XUs#ᾂt$ VmO|g~=kB|wX' lj+8Wpb?8:p_q:uocS(aqeGø_1gc-6I68l8R?x5P@A °MR/*h"QWpb?_H ϟz+k,c;*Z<K7ZR5I:z ~nA:V8<:ᚔ̆D>AqŸX' lj+02cR;`jBТlpMXC j[ID2ϖjVAqR'|01I mP;s8:`Us_ׯ߼ybxorƽZ쭣?!BSB4 r8Ɍn[BbXOk:+qP+v' \?s8:`Us_… Ӽ2я߭Cq*a|*?kVB}\(8$7cq:q9Mx$hNn<1: Z= WL<H2n8:`U[I_H_  L:+'{}( H X' lj+^YX' lj{+̶B:>}p8MN) It`2gH fC<̴s\dwvX' lj{+̶²B,.\ %?·@n_ph|gsٗ om4ƞ⾂t$ V}FZW.3Db7)3COldyOzqJ,4ڛoSVT:O?UIHKB2`>02DN9}( HZ>}NZ_!to.YֻتKVمDd|3*@D- J=D'쁜>ᾂt$ Vm}W=txYY2A`J\5& 4[ $ R+w 3L;$.\R!T<⸨$WH X' lj{+8ӈrąrG8:`Us_quྂt$ V}qց Q6X,UwayBY-D*U_CImlE*?y惻T N>s2F%f$EqW8+}( HZ|s=SqgG|_!vUoEI[a1Ӂl9J]h%rY wྂt$ Vx̙3|>r˽u}`@Ы(Gws+nc/;%iX9&;^D^-%Գ8Ϊp_q:u&>Kx8+(2>_ܵ]!v!nEHpVjLʄEŝ@]b4O$8㾂t$ V- I΍+;86P:3PQnu"qE3>"6&6tDD#Rd9] gp_q:u]L+tv CD(8k}( H X' lj+8Wpb?p"i -e] ym_  c`u`>ᾂt$ V}jy=uU4jul,'fQ lyQSO#+8NGN@`WX ydæ$BnzK;5K [M 1Ŗ$Nc8:`U[_a 3L O B1*;ltRXl9bkڡ]}( Hڞ+{2>tסrSTf.R9TME,y,I-= aB9x0S$ЂՑ]\Ls&Nop_q:u澂*o`oZQ)+8NGN@`ՂhWpgIWpb?8:p_q:u&M +<."pPLW ܚH² hȤP? RUGT]Ockh:+8NGN@`WX 俸?v_A:z dun>+[DcuƟX' lj+,l 3!94C$W!}VDBZӭU(ƾ9v̡x&U@B !5 rĞdBcp&=Ӹ8:`Us_a^Y! ~TBDԪTVN~ % bXݻ'٣oa^iJI4t:%u ^Δ9; Q6X5DYBu/=bW(~IW <eJjAtqvU<^~y+'LF&rBKdgwq_q:uNcJ'=N㾂t$ V nAGྂ8K⾂t$ V- M , Q6X5FY/e KR"T})Q+šL$h[O/wJKl"<=|ZpuvXRԏ"'+nLSu{SŒ+7+8NGN@`WkC`t!rB.Yڏ-J~.5nu4QgK,X' lj+tzh%l콩&H3@_[d*@Ђ$gڇaPRBDQ{S&ܔ;Zuy3K30K:GI_=qbVδ\ᾂt$ V}ГIG;d<` %XycӱbBd7BHSL%=|_+lɮ^o5~h)%tX{dӠS"*ྂt$ VM|}6 +lНħÓ~.J¬z%?/7q FLѫB YU'`G#.}Y6dɐTj1K;Cs5؅xPk:,F&rapLX' lj+8kBѸaد5a}}}( H X' lj+8Wpb?_sIp_apB vR}#`u QCƼZr8'^3䓧fG<J]R\+ZX' lj+t^\qVo 8Q_иhٲs%!pOp_q:uB7IzǰޛNC v|e$՛ z|beQ\ +8NGN@`W&IfwC]Q&$W}e-#۰#F}A%cWpb?MlOtuqtlqWVr@Љ]x5өғ1eDrfq5z Q6X5h0}euྂt$ V nosIp_q%q_q:u澂8}( H $<e9,dՂ|pk EVd`d- 27!%,s$eɩ#%I R 㾂t$ V}5_Q| >kx]x[8 GykuWpb?_Ꮣh"o0vQ]ROU񓅦Zuxb:hQ]{LRrrj:H&a:H r1xfq Q6X5ք[ V%K<ѫi!l-$$H凹3*@LwuŖFh9lX' lj+^Vtma0M@ ,㄀x$H?\,]#NeˑF:֥p Q6X5IbSBp_q:u澂8}( H X' lj+[dwW!toc=rt7T?p_ew<@vwe;ȣRBRΰ(X($#8:`Us_aΝ;SOŝIlO\ZRBсH_^{4 9}( H /8s,:,&2'x^Uۣ@ ɔXI%*I޺&Vb-MC;z <Ht8}( H ^ÁY|ҐʻdvBjS\HH vym (N6q1D9 Jr8[}( H kWE7ОnORĤ0bGymʶ{N$Z{&Q"!D9q( 㱊Np6 Q6X5`o gBm!~; }( H X' lj+8Wpb?M-c2\&L;pK:PM9įZIw@{9|2|#J~㾂t$ V}vl;Inl1l?|]g2?n(aRXtS>GYϘ0K9WCS}( H ]C<7"=~Q [T ݘg jzs,4y;XTv7!pD\!u7"lqg ?A̯S?⾂t$ V}2:gUJ2Tq+TLU_hVr=Iv'ƾN~k=!@D`{s;5ZI@wv2}( H Dg}gqn\zܪ`QK[+TpHâ 0CQV8o-K<xdC +nuxqlQ2>Q@W0.S}( H ;Dҽ! xnbȌNwZq_q:u澂8}( H X' lj+tjd~a+(P_9|ɷ+LHʉ_߃, !㾂t$ V}pܹY>Pifc1Lñ~~jBdafSVtX' lj+l,B[SInT-C }= HLIm<4_ȑ;"KHSg8:`Us_acp`_A֨,Rz@&PXWD{qI|ptwab,8}( H ]}^WFhS!vzަOڌ |ٕa )NfDMʷ O#JWpb?, {.L/ᾂt$ V}qց Q6X5Y+8NGN@`WxB|"PgzL0=&+0Ka B̜ES<,sVJJ&K(ajA2qR9kB8:`Us_aW8իW_y啸_`1IT=;vȒBgJx(7,kMz9:x i Q6X5v LwEr*jBТ4b˟ AْZ/}t&oT' &Dkw7j''Wpb?+W~͛7)I`^S7oC_=] Dd95 i< jh#b.=NO8:`Us_aWp4/خq ߲Сno܉J:BvVY2ʩcRȸL2X>4͖ mHTH5Y]W N+8NGN@`Wp UQ+8NGN@`Wpg8:`Us_quྂt$ V}>KƒFfHG9s?bפaLII#I9qr^`q_q:unqܹD_5}أg'KH& u Gr%e-Sz29I'$w+i(XwcVA /Xsd1ZL"22ߌ$YꪮA2d?2" STM;̂HYB@H è I9 XK[+V޴FOc1K (v^P=&o01=;CکkN+o9r*f|ͬ./jB:E@hF?I,hGJRS!&iޤ.[r/6Ix*;mflgmaLDZ. =9R۩:UGdv2/ jB:E@hFp5Xeʕk p=x+Ud*ϞՉ^GP-K>]8am04b<c2ܬUyLeePgKZNAQ+!K?} ZNAQ+B!" 4 V jB:E@hFp|%|獆f^vK'`$f>8nǻ9$!SB@H èo}jgfWjyb`h~Gkyg{t G*,g6#!" 4 Vzc‚b~MAY<_*zE>|rꋽj[ݣB[PR0@5CںmYlO¡V SP}a WiO>}:9A A KT\>H+^*G=]ݳ(immyFkuac卆F/jB:E@hFp{nN%vv!±TKXȀo feF)@>݃nyBX9NJ,J"P+)(>@0jrrp1ତj]=x)6"!" 4 V jB:E@hF@9 t 0Z8'|-/&GG g<s摀C@H è^777#__| '~X X_?# NB@H èV6/@zM"sR*܃h&'ӧ#5.8:B+\Xʏb qAa*ĜVg ŴuCnn.,&%MDɟzTX<ZXN˽POΓ t 0ZR4Z-Bm)*)CM<^P ` qA"Ʌ,\ ů z $Okziȅ9NiV SP}a $]=C  6^V!" 4 V jB:E@hF@9 t 0Z˗ܚ/|"?z]8 <G4']??Q{|&8'@@H èo߾]~Ol<JXª\r|CT=nꡧG(Aa>f-)^V̿d4նs;=m +~=7 !m `݄j7aR3!`*zOEeL tAAaô§O>imKNgU b$6\7DUo "&fۿ}z|/rYAaݻws**_pZ;$o{d$ޞtB }.X@o{0gL哇eV SP}a %",Bf]bxRjB:E@hF@9 t 0ZrAa.U|GߟXv_NpȂ%9~C{"K=>qK"u1!" 4 V s|~JHOx-8Ix[)E>N!}A9yq.<1)tjB:E@hF@8~%u sfvp[Ǝɲ7ѻȦd3Ohs.VKNcI'a甁<6ImP9rBAacr]Ϧj;= pa%0~t6'he&THaS sas? ^SCjB:E@hF@8~d=ƶ0RId/hB]'Ƨ:.׼A"=cr΀s)#x 4 p$@W_ts<ExAa,Zb-' 'F\n3A@H è!ZNAQ+B!" 4 VxbVnw nfȵԽ$|D]WCQ@>N`>,8G XNHAasϱB+-kr>~ܔaB9ԁ؛v/)U &'- t 0Z9҂w۴ ^hS# 6g]<X۟葪ik)V ɭ$@:"N.$s(4~я@͗<FBjB:E@hFĬxiuTz%̃U b6^Cr0nNM2l[BH6>{2`B!!" 4 VxbHE42oWG{ 7vwLh04ZA&$KL׎kBT=&L +!<!F7*!" 4 V ψTOlq?%djB:E@hF@9 t 0ZrAa2奼N}V`wMKeoC}1f6F_cNcP+)(>@0jy沟X ~ŜX[17&D( zM !" 4 {ZAT«W^~Ԥ\r@*?$`NL)N %*nxkul]x mӳ!tPx]YacN<u o{`+G<5iP+)(>@ð\%|xкUж*[ALe-HV}7o(5/f _.yę.tEakcTԆeJ7SB+ҒV SP}a/|] VN[֪%G|k|ފkN"<IdZ&􅎱cdn} VҎӛ"uQ ۋ=օPŔ8PMO( )ɡV SP}a $T,.>Du 9V SP}a s@@H è!ZNAQ+piZ/7ғSgI:-(C~2#<1s1az!0 t 0Z1|1hĴgu<dLc]DD( V SP}a DZ R{aE/^\[XE"`cfg9]OOq8Ղ16sSki_2 t 0Z< RHK)IuW*^x{5:d$8T,'~)m4j&iXٶ$9z j=e\ 1(n-*fiEڗ !" 4 V8^H?iuN3U@Z+QVJW*WM01oEE $ty<BAbJΐ<dS% :AaY&bA-u)TQ(,B@H è!ZNAQ+B!" 4 Vx?;?z}&B^osG{O_bk8\|1SPIijB:E@hFp^ .> v u 'X+HiؿuEbEo=BpN9|QbaUP+)(>@0j']/X#`/]YYMm~P.gCw+EgHrBR/Ǟ#ScIO\i _$9: %XIP+)(>@0j'cKHoȮvpJя{QTRvkgÊ<~Co{VD&"9T#panZjOA<2Ѷ_gMZZNAQ+Fn@g.+W<$h`}m0 7$ T9dM.&Q:Jlu#4v- @NϳPŔ!yYЄe]ZYpѰjB:E@hFpMz@shqaqAD=H( t 0,iV <jB:E@hZ~ZHAas˗/5GpoށsxgZoWTǻS`2O>'xuC@H Dl:۷~oۼ`UZa2IܥbG+Q!8'cy1@ ԿbAasA5XRêWz]+9TKI+`Xmk*;!][ao]b='U+%PlV%r0 a\iX@@H è >}wߙ' /yͩ86,c pKh3`14@ GK4&V}9P+)(>@0j»wTʮ]k~mVhu\02+޿uZAX1a1Xу\(UL1SyJEAayXE7]B5@@H è!ZNA%!ZNAQ+\ f3d~;0Z?~?O6o6a 2Gz)"G@@H èPmKlip"Pͪԣ) r[WVaoNrrAaՐ"htm-5sMBcBt_3KJ`h5w#\ѫILdLjB:E@hFp5ž+xvu 6X0̌WFe<y#ឹ.$P+)(>@0 #@藒Y]yk<&?a)ȩY\c9TɗYV SP}a )5A9V SP}a s@@H è!ZNAQ+<|[3 aAۯw\ zpq3Y}s $|,<`GZNA%` ۹QV5&D]_Sai[N>$[<?HvhrhKU$DZNA,ÿY0joR sk5zo!j6j)iR#cͯ>섄V}07.^drVi@]Xу'S%nV+XN$|r\h&V SP}a  >}2%g.ru]~s]BkK31tgbi~Xn7d~Ú\3CLAasݻws*BeWbRęKo ym:`.reBW83" imciƄioSb(8CׄE "P+)(>@0j)B5@@H è!ZNAQ+B!" 4 S? Fݮi=.@{`> Ohw6O~g cV SP}a yc gR(Z0d997Ly]z!Y64V SP}aI+}0j!*իW_^ ^ٯ ՙ Ik[ԫTʹ5%U0h 9MTymh[?L jB:E@hFdJ&1zْ{Z7NK ,:Tʽ2<Ih]o#s#1V>&I03FZͬL jB:E@hFMt- tݬ5ON+^rn<l@)KچOj@=dÕFUˋJi ZNAQ+<w,7.: A@H è!ZNAQ+B!" 4 V2?acx@_C&'ܼ?ٍ܄5t> H'>iV<r'!" 4 VvXm2PN?fy"P#~ۦ{xVy۪>yP+)(>@0?FfzHlcWI@h,KXKe/1 / k}s-\Ye3fzB;I'* 0 BAXQ'秚UB@H èWy;W;+TRJeuQZP6:\#]ݥu_O1/4<m&nw{Xz? uOJAaX Z* 8m׊[ )^-:v+2&طHV !$ϴV Y .kC|9Ok2,ZNAVoZkv'A|BAV SP}a s@@H è!ZNAQ+\s AݱR_[$Ng)~~B?9H1|#Hcɸm3cW!" 4 Vx^~RJI? qP+H}gfE99A"=<C<ڞ9U^(Aas?i=)Kv-kVW+J_We5"t,]rF+)2D_m]Rݝ si@m@6e3ʓzо~76jB:E@hF?I,hG|]kR#~7pK hyJvg03<9۾>(ʄ u&̪&y\1 t 0Zj*]p'O(mk v{\v֞ԉ9նv1UqJ<ε ̅,@چ y;(q {qva.8ZqP+)(>@ð` /PO(G= /F( t 0ZrAa!P+)(>@0j",>yg8"I-l1oo3Ϲ>Ꮕ3w6O~t%C@H T+ZxЋ4 3=T-V#B:^@@H èǼVo5e+Z( oPձk bi% N_0g8(mu%ՙÙI;5ZNA,>VbLEIRmh+\M XN. mXq$9]w37s3k$S^y3yɜjB:E@hF@*UT۴M:\bdNhTzsd3-{HBVw- Ca'6v:G̃VjIDAT^Zw!y3N9.8ZqZAa9*Kje)?9@@H ÒVxZHAa!P+)(>@0j?aFކw7Xxu#x4mǻT䡤 r$zޚ3vqG'vnVF'WKtyn1w9 V SP}a hPf<: 3J&*e*z0|mWtl`m ڇ !" 4 V \5դ\VS;_źߜV؜AȪBIp<p-ɾr,eN& KF;I0 $#bgF]WČv2gZNAQ+5 CNFEIe8q6n٤8H1 ZirM^9̬Zgm9 t 0ZMUJedio,NmKmKywYh_%2=6ðB+c1Ii&zBNhNK{mE!y3Ϊ93.8Zq&Aaj?{Z\ k- .' !" 4 V jB:E@hF@9 t 0,i F!_|ɭE;bW%<*z~lGHI1x-d=ww !" 4 Vx.}ooZ!w|nY UEGgh;N'{P+)(>@0jhk)>oR1Bs|ru˃=9 {8*!]1$)\6IQ =h!ͯ7L' ti'sP+)(>@06BVw}guTz%̃.f{NxX !l9IH7&bm`¶'e1Ϡ%ȖB;ZNAQ+<޽{7TDTu4 78'MI<! R&`U<}]#W !" 4 V /Ta!ʈkZNAQ+B!" 4 V jB:E@hFau7axۺҝ7GrCH3sۍgϏmj]&Yγk<u9!yJAaj?^Vy}ި+ x-uۯ8C}gr<`zɉjCrEPݗڃeV SP}a/\+Jxׯ_j3O*H~kN[uHW|s¤ nWuBY{-C}DÜjc#bQhҾ  t 0jW $֯+Z2@EP1N|ND$)x[ܛz+a :s}#uCr#x.RP+)(>@ðp=e]A/Ř[Æ!q#bnmJjw9^G1lV('V@_3F.!" 4 V v c(ZNAQ+B!" 4 V jB:E@hFp_|ɭKkˤ. OV`yc$[&쳍sS><QΡ}1u%]C@H è۷s߆6r{V+hķfBF܉GXyvy!^zP+)(>@ð~Z haN1چǦg Ŵ9Y+i#9sR}do7 mJBəHH{g@r/8ϖ<NF!dhV SP}a aZӧOs߉N-SFW |,V0*4}gmSIU'TiA}e9bsFۅt!" 4 Yݻ9`zV=)RVs.K+Wz_rŠBuͭ1%3f@L/%0PAלq<xȓBt !" 4 Vxh)-g%KjB:E@hZ4!P+)(>@0jB9V SP}a q ߰[{ ,5Wx&P+)(>@0j8~)+$X Z;/qo~F+Thx5yg!" 4 V8W@ClPu >r#x.CAaq|by)کBKTc4`f~B7B'x.CAaX ? Fp_\kϞ!ߕZ;g~%=g *[Aa³+q>`W6^ _@@H è!ZNAQ+B!" 4 {!Zٰ?n]ҝwwvP<*oػimrI3sN*|??.[ͪW쇯 @@H îI+ܼ>o,I5i}<(ۯ8ѩN(欞@l<;E=v 湿-'D4h<1' t 0LŸ$س ^ze`W< iRX+9aIs~쥻gJ#qヤ<g:C<&>! p]9i3$3<<V SP}a]+J&~]= -uRDb/L&)SM:C !ċj[NWvAcζ/z\My|@ŃQ5CZNA,`n] V<ʺ^O'TAmuj1glE*:f:T:7̣7SVW&ס\^iOf͵uQ ۻ&7@|z#cZOHG O!" 4 KZ>@Mcc(:ZNAQ+B!" 4 V jB:E@hµ—/_rkncC9R]'~91NȇcS}̟Ȗ<'oֽC@H ^VxG Z/ 0Vt{Ev T&?9~]nAa5C*8_g'96EUVЎb)KUVhmVq 9-lr&6JLyrPEVj,ߴcp9\ t 0ZAS=km)Wң^-@ R/C-pJS3IJTF(FX!`?'݃i&!" 4 {Zݻws*H+{S 3(]WZ} + RL z@=P; )rI+LmXcy"ǎ8n&˒(ɈNjB:E@hµB'bYɵ!h#r}P+)(>@0jB9V SP}aoQ+B !" 4 VX&/7z~J~X؋gOh- pcyHi'srֳZNAQ+777z9|n}Ku%nsK .&ڎ< oxjB:EJ{Z?i^z+,Sj0mнޅ$\OAɴIG )g5gM2^YΣGkɐV SXc/V+J&qP+7|Η_Xrg2 1 yqWll<|o.]lMrDv2+锠 _W8TsqZ"8ǗoaLg%H yL ^sA޴ 1 ]A@HD?` -e1] jB:%5F@9 tJkZr锠X ZfMeq_S#Ү1lk3O,o/$\3n7oQr>n`cHd锠YY  K]e[ɋTar<-)XAѶr9mc t tJkZᬄz63ѐ:Tʞab׮nc/yi@]c5\=9 ̏UyBz 3Z 4";0U=p3+L tJkLu0jS IyY^H@@# D'`'+md 6͒H1Ո@HFC^!f V SXc g%z[ïgu1)uNhwDX]0I!fҺ6c@جz^!jAN&M%Fɍԯ20F79B jB:%5F@VKaT9$@@Hƨ!ZN :`=#֯V SXcK+B6{,Wls~U0l~ps7?)CH_]c1[HIf?c1<rԾ!tKZ +G|EZ0G_351˖2TU=pWkGQ˽4 P+)Agʵ{Xٓʕ_d9WectsHKmhfi4piYpP6K{g=pt<H锠s_W@Qc zF:쇿t/&0@x؈֞A;"o?!jB:%5aLU,1~X]kz0-9X۾7풞01fjsImq931覜Oރ SP+)A1~[@U1}$B tJkZv#$@@HT+S+B tJkZr锠!P+)A1jB9V SXcI+` GB@Hƨ!ZN :`Q+B!tV jB:%5F@9 tJklVh4zV SXc+!!P+)A1jB?NNIENDB`
PNG  IHDRnwVsRGBgAMA a pHYsodIDATx^_%u 泞'a)YJbG-K!ʘC\ {CִPYFQ{X[<kO Ji [@€b{yyw߼yQY'ND/oĉ_uw;;ĥyOa?r9BvSߺc} qQ#pblEn/]?VP56~)'Kx6[$^g߸x l.[wP.E*x! t!ȅ׿\7N.1VW!^kDYވ0z,%O5o\Y_| -y> #nwq ,jFγ?z!|5vx 0?{Y BI U$b<Xn -:w!fà'^/= e \;Յh۬o{BX#*Е <B Y+* O~ [o{B|,w'.D quFrXd[RaN 8ȃ\Raxo<,ʈ~8F^ON%000&,Jrڑc)0}v`|XdA)ΰ3qv/Vjx#q{[Ìb߁8gZ!߂]kg߿o/, }h 'D<=~eG3˅0۩ x'I7Gc-Po.w6b/c$blu ^ o5"^Bx~2Dhy)e@ "AQ#Äm~+BM5PՈY//6 /oo SOb# 9^ S]?`g.籅QA{ X q _]ކV/Oй Əߖ[)*-zꯊm^O a>qg{9yƬG$yT ۽Sf/&G [q:a❿7Ӆ ۽au"J`;<ʰAͅ[Lܟ=G8Dq&y!5Bl^Y:gINZ'R& G~؁ !w.-;rq8y!~6w^-r!`{)J4(_vY^ʸQ{ d4vB^yaV0P"d<M|]d2m^^B^UA`J яFqPzEb5JvJGNٱ OQF "|$ dFDvBpSD)į* 5B;)rBImٱ q5FP XuñA`G8B4FDvBܼy[nL{`=a]t+tb\FP/PPSJxBǡ0Vԋrٙ ytGpȌxtBi88B:prƱف QlY@@EL}r"^#";s!t:.pDPlO/vjŸ}B,4@ ؏׆$P͓F+v/ϏXtV)U,Xnp<杼`b}ϳb)vv*Hg\u ,BvPY2"D|؉lB _i>j@ܧH&-lB;]B_#IW7’3;P`+5b\6 È#|([Z/&dEd-kDNzg'/:h]QDk_e2)bs{:ݽf:i|/)$"gPmy/D{Rn X#Xq`ckmx!^hDXAISmh5ijAʄm^ng,s]؂n~ ѩ5oif :VB$3 ѭu%^y/J.ӃQx<*"P]FMpc ҹ /Vv/D9\gdɿ7aψj"s.6/D,Յҧg"~W_٘W_}|j%dw<[;/?faɗWYA$r@_|+_O<c?#ߊB޶r]gae Ӏk~Y݋7AleyٳϞ,`vUH>l]廎 #:d,uj}|٫KzeyD5_ _Wᩧ–P|*Gv񹶝^ 4`?uaO3*,@^rXkVU#.  }; BU7?. [d_7koʗ}ݫ eZYǝ[@V,<, H8NWo.9h R_}{ypZv.jP/TeE\&DL .ñ՘@ÓRߊ@b99l$O}j2 ŒW]o"#S8? [xh F| "QϯN?._kO#R? ,ph˳cVITyx>؜8^8a?|YVfD*r+< aÔ'm 3 <goqgt.O%nƒ>v[#^lօ U({ BM_K䳳KWa}t*Dg1za"FuAUڧ"-|~0^^: 5fU 5'Kj5u΋uA_#A|[$l%F. Nx #LݫU%* #kw\^^~)0n :>?t낰KWR@ 5 yR7ʒ*P\o^ R—w~ PY$>,3ۂa7.rБ7pM $\̅W \FkTyX=LD #uAإ71xti# J'3x]v*5<CE97rK Ž]ׯcnQXzNuj^ 2,*aǮ]օz4JmIs.}FsOj. َa'.ͳ``&t _ulOx]v.Aj5>+ǁ5낰KW<.?#'2L_8i2#$Ix]{x 8 7Z?ȹ ,^_Du6,DPSEaeAI/uAإ@sMY&!v*@W^aǮ U%##낰WAޤwX= &O. ƄۅY٥<~vz@#C N UiNGL~H $.낰cW9% M VF N^>on Ո b U(eJq] ؅; a%O! U};/._@UpA[;o{ ng낰3WwV?"^ݸ -Sz]X . >kHa#`o5Z.ݽ \C ``a uAU`h ~=Dy8/ݽ d7 ;嗆s}:'!: Ryz]~o<] |f?/ )PH?V U~~rѷ?7r.?o|lσ|lΝĝ䓌YgO|'u$O6˟;w'^F;w$3(!#/:6ҵ|+O =S&-@ gX@KwOԆ.^.x#tK"A]?ˠxH'_'=FϾ!#ξ!_'꒏ۃ ?ZdRG@ |g[ ubm׿.ZoAm@%РLԆچܐH^<{ً7@>zvqRnܸx zZ*[p6ďV^yi._!.0| / 3k ͭA8H9TKXl\l3m`%XZЇ fUv,֌3j=O/[O *F?w;׷ v&aSBax 9DLŸ66<7ԉ[d$cW:zI|mmۆ: ղ|gWgC}/x1Ьaa$m3׆" EFmE- v'+]L m(_ke'nQ [6YYVde9?G(D}( 3:"9q'2ʲe>bmֆS nc;ֆUΝ;`$r `.ߎTRBg!wYM)Oun`ddAlF`X՛M#0Imxaavks^$:RtqgBJȊk! }dXX D۷؆D@ r(H̃DFamRVdf)$j|kQZo *Ʀ 8}WO[ m,cՏqڻ6 6+J[qZf KBBGfC7ɵz=:Nݡۆ: kbA{%=0s尼5@맼8(#YcH4G$X|"E@bZmۆ:Ǥ} q*D!Vk/~c}$ ?rPkÊO8(`>AqG nQ\ rD҆b*ϡO4QdMkCq0 ZNj[  A9q"=:~@sNk^` #]RaG-<t@EۄFp`_k {ֆbpj̋<XYNV"rCk\'prOq\f,O{.^'j8Ro6?.Նy Vc@~y j@Br F&6CLE9R {[>~C 3|vɾA9Y"%-5]ۆ:^΋ f ]qI Mb<ڼߩՆG6Uֆj~p7#xr!!ᎃ%6N~Y^Òۍ_= JkC;'N{[>4nAFDʡ -0*/eō|r(0{ rti(KEHʤ%<=! TrIֆ6,*Jm Lm@m]VGE!)O\`hxXy@`0 e}$A?,( B;ȉ/?㵡+WW^sNA7[M0NM>Ƥмd"P b3^1^V},Yd"tC@m#Pcd3s68c6_䬖 B9w9IE *_@|ty~*ɏV{zmX/w B=3!aKպ!x=$Jfjzmpxm/b N _BR#2!A*6$^1^K2 #f <V/sf=c 0` U{m:Sxm("΃},PJ+6t.adkpB׸:,S=^/$: +kC'P?n㶼 dmݨ$6C';k? nym=g?6l<h@2ljgqp&nZc(B ^HK&6]/8M߀-$  `F_>ݶvsiUDy 0L +`}&ڰt48|&)TS_qu*GmЌ#yxm&t 낿48̀I0 V9\80l|haa6l\k2˙,A"H;\HgֆM!AVGCͱH$uQ'"ֆimXp<,7RPfzm 6ea4YWi=*#k!K$5vHu >&xmX;\}6^6Dh#8=EtضqBg;J_cOköOxmX/'tğ0 #܊(<Ԩn.}@ {[6]:ZZ63NbGwy+1ɍS9gr-$%SڰvX{[:uTȍÑ|N,}n w]Do167rbhq,FIkÜ_N0w6ֆMU[6}x8Z(?ސ2pkXrK>Iim-~ZGԆwr_ ` ' x#`uaT08a߼e|k/S= On6gaL؆i q۰^jnkmx|AE$p/Ph[>);U&ӟx1d#d%3>1۰CxmX]p3JAQ@ #j/KjZ>D$̌Jo.6׆@qpDkg M=Hr14HJ= 6m0/]XCz6|l!|??緰Ѳkf?en |\qhCvoC-eۃh@KᡵԆ]gokGg ؾM"d|fȯ?YJA]!7gJr.GB"{Z:sm6<8km+6׆:^~7~XKe۟1j*?74dsO|'^7ȲΝ}"ZAYZcP w;sw@e ࿗s~/?2~r|?;c=ƤŸw *D调@U@8xI@U@r k@qZ D^vV|p[?EU.0i1*4`A0q3ZA5=#O#КEP?e*xג?~gW_D&<{oxsNлxc,]g/RmYߍg/޾鼳k"oyG t_2 ϞJ UpK$-o\<{, ot*hU= S#Ky{;|B .یP߸JCP˔OYp\$ajdUxB[%sj}KS g'5YgWOMR귯B^<{b}l/bwFP/X]v);WzOdDQJ-vݨ FMBcUh?jW*oyž^_ ="Јҍc[0-UA_ߎ.~t&fACM @Sz}JUx l 7odA~IJ0܃S ql]hUzߙ*џ۸|U=^Y Ņ%:|E\QUaLV"@辂e*<s13X/X*qUx{{ϖ~ԃWg◞A  _e$̲CLT>aKU`KݳHTwV=QU{WIcaxU(sUF+㪀:.K̅rZK!w[o˟} ?(w^ߤ>Uc`W~ Za|̚' 1׆߼o %bɪyq\Gc\la1n ѮE i*Ī~?N/QgtYԉGAWލW81 ťN y,GWW_MʳÄ\y{)_}ʈI,U`O0wUxꩧ.?E!4'~Q +GH|6]ew>V83V|PB93" 1z@s #Kc]D$CqKj5&`@  &" Ea`h$ςcU,2Uaa}N {XKsta{!YwPЊPH چHXhm(V޵@]Bl*'W Z9؞ &{Apɪf\Cz ]}B<Ah]G*$<8nYeU2+ x>"TgF,3 t&TcU,_`WbaZWO1 e T>x |y)y,GA_/:BX*7ɵ7%$vy<=,8BЫ@UVu5(Pb*|ӈ0:]BWxU8 V*9( ЃTS i zP d_"RP*㽟@p%UŖOCB8X- 7"H:Z_4q&~B ,3UTR82(N@mxU8 SR?RlaZ2Sh] ξT,{I;~*h;Ë:Lt`N{* {G`*b':ˤUXKUuҪOM"W@Uw>ǫ‰쥯O"@`qZAn&klU}U.Dۅ(3TS w NīŠ_/p(^ *7&pȱy;IA?.VEpUEU fay5@w8_1e( QP'* lp({UX ^VӟBЫūB3q @vE?fIq@&愛I-y5V 9zùЀ]_Ge=Ϗ?*rV Ƒ0>+?|FJ&g>VO B ,Y `0w&MgANH$ 80<wT"ДUXߙOKrHU0oFfLX:[īD*.VΟ?Hf"YXs| " c;ѭ<.(8<G scW(cDžTAA9RWB%<=dFlUx 7Aˀg/`07(YG n CvPG#H<ytOApdd[gU4WuC#]U>OjGDG9*8 NīL3`aTc|␅ uB7˪ @8cU?ʤ聓 /-CH snU] AX*8 QH3g0`_Ķљ]07:Qjm]:UEonLѤUQeUzUxUX]_A<o?M)I53 <%v}PWA:<$S* [>f:q*|B,^H9(?2D.emt\&1`B\1 r#8 ̂Pa. C(抢˪"@p) !zFaV7F@<( W2(d^V&ΰxZ ^Nf+Ua.n Nd? \kU;l>9"§ѯ& C")G  R~D&K@ QkH(a^EC> ="СOp{ ^$jt@W*P.iTlpH*¼-U?9WeU?FpU||aW!G(zぼC' ὉG"ǧa^V."'VoϚ:AN~u"jO +cUaD*,W|5؉Չa5 dac}j·C 'ևWE.hctErL &lBE.RGD ɫŠYU ^W5"ɂ&q! E@(wM ;7*,Wu_E8~_ : 8J@(e-K s^W !,[K@ իQe9W *I>$!?m$⠂umUv#0D`xUp"^W+` k;|H"sբ>*X`[(XPMJ&! ׁ,<$hT"HUxUp"^K#z+!`c۞_u \ /:,9ͫI|d/U.nA5Wq! pkU`@%UaebwD*lz@YP^S?jWD2xUZ*]KURR8!|  ҅kvD*l f Qu&ǘ!шRBm| xU:!ǏDQ]d1`;N* s)ߛī}` ^ey >4џ$2C'Uak\~v?[}w$Rgvx^t*˚ Nī2ՠޘ.:>e`qJ/'HJK ^ 9??$I]6'BIm9O?:D*WXEVdCβj+밚JccU͛z>[&`?*i zWXWXU]*8 3޳Uը@8*=.@$(rYū^_DjI5* + _X!0$#^eVAY߽&D*,._|@]N]]&"PrQCj83[H>6®$G!3< Kaxq]E]9@!Ԁ(TjY&ْYF*BoD*n8nGD:\@IQH*:J'E#*<x0ū*6ZgN SD?@4H+"T ˯;-g3xUAX*w&Ǫɯ꺍d׾Cb$tZ{$1TB<^6~ԡ]T}NIUISeW -W'UzUxU"dF mHuY# D*|n*`W:NrWr#lUa)[v Nd»>( +W%Y/xI*ll_v[Q|\a>[v xB ApUA+мs2Sce $>zR e Ua$ߙ~T @-~x'H`ī²l*]@D*lW?U.@aq#Ig|Bqk>%<Ǫ|­X>J {\a>n`*8 ŭA"6{U8{F;W'UaIt}!j'؅ G&q( kdL$,L>E[S@U Rm*nocQ 6D*@p[U\l"a%Z{݅ }O2^ ?A[cU x?-8-gTSEs>Su tuH$5^_Z@o[gU8@}W_İ<J88,ݬxf#;BK<`P N7.$;*8ndWN_?joǏ'ʮ}"gvHD,8^Vv瓛d?§ t_Ua U?-fe_^\cUӟBpV+?BXpB9B*r>$zU8.TUeUx!@dU0gpVg @cW2wUUP&[*M=RTO~#2oݕ?(Uae* Nīe7]H8ȍG H%29 ,eG@7U$+ iiV PEl!G UAG&)_*deUO"@"ƺW'Uae1}u'2K ~]z._[[_A+Pn*|B,^^V~٫īa8Y+ Q|3Щ'TOM".#еY8Ǫ5UdƯ>֞k᧕R*9?Fe U!䒽Ԫ@(S} o#zaD*|sT f:*;I@rb?{E9B ϣl"?:?}xU*Q xVaFHdP!T eUD`bl˪p`8 O y5`-2AP CT .¨Jأaɪ0mV,T qT@.CD*4bE$JZ_x]-XvnSUgU 0fşf٥,! 6#-$>=<7p)O0 4 yBngt)%̵*<1Q$2$UAo~W Rqn ~~$EXcYL*2#F2 NīB҆BϪQg o:7zAOw>3L}rpϟ_?W lN4'xUh~o g_qU87v9ބh& V>QeUxhD*!^,^W'Uᗎ!{c#'F}S6(k0}q!vṃΝxΝxl9vB:,)خp,N(z%Ν{[?勑؍ pb8d/E"Tv<;73&4".HH?1 pL!]`PD)?p/d*\4?%_p?@[b{[3l? D.8s1nk_uӧ'aΆ98'\[p̼K ^?Miv>؅wah ҅/HkG;WakA҅ /]@!䯽ڥK(G*yrv/˿c-qz~b #.9DԹEF# L&Q ]'6BJRCL eyƜ"S^V`Yn̂ iw9.x7n_}6~tjcNٳP7qvٳ!)֤7.ܾډ݇vڅ# n>B-:gupc3XCN 8N„]׿cnbg%3;SAr﨣Șv.0,`r.c=cjT]pyir]͖Tm ql.$;8.tp|ًv W c͋7)<= cYz 9_bP[0C]8wܙ3g=x1,rI-DjM%jưILŖ_O&ghZ*ٝٙ>X[šP+P3څ@ dS z="0.8}b'4i~*0W~>XYxlrt & vܷO^b ~͛7 -|sqx2"ɷGӌEBy!CFbl. ] ,c^ko[~t1a]gv.uۅ_фUft!BX]ءp!h t@ .b>P bvϿ,m]3|gC^nPOs^uWmمI%څy;gD1 MA0_@3~W)_Esk deGodW!$h 2vxN튭nenw|T2#Xr3 3b[Y/$Duvaͣ0Am lm]M“|_~xv7/8'2eqHah$TIkM埉Z?e$?LȂp,';Wbv+c&]H;9wEK(-M}3CƏȇ%2l.ׯX uM1?(em bHE R@̅u6|I8Jq$N}cb|aFY9mv{u1zڅqaYPʫe!Ad8v # v|E!Iaa&x\#Rg^Z6fa5_dmO|L@ATKg:ڿ~+ZO}aMvaaЄ`dКڼn&::-# (\`*av[xj.`Ҹr*Ą]X4[w5>sI ^ZB W1Eh6Z \_X W6 ^D]`h]g rX1x+g2 6V+aMS3 L]l`GhUOEh⯠>ο:%w,|R[s0 o X.p!p]aniKbT"<Y1/Q5 ]: !m8&mG8(߈v:y ä-_M3i }#v3q5@cT c;Jֳ 2cń=zEgB 5l~UN-5*%loLb$tH-$U4au # Œt.\tɸ33,̢I﹇:?~73ȷ_oI=c[#\>w_:t.vw66١q;{sՏ'$e?G]29:l寉%uo 7ل0QuV۠8햡,_-[?V,Ćw֭&{/M[fv!  hQAߕ!}["A!<8 M|0m[$vs!j ՔJ _=EliqФ[1Ə,BWՠE6;\L :Av.^;r(z nz`FzJBh `覿0bFΉB+UI5BDTlW;ICk 9O?Cq& x'>*$K + 0U n5a ; ]٭f~ nY] Na1 B, 2^Ύ&FO(uIBQ{$<WSip:B"h\+8. j]UBE a+#(2j@# ;+.|a?#hb'|pw5PM{sA9"r J8.$ ;tva2BX ATP 0ߧvUEشCԁfAVZ W'R4mv}d]h\ d[(ʈpB_"Ɯ?\]}#ZЦ>;4.q/]'م?bpۅK0}`AC ' T@o~bt9}lIY#I|lv޼yv~!>arnB 6TO"MX6|Ƣ*#;ZSg]xchS fNq+6ojR4<3Br$kw993ypJsnzźB}F=n4Qm" lNGoӦy+sN1>I HP0p"Dj%q+Z?Űj6(8'vW.8Bh   ۿO.o%_LvgAXc^:nzE]xڌߧ\vk8B <fL`}'nzNvavhYvW]pVۅ^YCj5 0+vYFhiv^̡fTއu.VP0l.4 ,f3"NmRgfż! C><ʱm\R 6D]ľC!AyG6υۅ^ba+va39΅fgh W0s"nzEgBQoO ; `)=[3Bh f¶QG@ +6 ً#9^-vWt.2 ۅ^YnzEB^13,z VΩVj_~ẑۅ^f>i5م$^|MZߘ@; I'.-jP5FBh am @wp+Z»>_pNB!#!΂f1>3vWt.h~!M] PxD]] ]@[ĝ=Bh 2s"nzE] ݷ ex+۸Th+\|!/h7I:/{OfC]hN|8x?v<;uͅ䛴LUvW]X q+ZB2s"nz>؅K =U(z w&O,_dQBQhҍ"6Noa.􊽲 Ogٟfa1DG\F ۃLŖ-Z"e  ڰ*BN@i۷XhVC+Ӏv* 6 R#Ɇq+‡>'va$V`_pVg%]vs = tI]\@+$3-ۅ^WvAᵽHgPyqK4vW]X+jV . .>v9 .oc닏:g9APnX>@%yiB#LJNFX9f6ۅ^jaW삾ˀ&W a *`(7 _6D$ڎ D ؖE8=vW.lp"nvW.pqhV:Qȵxa8L=QD%=ZBEP_-,(,Y1mcB,.*Br4VdaGQu]mDswq+v.t Q.8+BOgurt9qq'P$@AQvT)R}R av8@Rמn]` U- l" &C4kIFP0 F`$~0 *#ѵnz>mva_p˾gM]` [hs2| [%kcaIeD9EgD ̲_)"&)ݵ{. dd&&û6H`RU.م͠M}hΎvW]pVۅ^ovW^zlqPオKG_ӯÑu^#ރL+ (ltj$m b~z0,b[;:nMa*Zxm U^S,#scw#nzڅvahtFp+.8+Bs3g~>A"q! ae*g[H}ѥTy;.􊽲 @mjDj@[, C0΁ r,[r5%P/@A4Snz^مyLcS /8킳. ` /'䇲vCB^- vȻOK|~)ҕ. 籽y&w;H͗{<`5+2HKX rle/P~y lCDF8ܴO#2w/\]n_=V /8k킳. $f|Pfի 1R@5POb^FTۅ^vA/e4ߤ@qIlK?kL=t ’ߌkKj/ô·ۅ^vY nzۅ/܀=o"@e.l07A;. ,g#AYWaTЃ]4S0#v Bg٭q 킳. 3/x O.ݻ(>- Khl)DV1?Bp0;v|$kh[ U fv풍PrRb8n=bY~~ۅ^va}$pFhS_Bp vByk+ӐרowrGQ+ԏ;$ ՗7 % Bt*Ig^V.م2 yYZY!pk +)Dq8۪YmAvU+C 0-:A*8(J3)[.vW.,І /8v nz}*t@2hTz H%X<dvWt.WCFUeb6Eę<GkeZe- ZN=.65 W%p7-NǕw vD:r_pS] x0*k`BPB5`%!Buwp+v.?3vvmE1 t /)4>ض}aP`!rU"<FqB _X/}h]h’YBp b]+,xϟF[Yh"<3{ v>HkݲU@[email protected]Ōӧ3KԁpFC5a#QixTa{FW28JB؝6vW. []YY nzE]/8'vWم}OvEu*2)Ofyhlg:q,F].s =@#DM OrA6~~ƥ5|bI.= ĝvW]pVۅ^j>cgeG( p6Qꒄ"68p ZB]'?(ӵeNBpvh}LB_!޸c55R8J~o +*re@VjkBh ,G̅6ep&nvWڅGdv`B(mQ텅 vW؅w}Q ݟ"(ԙ녅 vW], M*nzg%]mv2.^IjTHGiTV+8vWڅ0]rn, ImkVؤUM54 (ىq+gf'ZjQ 4Cqgp+.8+Bp!89 әgAgF+uIJ{Au6l .a]>(\}(24n VmQ:,mw+E[2nl .ާ>BP /8vY nzŞۅ2mܟ>$2!xA'SS"7T S!lۅ^WvaK MOHH0 3t&)$&m ʥ!Xh\qBjm9H46ۅ^j ǎ;va_pVg%]mvNJZH,H]ÏbeĤvFID ۅ^b'vÖ͆U "TNʡ2ն=YPgP.PTv\b J`+]څ%Q jefBh  nq+.,g7c۱3)۳$Ө-'NtɖW'(OW߰Xlۅ^vaw"eŖ-XaSy $ɮy?YVew+ :2(1lMBpnao jN0]pNBh b]Hc^]i] hO,˾0h!v3/۱h_KZE ,ۅ^b~>bc]Xeq b´逜p)vҞ&,0PI-0dڒ:'Ӹ]mv}İP[A[#ؖfHwT/Tva5MɏMJ ?!˦>]uȶތ^-nzEgBѦ 5qgq+.8+BQLChzPTOsyI#@~y:Kq.VIn 6 *ҒG ã[4dW`"k$8+S D,Bq+Z;IG$i, Ni I_pNBQ/۸P矷k_&Puq:;j_ jlFhj> u]pVۅ^)2Of%w9wIdwHLX IvWم~aMvHm!p|6uٝyH}A+Y?NߛU"vW؅ ~1 5@[wv .<v9 va0HQԇ Nˆx(;=GG#L{' v.څc{Mma, PW[|8[iCF[d&"t)YK༩al |قۅ^Y,0Q26mv||9 b}7"  c?:e]4ava}j@//h#ĮV-utaMH0z'TGٿ "6z|<j$} Ϊp+[`N}a'^2k0I5T+l%y9de7Pj9:,8+[`מXJ2Fq]-m}afYloV#0ܮYMx!5;#6I/9\):*#I#<BʁΥ"QeMR P4ۅ^v.ڰg$u؅w}WQ.ذ&pAnw>3'wy!gFo:7?G\䪖dOR%Io<#ȓlQJTDpW9nzFb lxCeX]`DۓHKaU;gBD7$MJ^FsϟɨDC0UۅdBۅ^G|9 "62]pNBHl nq+[`[C Ή]-3;nzEb lۅ_:7υBAvl} 4 3GnXu9¿C=Q8xA#ga+;/?,ܹ/߉;MF5 ;wp计O33|;_Ɲh|XBv914 O<wgVPHeD F̕5 , c|N(";8-Z9ﷱM_~CF b+EF\A)(h\] l!dC[K kй?4/" !iÉLDSZ2/7AA+o}+w) QۍǟgvbWF[F7vqiP-@.AwFp:4-8Rem{=U&ًKpgv2(@9 z qgL;(vX,{$ÅCVp(rvm'"u.['FgI0FW7ƚxkq.⎳Q:7 hա;; v~kk/AKE!sȱ$l.IN OzڍZvZ A?pA3C/Éq4xDQCI'F! @F0dgWp+ ?S)4s1 _YK/\cM g<[:8c΢Ǘ F# QuQpo(JxVWo޸|3$Qnm4 86j.dQ\$_͇@w!QppQ(Ki(- h[Oq_YiU| D(vZ7 3FYf଄FAC! F`Ɉ  a! o_Eip0/h ۇQHލaFAY9jyy{/h9} $3;nzE47 ( ܜ|{2ԍf b8Sj:;O,oiE:^Ԍjd;Bb 4,cb(v3RdSwTnTr:,l³"$bXrqFN0 !r3NCm(xk< (l@Gǖ^'!7o,=ZmJb 40CT<cܶ,lGFhihlHBD'J0yՌVH%0p8ǧlRTD|Bә/Jw)1Όl FE5lnJ KDX&O0s*z> Rs(Yj/XбFa[ݲak([KH]D 4nS [ f?b4u= iPebhd|<QPhVWqkZkf4 {@(6[&IҪw(7(Hd7hASD,XS=:>O\wMؖ?#4qǙ9}[Fnzś=E@؀QpzܡǘS5QpeQ<`F8uW^y%'7|w"ĭ-N^<U2ձ`:8O]BI!>S+Z[0CT]kyr< La3+(¤0aB6ZJ ˼IgYڟ\]>glp)ц3O4}(nd_cU3c-ь $ٶcL Z~qѤ–FI4>fy :9%qIF!1 !CT]kYh0P!7ڀ%'(Ajҏ-[Ye2vq\=MeShaPg)0 lqgؖvϳL;;gy:nzgy(uIRLr^Oa')hD^y@ec[c^46LX8%k|‚ōBXQؕy a*|&dЍBh5 ek/l5  nzgy(.gi6 ?޳<Lܙ{~(ni6 W^+\!DYlϿwKb;."Th\D̳8k(<Q 潁O,lbD# G; F`"ҨC;n+ajK:+H)&׫X8keFܹsO=TܩZ #6y Pԍ>CQaQ?K+(P[uVZ(CTX3g4u !;^4c[p\lsPBT>Ole}Fڵk>Sf1 /l{VӖUvOFWS6qQpq+(8#F!.Q!e0.l+˟!;k(|!:Q`l21P M<44BFA5k,_ko~ow!Gwj|;GDY~+_x_~q)9 7 D/+h8n @@ ?(T&CF%C}Os4u ASBHknGKM埕kLr٢Q zEFqǘԜV9<dAKihQc])@I!(pQ`niلQ("z Q(}sn?QaZ 7 EpWǟhƎY.ad∨ GD$U-)aXc")- Q` /.ѤxVG(OZXx7Ylo޼]ٲsFcD [plEx}Jha/X k~8آKN" '@( 6+I_wVv`Q}rH?4ik'Ae"8 \/GѼ%1 A0.܅2I9}dFY-mFycmc3c=1?l(F.vZY(<eꕦIoQS~#ޫ7b]y|EU3/ZIW3h5 g3=@\!4oa%ѕoDsW_SF|g>ɦ}i'*$$y-Gi:'e>d,v&[zv<c6A#akh-i4'NE*Tf& |z\Q.βl\X8$8QBiC9,XbMN+Q-F>UW ,?wFw"[u:ܲqʲ NmK.6HR`gɅ@4.T_h4 #Q\ƍBؖQ{O~Mmq4T7d#9CW-cC!-fԅ؀ֆb@YBM-]MqO{eO$/V?sm0- ìrQU<)lh;ڋHS~<E1ӣ<{‰7\Ex'[u#s:P(8˳QQ/ѬZ.h~A1TjZ<0PQ39LEQ>zm M5 +KDiEk 4d+a&5 mn7تkF!d!mP$q6;1$5ޝXF!l9^MS-gȸ5<bB36!F[ii@-E>D͚Q4mCOV,HB`P7 ԴgHlVh3 }!nbF۝c w",CzvTfTL`[_h8VvY~0<1nVKC@]hiA(ns]Hg*8 RQ*R32[}FYnF/6~;(0(jB9drG`)=nzEB#Gms+ <6Bg#^JNmU*ȂN@nƖOĴYe:Wp;33mC5y_/q}Go~󷟗 N$}ǡ.=)={), B 7v>>E\Jq#q+:|'}SX?F<#_}yFj}|Uc猂A6gd3 ~I\1Y[5 _N*hEV(daN!GhيQnFF´V~C^7 h#eK9v?hز|u`QQpgF!j0;?p}ß`\(M%FC>9 u@ABӖ6f5b=dR7 hU9_|ۏ˝V'2 ֗QpgsF~B#j!Qwě ,i @j hwK$nPMkfA5 hp`SMq(Kj5@B~$qSQh`Duo,:YMH6gvA綋Fea`"5&"%G\yV) =p+Z'jgh`vhilϡJkd v,&#ԕOa$( F~!vFNn)Tiakl6)j &i=97pV.?>-uh#(6`3%oV[} ,gyV)ئ?5CV(8˳"OaSlJa6"eQ߉Ud[E$ l5XI~xzYt>4K~N:+y }?$JYgv}iz(Džr8SA"' @qv4<|3zxlR~E0ԱYh$~\h[b%($Fu'jU:I${G<%6;8&C#8J=YIAL)QX94 qg6|L!eAѤ_7aݸQpgQ3>(k2!V5# Hh7 )V8eij9$lY7 z '>@l$"^ a(hNZ,oLHPܿf(mF}d]zi{]0ZX,]OqvxP׳m(pQExN-~%*9cSV? /(>np pgPmƔkB6)Ȩ)h!b)ĶA݊1gE5b/(('?bڎ37 (7 Jpzi^y طTC8:X>@.i\apQy_t)X@WRm8Y@y{hTY"A_YdA}dT % G "fvɁMTBes&(\~=* 7-B|P(`zu\rDdQopE%(ۖ F]gE4 \I! ;Iaꦅn1h AlH;.zX)6 &W(t ɘQpǍBh3 ?Ug nzgy( y_WC yF}&][p+mΝ;SOŝh2<!7$.ICg̋68TI+&w)p+j`Μ9S3 %t1ڤPU4f]A;s'(5 r,&"8'FW(\v<uT(Vg۹.@םk"HeS\=(UHJ( k0;nzEQ>0;nzE( 7 QF!:(NPBK2F`w[;YY!P`^]P|!#hiY.Sǭ9@,6kC%s"(DL qڌi|C1 O ؍jFMZv׈y_$=D(olt BؖQl8hJ8G6Q&9@mXխ6{FX&Vh%8'87 b[FaWP1;>6nq+(8FWQpǍBQ!/,2]T:q˕T\- >aDP+fG2$Hl{^j q7 n/8H&,<`kxd9;bp(5<.q9`5/8QZ#-|TGe.0c(. hlh]ãɆ<4< kS9<$#fc+y\leVp9(Sʻ@\Q5 7H=.B/UmCwP@cgrÂM7&őX9)r9MugX7 )8DQx ;l?#gco|޷ՍFW+LBp,^YP75r(', Twbe@qXڻM?qQ5 lÜn -2DQ>I$' /GFf%R٤wBL@Q@;i I"Hv FWO3DՍS&I6 -[;[ TPR4 (>$1O*,b^M]ᡃFWt() s!Y-yRki([ Hx2Q6Y(pN$ Ģht(t 1gWq,^FY7 <nzEBDO˓vD?٠ ]=\gq(wl[i3 *̪os"Xa]=)MXTAkdWd^7 (| QuԿV_ӭ@,q9@cP#D~ց=3 nzEQ CT])}?|;]6(]6uʵk$2H{ FWl(l5 c sFWw}3 QqFWQpǍBp,^+Fcx(JՑB΂g UdF%(s=Sq'U[4?Xy<QB܅Z,}Sv>@h8,[sMRP8Q Jޟ24 gΜFhFB5qhZ>m0| Zwer\%ZNq+:h]:ujS W؆Tiab l[r+'tY%)8JBwP>*FQ8Sp+(8FW>Ug nzE??=0zzsdѢZ$_$f XٍBQ.P[Y,] ~<.q`5>E܇QeQQ([[cQ/ o(]4 11OВ)̃mͻ8@2*KQh8GȳIO1GR H>]$fd>,FWQh^A h @?/Bk ?,h#18o¦O0G4@< O?(;gVEς5 3c b>U{}hÍBh5 e37 <nzEBY_h}[1Q8,OwodѦXZ;se ?`{)ǜExLB=t9q+(fOӃ\ #i2y p}$]2Y4P<_'ѓ>$BGvHQ," F qn) &4x?d3vh9lr nij5'"hcLm8VE!¦$lѤـqXgb}ry\*% hRI@rh0 @MFW}!&lln|:4HtiZ<4"p ۱Q"CY"ƅM*3;"j}:&4`D%d^M8lSpFa3h]!(, ʆq+(uBp,^FY7 (|!,;$I yM8LdXB+s:@[')㔘 4I#n'}3 [&$! TnUY BCb:I.j@0F2IQ{ht.s9I%(Pyd#)8+`º&BQbĝFWQXuBh1 1DUǙ^FY7 (jbY_}Z cvX[HKM)eX'+8QFj_Xр[ " WvVi CPVHU2bC.24#V<+; k=Q1 h0aiEVǖYEl|"ڂ*b?16 <"H 4P'5 4U7 ?F}FՍBm$|BbRfQ1~c <u`V$EQSpgy( 7 Qnq+a.Y.yaބvaYޕnVĈ fwAjnuF"lUFWQxb,m MmOwûh Dwmg]b3~UД heJ|PGQebU/d:^F;ВI#.M7dvnџ&2{fBmՌFR#<L@]Q;gS7]zptlm]qmՌj`TCDdEv(tm@wv7 <nzgy( 7 Q`O|IIk:[卓ar nT:!ʲkVQ7 mXvAw&MCx\jq15|YHښd;\[AߪV O6t7 bPB\\OYL!`tBnC(X%AKPnzE@-H %vMm/7 1ԕBXʁX[ FAos0O { `ƹ-(,)8kč<nzžgQnq+zoh oFE̴JUFKudzQK"3 Ν{ꩧNհ~4@̲v7CY|oI71S(k40$T ReVSƍBQE8sLbd,˰P nVCʠLBG5iF٣Q` i(>k׮=N{ gXɮn2oFtiX%ԁwpO }2 D2E(8FWQpǍBp,^WFa0HJ(jtPR4Aj.&XyxS:h^WFW^;"+m`aJ$Id$W :s#5]敗&Cïȴ _f@Q2Ij5(}3 ޼yn6,.aEXuªV--<dTK˂V:S r)m!1* nzžk%hKҢ8Q0<<dWJg*-EA.,}T-5FWQxcèQXSpg&( 7 Qnq+(~0<aL<IBQh< 8 Pg,< %N2ÍQy#7 bߌ<cmuiGR.ա5BΦ]>"d<5p 9$|rl#U{FUT@Uvv+("<qM 5!lh܅@cFwm[:\c ZbA*U7 b½{*lh-FmN6NaVXΡPF:+ F=geQXzׄe;BpB?p+(8FWQpǍBp+1VQ_mW'ʐa9ʎ%wӲWjNCm7 % Ci,0"?("+cj Ym5 ]\VIm$NfQn,ׯ_=,p>[u(`2.F(`+hVБOQn"H^ t,YMD~X硉GҶM1 7 lCDFSpV;c3z|LY n~DGZq+(8FWQpǍBpB9[opZQ~I!$2w"QnsU=؅(e_glp&Оvûұ7F=}LXͳbRp+(X3g$Fa6Ϟ\BPJh1e{;-`x8Kht7 vڃ>x)k "1 sm]M[q=s-ڧ]--IҕSpֈe#cAhO& SpֈAdnzgy( 7 Qnfa0H;CSur+A$c -L&5R-u *FWQ_z5lH=͇HbS>*QF5ȶ*eg#YS 7 ,(`k?c4q5͌І""Qy2SI ]W2A#rpKFWQk63+m4ElUJIY|4Fa^ ;4BpA|7 <nzgy( 7 PmvICy 8B;7Lm JNBukp+(B}>MDvXȃCډ6<lC}lI D21ƒIR r0WٱGPԨxP99JQnf>OMr(V{]N4@ckP"U4ca|Ti'&hv͂8 A.EvDtnBEQ0΂^Fah3rUi Յ丅_Sb]"n# #BycD&0#c5Qnfay I<#ژc7 -`%zøQnq+(8FW($yky+~F=$R$kԃ,F·÷dhPKiōBQ.1$wii IGPdrX%c< :z~F/W$:*As=X7nzE/|(] 2$)IA!B}v!-th/0 0LQQP+ t7 FZƉ-.3Z>vi$ryD Ц[s5 Ͳ(L$2}R4Vbiʟ(ଏFa|LY#nq+(8FWQpǍB`YyP<hRhYpЌ@(l) (sM|j'|W- I Ү2yɬA Q(f-]iRelz YX۹F@PRoo1V+s+Q4 gΜi4 -I˺Kte*c4(v)fgSn2E1`(FAû\`^Apڵ|ԩSF!4$iKt:q43֕\LեbE2vQ`gj}+Q+e:hfDa`;;B3wv7 <nz;Qnq+a8}M',vP-.oDŚUuU$^F4jWLHȫNJb;,$ ,,DROOb PB %ȃl(]4 ?p xzBUcBFE,f8[:*kiʏ%W}Uדnz{T xl{F˱\@<N.UK6$UwCe#MIDM8Jm@ģQpOY;g6%a;_SpֈYQ%nzgy( 7 Q7 6OfA_Iơ{ӱA:,v<Ub%X)icnzEB}!!Tk, B3[V,5 dD$-%X}I8䑄FZ9`W :ȹOyFW(b ]J<4*74gYOJHt2$Iʔl+mϏ=7 OFy!Cfu-+2J\vTb*S:QeLs`z-yF$]*6*Te#dq+d@AgYj;_h nzEQCT#c֊^FY nzEQLB+0 bb<6Ki玳, w̴D䱦o7 (CT}Ο?ո`c#D8Hhc p&BX8Ԋ#$͘8q؇)8i6^oFۛ7or]=F;1rn q;'QE(dD.+Q'l7 bߌ@jx? BP 9VȞߦb6G\rHʱYDuN8a(2 zu5 c + 7 <nzEQ,CTu)Q{n<l'juYdN#J]08ʎÁra~P0#Gtn $kQnE#,Kɬ@$+P%Um[Rs_FZlEö!*8((!貜 a:Ϫ˸QneE_(cIaL Pfi0 o dDItd r$lw7 (| Qۇ>IUXn ภQfe&tYSpƞFa|L&nq+(8FWQpǍBh5 2Dg'S{PDu"R^ଞ>UwXO!j)upz|-SpȾl;h ( g)8kdߌNRUQ5WFSXnz^gMQnq+ڌe37 bB9[;VX! Z&PTgXO,7 (|!ΝK>E/OaZ<z\ãDPr! "S,HfC$25rxt90:Y gX)sKFW("9s&1 |f[]Mb̶}$qD5urAHPGVmǍBQvڃ>x)kvl:1^:&2II֦Bqdl:@®-"NFW(Z]ɯ @k+Q{h'}*C(=4 q+(8FWQ(ꈫWGwuIkQ{dfԕ]AVFWQ`p4 lfpf46nG>(K `bߌȏoFPgߌp+Z;?GR14"ˎC<IЇxh֔E*moFh ؤoFX+7 (|!4o4-40Z $ρ5 l27#b3Bu7#(6{f}M.leql(.nzgy( 7 Q{n`:}'d1/Mqn^kb׾Oau($7Ym7 bߌ<cml|O1YRBƆ 9.v4]$B^Ծ `W[|!ߘ έBrx^b9< FWQExN3mҞ j!ФنJ5캥-HtvQ`,Y 4^FWQ{O~Ӯq`lkf ! .6 [$Bk(n_#>u(u"]`{ β!bg#ڂ;čBpF5[FWQpǍBp,^f_0D=Fkga3bq;#2 'g:Չޥ>p+((#Є-7#b{D b9"T)fx$AU8ϣt%t("VwU9 wmDVj:8%c9גv+Z/ji`nٖe($ )f4{XDDm46R#UҒXp#.KPYOǎQnF`^:pv]4K7lq7|Bg6`v&\&*iRGh$Nqh^(>Fay8΢hC]c {e@KA_UFW8Sp+(8FWQX <8˨SN.֞%YUKF ~jeYэBp\YZ]{vP`+MrB$fa*+oIT!ҟPS3 pV.t<QX4WUaݲr֥B('_H%YlP'![C/7 b(c֭mҸx%rlJM%Y*`F0"団SaV$7 ]`a|Li5 3'/P^FY7 (|!:(2 A:'8cro Q? L"@]'ìčB+pWƝmiq=<)D#QR skHqPdрDh8@pVD|$plo޼]4`6Ka[Dؤ%9ɌnC,0ѠqY L4X7 (O1DFZdoҤKLZ$I9Ɍ(,<рr;-@SpV^_=: yYSpe&( 7 Qnq+v(V&뎆UVI! f|zхUmu̻b7q+ڌ!nW$"aXC-jBE5fS-9|y!.rBMYI @X\1]It4C̵nr7. i_a`;캶7]=[G8~-6h> [-I$j7 ш-pwq+:hP5hҤyo4E-H0lٌuWIǖr+Ԉ&iV?GSpF®Fa|Lnq+(8FWQpǍBEP_BLu慅0"Z/McKs:עnºq+v(ԗEHVh eU _+,DըZ %-;$ad+t7 (|!v(p-+O!rZlހ[صHQF:d+t7 (}d,BQ+#(@* `SC-I'kB *f]T,aFWQXɲpblf/)8]('jbjqY7 b?Z( 7 Qh``%c<m'haFiBlA<Z)ȶRш?}p:͎l÷&Bhn`4@y NQXi0],Ja}sputV |Bp+v(,SX-nz~gQnq+:ezbݬI3nw~MT[&Nit+ڌ{?U<cmZd; !! j˴Cfƭ9KYtv ?B<U :W[4 ?p $m [6m-1g@Pk W`SROuX-pGq+eSHh0l?h6kMCT >`-sß~x8էN=S QթFa|LF8Sp+(8FWQpǍBQxWb,w$N3(|)D #$<ҷ ;{Q5 m\pM^.8Oa͕P^fv,K*: hU!aq)%KRY9>eep+l_cjKhR(l-r4N rl%WmF!_p]B,AL8"<=BQ4.v 0m[hJ5,h!flʏ:\ P=gQX 5 c W^;gݸQmFLBp,^+F,\a Ivテg!"O:PΡGr1hҠ3mߞMQ5 Ν{ꩧNlA"F6& P~Tu6oԧ$SFWv,™3gjF3Gh0_gHO?0UgR&Cu17GӳnzEb 4l(\v<uT(c\7б~Au? bAGPc%:8=$@N}!mvwN 7 FW$@>x Ϊp+[3;nzEb 41m.eSmRY_t2\JlK,:ʥLF4qFgt&TGTB>׍^ ;jr.,; :!IluPhRG/>=iw2'C. E~M"Z#hȈrp,rD`(u7 "(<1mYK#z`m@\J0 1f+˴SǦ"v$"F!}Xi4 6)p(hi@ic=qZF{qz.2qtnGK9G]HDxزSS:u ;gvmc κHl7 Q-а&/*8čBHl7 Q-а&gd4-{rlDz V$ 6u$ `*ТQFW$@C0 e@[DY!Oḧ3LCtn\BvSSSޒVO (LW^ 0 ha%FA3Fs?jf%WlÕZ sAvPƿjq+[aF qB71GTb 9M$'jĖwyn_%z,nzEb 4(m7h;_&ōBHl>Q lAp^ k2 N/q+[Aƒe37 "(8FW$@gv(hp̎^ (!CTu)Q-F7 "(8FW$@gv(hp̎^ Fᗎӄ^ n k7 ۸l[$@q賯۟0M  㬉+y ;x7;w^~",;㤕-Y`Ja i_i^v"ILkΝ|=/|ՕH$AD9+?7q`qgWx 87u &)94^'>ug!v} .h_ >?WpW8Y) :lElr(*;PB_ 3=I} ܟ_͇4`U (&1E UČ*GUli0?ql; qO/!N :D8 l#-? 㬃ƮD?zH0Gc4m 8`XuS3&Ӏ}TI}U gN>"񏊝wՄ8Q!㤃笰NQBL"悰ҔtĻ,uq CyԨ0wH0rr+@b{IOྂ8 m=mM;LUW#"IF}SjtNhYW "1 b U^4DLL?_E<JCϱ(?zNBY}~7o/+"zF?{}wI,k/]Kܽ#^{Yx#!Yx/+8ůYW_dDv"I/0 QX_a)Q2SJ8:`_zWyVTg^com{q*C5--*3$qVOE8N_j҅G؅ ]|ŧ >iX\[Z+p7/."8:p_q:JGo/O9 OnƾקC{gd޸xcWg+.ވҙ)C8++<7o<I*B>}8cL $$1W\ >ՋCիѫw=o\r)eRGۢlkuBG?`r* # (ɓ`pEܽpV |l oyG̸8H}9ʕp]9O`u5 zVX4WDN+ű7K QHQd:,6_!qWpgIV0pp.G 8*x 6xϡПKG@S  Wp֊ ?o>8Zc$DwΝԩ+y ?_GHRfbqgƾB.A_A 4>x=o}qZ|q¼}qց Qn~uྂ8`_bk|ʀco}> Ȥ(m9iyyV&Zh3$~,A||$ f,hơͳZ-B$&LA $%|*r/K>h{+V׭1w t2AW8i}W.LܯIpZvA^x*%*SA2>Y@zUPyt%W8wSO=w&A{P 7qa[YHXZѥw/ zwjڸՑ]S㬕 ‰L$d; 'C@ȹ8) fTx<I6L=OԨ {,_4g%D|/8sT_7M hC$x3;BcP 'h$AhLJzZrR4$w6=㬏 {BP=&ǵ疜gᑦ^Y'9I"iNC]xP$.<n7QP5jWIv"K!Y^Áy7kO6,D;x"dT-:js yP>`93L8+g-sQ? _wu+;W>b FvE,dvxt")ve\< ?I {t$h[x5 4<}qVȾ rsZ:N- "Aw__!>; ΦX8߿G  t﷾?ˍ}qBx_Y aOpTsvxY+16okjN#Ht䉆v4Iҿk4/ }mgNWKB (gQ،|}>@Nou_W^}W~u ,qҀtEҢ SWEQU}MS |__diɱGu,+='a#<4sg}3{A9P5C0\0)C]okD*zH^O`*QDQXx Y)5)_p}WI}8'~_WTLDžIخp7oR# =qO?ގL+ |("lz͒'{٦Ԑ[vPϘ  3+0zӘbD2ޠ(@},+<Iؖp…i^IqFED!AؐW\L{Ъ+B M7 ngbB!p-D+ /Bϟ*QWvWX!IGWoWgh%G⎂3S}q t8NGp_q:ʮ J?g>qqiX9A%̔t캯+KQWJ$>4Wk'6V8 +8NG遯05K8F5BzJYNROv QWp_WeBz^JOӈWhjr}( M¶|__a">[{Tۅ'q<$C/]uA&$渎cq_q:ʮ +DOT=z|QQp㾂t+8NGq_q0Pʗ}Uyҕ4 V{φ\qqXWxI謯mMKf0DiHApz=8šz21\q!P8{\+3 pb<x#V>xWFC{a4&g bA΀:!9+u+;w;Wh nN/^وM$E>љμ #n 7@gLwƾ$ Y:qqv|=$lW9sD___)jN' KL$%7qWpz fbWO?о Eѿ?3Óq QvWI:NgW`"$stP.Ћ(+8NG齯0;73&GqG}[Bk,+|, =.c__:# * y>#f{D_qȸ?3e/<k?/'8NGW@wȳ GbUfW"&4['||W6}_/CJ&K%d;W 懿vJ4{+160 s3C[h fѐI ,yVdK4< E_n~q sDžͅBZ;g_a28}EI]^W0۱K>I1 A LxWDWpV ϟkn_+$fR?j 9<$_{ƟtY};:iV"qx@|8 a"0D!3}PໍnAj̮yPϾ#<C$hfju[<a.w&d, IBl.ܑCY%p{_vóOT: c_S" h.9xeĜFz gOX.[D t .l=_>i1>)nOm}^˧E7EjR 0)Bċ!r4%^; Irچ0W dځ}`0mqͰ… y D;)Hqk/g>oAJP| TLrS현T3j|4+A3v!O, p\D8rq ,+XvWX! "5Vb?3{}c«{bNsl8fp_qe_}~|gʕ+aNjdH$4pᬐq6Ǔྂ8Km_o}]IK$OPS[3"utEbW_q4v}MՂk!ũKQӈ?)Z7JiKkqUި12gY1vgNo'PO:)Ĭ=$xx5X{+;wұ|{qn%Wh9C$%ﴓi?Vo>A{oj5E9[6:NG[_A?i+ dE鮢\$iV xnyفL a}ryM7Ƥ95s0fq=C?_,6 QDi*l< $Ƒ$e&x9Kl]g[8e1_>Kx8p{tcwUZhҴx"mz{9cm<6+;(b>S~q?_a&Yoq+iW@jrڶ-WpŒ$:iYyI@5g}?kgF;VCv36fĩ&SJ}MXrárgQRIKF9Ӈ%1L kbZ]LhU"XG<5aEtd̶⡷xqIEa 3*7RtC.fp?q_rG០>͚n0+0V_=PR۬[@ģU[|0(u4 î*Py*T,l%H`Z"UBϗ8~h Ì&DhWw3Ʈ*dd,pB^tj!+8R__Nu.3n+PzC,]5c<[.\j xUH"WˤHȋĨĥ/hMrAILwۋȧqǐ(OQg?x鈽2Jpq_qqjwܼxKqGþt˱`Q_aV&hbTGx`7E:OG/2w$E-+ Ro k": sqiJq8 }Mc\HsФ"L`0}r⢅k\'No|b>LJ='}"h |TPHWh[k7qgo|]HM`%>K˭H-a􉱯.4ЕӋ; @ΣnqQ0/'.̐ I8QIKQMfap\H6 nIWTCoI٣ĵ%wྂtfgօ+m?_#A8D1LK\PI`J)ْNop_q: k"֏;uO<Cϭ;0P:]լr2Jdv8}µ7WpߓWʽZ/_܇He8YYq:k|Q/s^xq>Wy=E/<2ȿ|ufȏ%'qgfZ^'oL GG v WpV{t/BO顯P~&_с`^?“wPVlZϠ+LLHo ҵTA=tvjU 2ü†%ntA,|Эf|6_aZWh.<tQ~Imvۑ.8NG衯\kO?;a8}zÀ2yߘW2}TBx.ԱG$SDB OHJ@J%i[hl_,<;< X`]i٧}/?dA_!\x1q_qqyۮ.<v+(*lu_AʜfPk7SM@g3=0u,OёcԳ/+L)Į4 ҧ1:6^'xZ>%Bq֓I+k1xBˣ@#1nsytΤyWe IDw1(w:mtΙ, W^}W~ t1.А&>#, "3;YWDW8 Ld޾]5= 7Q,4?Y}$mkUzD́n⾂t|wIp_D+\~͛$hg&jw|`XfV ]^=큜n⾂t$ V}Ÿp4/f~rzesz0MsIWej, ba&גUEsZOHZt $ V}gB#5!]; B;jGbS--PW# ] X' lj+'ྂ8K]_!ѣcJԧ›H4 ~'8:`Us_qu;BIXx ڱPf}@20S6X5քze҈ ˕*ãq&()$UR.<h? >q:ušH: ?=Nsw[gV+ij1 %uZt& ?._u Q6X5D)PYq\DD($ʠ%W,R=nOK=鯄TӝWya$.<L o=!p_qu|O&}ݶV ʁ+iٹkreaL9Jԗ^_ q4 rdK;d-=z*G/wz-p" j4[NC"wzsDSl=d`|hLjL98$c 6X5Щ7cn_!}AvͮG9"äQtb?8:XֳU`:Me+03`t$ V}qz| ONX !)PfT&x JƾBLNqušIڟ?VNņU㌰P-s&-a^+.v7 v~>32}sX' lj+,ùsz꩸3J|FeK* {wī%Xi$:nKd&+8NGN@`Wx'‰KxΜ9sG(MFdJ=Z?Yh ӹjjV$Iq0 i<pP$ԧ |Вul]L,pgX' lj+̋z NF w|`:M9xxؚf\$3&Y LWnmӉv:A8k-:`U[[dWX OqoVǍO8 P~0Msဋ Y@+H|XRb:]iH2J4q>n⾂t8$ V- `քO(tsY' lj+8Wpg?8:p_q:[u†y7bl a~y kp\ȇ##l!~„ƯMeΐ$˹=䃙dUeN⾂t8$ V} sW+qJ|FY2.\JzwçdjHt]FWpgX' lj+l Lc 4rz ]2<"S-~P' MTtТґ/^Ƥ)%'8 QRc^;P5gH]ǖ\uL8:`Us_aW~͛7)IОL: }sdU]Z I$IpNz>2 I_A1qLtDZؒΚp_q:u†p4/]fx_{Y郫GGPw6i-fnÔDg;U$G׼4$ #&Ŧ~@8p_q:u澂B>1q Fp_q:u&O%}q}( H X' lj+%k tw괤V/ d*—K3Cx;F~+¯;͛OQ4J g8:`U렯pܹ7?#4c޻ؗ3I9ڤ,YM'. t09}( HZ|s.=HbwT'Մ:EbIJJIrg׏;'ݚϯB$+0;AJZrKܪQ}ڡgyWpb?uWP/zp<Q=?:KS#¤賳?>nS!8}<2ܚğ '5b˱U;, Q6X5T5p"73=܄<мD!X#)x\k·'Ujjݸ娄E1b55cG S)ܟA8k}( Hn =ǽf(8k}( H X' lj+8Wpb?_ m]_I$#=>Ot0gnS;5Q2X' lj}:0b0Z!G0q|{] SX' lj+ ;+tya[=6P+:V7!.=,|IM ȻSN5O?EIX' lj+ta8뗱JBʍ!01*ڼ8av r%Q&ƎZ@Np_q:u֏qIK&䡗 Oǝh-ǚPaL)0CwTEu74->[{TwYQ-6 XUs#ᾂt$ VmO|g~=kB|wX' lj+8Wpb?8:p_q:uocS(aqeGø_1gc-6I68l8R?x5P@A °MR/*h"QWpb?_H ϟz+k,c;*Z<K7ZR5I:z ~nA:V8<:ᚔ̆D>AqŸX' lj+02cR;`jBТlpMXC j[ID2ϖjVAqR'|01I mP;s8:`Us_ׯ߼ybxorƽZ쭣?!BSB4 r8Ɍn[BbXOk:+qP+v' \?s8:`Us_… Ӽ2я߭Cq*a|*?kVB}\(8$7cq:q9Mx$hNn<1: Z= WL<H2n8:`U[I_H_  L:+'{}( H X' lj+^YX' lj{+̶B:>}p8MN) It`2gH fC<̴s\dwvX' lj{+̶²B,.\ %?·@n_ph|gsٗ om4ƞ⾂t$ V}FZW.3Db7)3COldyOzqJ,4ڛoSVT:O?UIHKB2`>02DN9}( HZ>}NZ_!to.YֻتKVمDd|3*@D- J=D'쁜>ᾂt$ Vm}W=txYY2A`J\5& 4[ $ R+w 3L;$.\R!T<⸨$WH X' lj{+8ӈrąrG8:`Us_quྂt$ V}qց Q6X,UwayBY-D*U_CImlE*?y惻T N>s2F%f$EqW8+}( HZ|s=SqgG|_!vUoEI[a1Ӂl9J]h%rY wྂt$ Vx̙3|>r˽u}`@Ы(Gws+nc/;%iX9&;^D^-%Գ8Ϊp_q:u&>Kx8+(2>_ܵ]!v!nEHpVjLʄEŝ@]b4O$8㾂t$ V- I΍+;86P:3PQnu"qE3>"6&6tDD#Rd9] gp_q:u]L+tv CD(8k}( H X' lj+8Wpb?p"i -e] ym_  c`u`>ᾂt$ V}jy=uU4jul,'fQ lyQSO#+8NGN@`WX ydæ$BnzK;5K [M 1Ŗ$Nc8:`U[_a 3L O B1*;ltRXl9bkڡ]}( Hڞ+{2>tסrSTf.R9TME,y,I-= aB9x0S$ЂՑ]\Ls&Nop_q:u澂*o`oZQ)+8NGN@`ՂhWpgIWpb?8:p_q:u&M +<."pPLW ܚH² hȤP? RUGT]Ockh:+8NGN@`WX 俸?v_A:z dun>+[DcuƟX' lj+,l 3!94C$W!}VDBZӭU(ƾ9v̡x&U@B !5 rĞdBcp&=Ӹ8:`Us_a^Y! ~TBDԪTVN~ % bXݻ'٣oa^iJI4t:%u ^Δ9; Q6X5DYBu/=bW(~IW <eJjAtqvU<^~y+'LF&rBKdgwq_q:uNcJ'=N㾂t$ V nAGྂ8K⾂t$ V- M , Q6X5FY/e KR"T})Q+šL$h[O/wJKl"<=|ZpuvXRԏ"'+nLSu{SŒ+7+8NGN@`WkC`t!rB.Yڏ-J~.5nu4QgK,X' lj+tzh%l콩&H3@_[d*@Ђ$gڇaPRBDQ{S&ܔ;Zuy3K30K:GI_=qbVδ\ᾂt$ V}ГIG;d<` %XycӱbBd7BHSL%=|_+lɮ^o5~h)%tX{dӠS"*ྂt$ VM|}6 +lНħÓ~.J¬z%?/7q FLѫB YU'`G#.}Y6dɐTj1K;Cs5؅xPk:,F&rapLX' lj+8kBѸaد5a}}}( H X' lj+8Wpb?_sIp_apB vR}#`u QCƼZr8'^3䓧fG<J]R\+ZX' lj+t^\qVo 8Q_иhٲs%!pOp_q:uB7IzǰޛNC v|e$՛ z|beQ\ +8NGN@`W&IfwC]Q&$W}e-#۰#F}A%cWpb?MlOtuqtlqWVr@Љ]x5өғ1eDrfq5z Q6X5h0}euྂt$ V nosIp_q%q_q:u澂8}( H $<e9,dՂ|pk EVd`d- 27!%,s$eɩ#%I R 㾂t$ V}5_Q| >kx]x[8 GykuWpb?_Ꮣh"o0vQ]ROU񓅦Zuxb:hQ]{LRrrj:H&a:H r1xfq Q6X5ք[ V%K<ѫi!l-$$H凹3*@LwuŖFh9lX' lj+^Vtma0M@ ,㄀x$H?\,]#NeˑF:֥p Q6X5IbSBp_q:u澂8}( H X' lj+[dwW!toc=rt7T?p_ew<@vwe;ȣRBRΰ(X($#8:`Us_aΝ;SOŝIlO\ZRBсH_^{4 9}( H /8s,:,&2'x^Uۣ@ ɔXI%*I޺&Vb-MC;z <Ht8}( H ^ÁY|ҐʻdvBjS\HH vym (N6q1D9 Jr8[}( H kWE7ОnORĤ0bGymʶ{N$Z{&Q"!D9q( 㱊Np6 Q6X5`o gBm!~; }( H X' lj+8Wpb?M-c2\&L;pK:PM9įZIw@{9|2|#J~㾂t$ V}vl;Inl1l?|]g2?n(aRXtS>GYϘ0K9WCS}( H ]C<7"=~Q [T ݘg jzs,4y;XTv7!pD\!u7"lqg ?A̯S?⾂t$ V}2:gUJ2Tq+TLU_hVr=Iv'ƾN~k=!@D`{s;5ZI@wv2}( H Dg}gqn\zܪ`QK[+TpHâ 0CQV8o-K<xdC +nuxqlQ2>Q@W0.S}( H ;Dҽ! xnbȌNwZq_q:u澂8}( H X' lj+tjd~a+(P_9|ɷ+LHʉ_߃, !㾂t$ V}pܹY>Pifc1Lñ~~jBdafSVtX' lj+l,B[SInT-C }= HLIm<4_ȑ;"KHSg8:`Us_acp`_A֨,Rz@&PXWD{qI|ptwab,8}( H ]}^WFhS!vzަOڌ |ٕa )NfDMʷ O#JWpb?, {.L/ᾂt$ V}qց Q6X5Y+8NGN@`WxB|"PgzL0=&+0Ka B̜ES<,sVJJ&K(ajA2qR9kB8:`Us_aW8իW_y啸_`1IT=;vȒBgJx(7,kMz9:x i Q6X5v LwEr*jBТ4b˟ AْZ/}t&oT' &Dkw7j''Wpb?+W~͛7)I`^S7oC_=] Dd95 i< jh#b.=NO8:`Us_aWp4/خq ߲Сno܉J:BvVY2ʩcRȸL2X>4͖ mHTH5Y]W N+8NGN@`Wp UQ+8NGN@`Wpg8:`Us_quྂt$ V}>KƒFfHG9s?bפaLII#I9qr^`q_q:unqܹD_5}أg'KH& u Gr%e-Sz29I'$w+i(XwcVA /Xsd1ZL"22ߌ$YꪮA2d?2" STM;̂HYB@H è I9 XK[+V޴FOc1K (v^P=&o01=;CکkN+o9r*f|ͬ./jB:E@hF?I,hGJRS!&iޤ.[r/6Ix*;mflgmaLDZ. =9R۩:UGdv2/ jB:E@hFp5Xeʕk p=x+Ud*ϞՉ^GP-K>]8am04b<c2ܬUyLeePgKZNAQ+!K?} ZNAQ+B!" 4 V jB:E@hFp|%|獆f^vK'`$f>8nǻ9$!SB@H èo}jgfWjyb`h~Gkyg{t G*,g6#!" 4 Vzc‚b~MAY<_*zE>|rꋽj[ݣB[PR0@5CںmYlO¡V SP}a WiO>}:9A A KT\>H+^*G=]ݳ(immyFkuac卆F/jB:E@hFp{nN%vv!±TKXȀo feF)@>݃nyBX9NJ,J"P+)(>@0jrrp1ତj]=x)6"!" 4 V jB:E@hF@9 t 0Z8'|-/&GG g<s摀C@H è^777#__| '~X X_?# NB@H èV6/@zM"sR*܃h&'ӧ#5.8:B+\Xʏb qAa*ĜVg ŴuCnn.,&%MDɟzTX<ZXN˽POΓ t 0ZR4Z-Bm)*)CM<^P ` qA"Ʌ,\ ů z $Okziȅ9NiV SP}a $]=C  6^V!" 4 V jB:E@hF@9 t 0Z˗ܚ/|"?z]8 <G4']??Q{|&8'@@H èo߾]~Ol<JXª\r|CT=nꡧG(Aa>f-)^V̿d4նs;=m +~=7 !m `݄j7aR3!`*zOEeL tAAaô§O>imKNgU b$6\7DUo "&fۿ}z|/rYAaݻws**_pZ;$o{d$ޞtB }.X@o{0gL哇eV SP}a %",Bf]bxRjB:E@hF@9 t 0ZrAa.U|GߟXv_NpȂ%9~C{"K=>qK"u1!" 4 V s|~JHOx-8Ix[)E>N!}A9yq.<1)tjB:E@hF@8~%u sfvp[Ǝɲ7ѻȦd3Ohs.VKNcI'a甁<6ImP9rBAacr]Ϧj;= pa%0~t6'he&THaS sas? ^SCjB:E@hF@8~d=ƶ0RId/hB]'Ƨ:.׼A"=cr΀s)#x 4 p$@W_ts<ExAa,Zb-' 'F\n3A@H è!ZNAQ+B!" 4 VxbVnw nfȵԽ$|D]WCQ@>N`>,8G XNHAasϱB+-kr>~ܔaB9ԁ؛v/)U &'- t 0Z9҂w۴ ^hS# 6g]<X۟葪ik)V ɭ$@:"N.$s(4~я@͗<FBjB:E@hFĬxiuTz%̃U b6^Cr0nNM2l[BH6>{2`B!!" 4 VxbHE42oWG{ 7vwLh04ZA&$KL׎kBT=&L +!<!F7*!" 4 V ψTOlq?%djB:E@hF@9 t 0ZrAa2奼N}V`wMKeoC}1f6F_cNcP+)(>@0jy沟X ~ŜX[17&D( zM !" 4 {ZAT«W^~Ԥ\r@*?$`NL)N %*nxkul]x mӳ!tPx]YacN<u o{`+G<5iP+)(>@ð\%|xкUж*[ALe-HV}7o(5/f _.yę.tEakcTԆeJ7SB+ҒV SP}a/|] VN[֪%G|k|ފkN"<IdZ&􅎱cdn} VҎӛ"uQ ۋ=օPŔ8PMO( )ɡV SP}a $T,.>Du 9V SP}a s@@H è!ZNAQ+piZ/7ғSgI:-(C~2#<1s1az!0 t 0Z1|1hĴgu<dLc]DD( V SP}a DZ R{aE/^\[XE"`cfg9]OOq8Ղ16sSki_2 t 0Z< RHK)IuW*^x{5:d$8T,'~)m4j&iXٶ$9z j=e\ 1(n-*fiEڗ !" 4 V8^H?iuN3U@Z+QVJW*WM01oEE $ty<BAbJΐ<dS% :AaY&bA-u)TQ(,B@H è!ZNAQ+B!" 4 Vx?;?z}&B^osG{O_bk8\|1SPIijB:E@hFp^ .> v u 'X+HiؿuEbEo=BpN9|QbaUP+)(>@0j']/X#`/]YYMm~P.gCw+EgHrBR/Ǟ#ScIO\i _$9: %XIP+)(>@0j'cKHoȮvpJя{QTRvkgÊ<~Co{VD&"9T#panZjOA<2Ѷ_gMZZNAQ+Fn@g.+W<$h`}m0 7$ T9dM.&Q:Jlu#4v- @NϳPŔ!yYЄe]ZYpѰjB:E@hFpMz@shqaqAD=H( t 0,iV <jB:E@hZ~ZHAas˗/5GpoށsxgZoWTǻS`2O>'xuC@H Dl:۷~oۼ`UZa2IܥbG+Q!8'cy1@ ԿbAasA5XRêWz]+9TKI+`Xmk*;!][ao]b='U+%PlV%r0 a\iX@@H è >}wߙ' /yͩ86,c pKh3`14@ GK4&V}9P+)(>@0j»wTʮ]k~mVhu\02+޿uZAX1a1Xу\(UL1SyJEAayXE7]B5@@H è!ZNA%!ZNAQ+\ f3d~;0Z?~?O6o6a 2Gz)"G@@H èPmKlip"Pͪԣ) r[WVaoNrrAaՐ"htm-5sMBcBt_3KJ`h5w#\ѫILdLjB:E@hFp5ž+xvu 6X0̌WFe<y#ឹ.$P+)(>@0 #@藒Y]yk<&?a)ȩY\c9TɗYV SP}a )5A9V SP}a s@@H è!ZNAQ+<|[3 aAۯw\ zpq3Y}s $|,<`GZNA%` ۹QV5&D]_Sai[N>$[<?HvhrhKU$DZNA,ÿY0joR sk5zo!j6j)iR#cͯ>섄V}07.^drVi@]Xу'S%nV+XN$|r\h&V SP}a  >}2%g.ru]~s]BkK31tgbi~Xn7d~Ú\3CLAasݻws*BeWbRęKo ym:`.reBW83" imciƄioSb(8CׄE "P+)(>@0j)B5@@H è!ZNAQ+B!" 4 S? Fݮi=.@{`> Ohw6O~g cV SP}a yc gR(Z0d997Ly]z!Y64V SP}aI+}0j!*իW_^ ^ٯ ՙ Ik[ԫTʹ5%U0h 9MTymh[?L jB:E@hFdJ&1zْ{Z7NK ,:Tʽ2<Ih]o#s#1V>&I03FZͬL jB:E@hFMt- tݬ5ON+^rn<l@)KچOj@=dÕFUˋJi ZNAQ+<w,7.: A@H è!ZNAQ+B!" 4 V2?acx@_C&'ܼ?ٍ܄5t> H'>iV<r'!" 4 VvXm2PN?fy"P#~ۦ{xVy۪>yP+)(>@0?FfzHlcWI@h,KXKe/1 / k}s-\Ye3fzB;I'* 0 BAXQ'秚UB@H èWy;W;+TRJeuQZP6:\#]ݥu_O1/4<m&nw{Xz? uOJAaX Z* 8m׊[ )^-:v+2&طHV !$ϴV Y .kC|9Ok2,ZNAVoZkv'A|BAV SP}a s@@H è!ZNAQ+\s AݱR_[$Ng)~~B?9H1|#Hcɸm3cW!" 4 Vx^~RJI? qP+H}gfE99A"=<C<ڞ9U^(Aas?i=)Kv-kVW+J_We5"t,]rF+)2D_m]Rݝ si@m@6e3ʓzо~76jB:E@hF?I,hG|]kR#~7pK hyJvg03<9۾>(ʄ u&̪&y\1 t 0Zj*]p'O(mk v{\v֞ԉ9նv1UqJ<ε ̅,@چ y;(q {qva.8ZqP+)(>@ð` /PO(G= /F( t 0ZrAa!P+)(>@0j",>yg8"I-l1oo3Ϲ>Ꮕ3w6O~t%C@H T+ZxЋ4 3=T-V#B:^@@H èǼVo5e+Z( oPձk bi% N_0g8(mu%ՙÙI;5ZNA,>VbLEIRmh+\M XN. mXq$9]w37s3k$S^y3yɜjB:E@hF@*UT۴M:\bdNhTzsd3-{HBVw- Ca'6v:G̃VjIDAT^Zw!y3N9.8ZqZAa9*Kje)?9@@H ÒVxZHAa!P+)(>@0j?aFކw7Xxu#x4mǻT䡤 r$zޚ3vqG'vnVF'WKtyn1w9 V SP}a hPf<: 3J&*e*z0|mWtl`m ڇ !" 4 V \5դ\VS;_źߜV؜AȪBIp<p-ɾr,eN& KF;I0 $#bgF]WČv2gZNAQ+5 CNFEIe8q6n٤8H1 ZirM^9̬Zgm9 t 0ZMUJedio,NmKmKywYh_%2=6ðB+c1Ii&zBNhNK{mE!y3Ϊ93.8Zq&Aaj?{Z\ k- .' !" 4 V jB:E@hF@9 t 0,i F!_|ɭE;bW%<*z~lGHI1x-d=ww !" 4 Vx.}ooZ!w|nY UEGgh;N'{P+)(>@0jhk)>oR1Bs|ru˃=9 {8*!]1$)\6IQ =h!ͯ7L' ti'sP+)(>@06BVw}guTz%̃.f{NxX !l9IH7&bm`¶'e1Ϡ%ȖB;ZNAQ+<޽{7TDTu4 78'MI<! R&`U<}]#W !" 4 V /Ta!ʈkZNAQ+B!" 4 V jB:E@hFau7axۺҝ7GrCH3sۍgϏmj]&Yγk<u9!yJAaj?^Vy}ި+ x-uۯ8C}gr<`zɉjCrEPݗڃeV SP}a/\+Jxׯ_j3O*H~kN[uHW|s¤ nWuBY{-C}DÜjc#bQhҾ  t 0jW $֯+Z2@EP1N|ND$)x[ܛz+a :s}#uCr#x.RP+)(>@ðp=e]A/Ř[Æ!q#bnmJjw9^G1lV('V@_3F.!" 4 V v c(ZNAQ+B!" 4 V jB:E@hFp_|ɭKkˤ. OV`yc$[&쳍sS><QΡ}1u%]C@H è۷s߆6r{V+hķfBF܉GXyvy!^zP+)(>@ð~Z haN1چǦg Ŵ9Y+i#9sR}do7 mJBəHH{g@r/8ϖ<NF!dhV SP}a aZӧOs߉N-SFW |,V0*4}gmSIU'TiA}e9bsFۅt!" 4 Yݻ9`zV=)RVs.K+Wz_rŠBuͭ1%3f@L/%0PAלq<xȓBt !" 4 Vxh)-g%KjB:E@hZ4!P+)(>@0jB9V SP}a q ߰[{ ,5Wx&P+)(>@0j8~)+$X Z;/qo~F+Thx5yg!" 4 V8W@ClPu >r#x.CAaq|by)کBKTc4`f~B7B'x.CAaX ? Fp_\kϞ!ߕZ;g~%=g *[Aa³+q>`W6^ _@@H è!ZNAQ+B!" 4 {!Zٰ?n]ҝwwvP<*oػimrI3sN*|??.[ͪW쇯 @@H îI+ܼ>o,I5i}<(ۯ8ѩN(欞@l<;E=v 湿-'D4h<1' t 0LŸ$س ^ze`W< iRX+9aIs~쥻gJ#qヤ<g:C<&>! p]9i3$3<<V SP}a]+J&~]= -uRDb/L&)SM:C !ċj[NWvAcζ/z\My|@ŃQ5CZNA,`n] V<ʺ^O'TAmuj1glE*:f:T:7̣7SVW&ס\^iOf͵uQ ۻ&7@|z#cZOHG O!" 4 KZ>@Mcc(:ZNAQ+B!" 4 V jB:E@hµ—/_rkncC9R]'~91NȇcS}̟Ȗ<'oֽC@H ^VxG Z/ 0Vt{Ev T&?9~]nAa5C*8_g'96EUVЎb)KUVhmVq 9-lr&6JLyrPEVj,ߴcp9\ t 0ZAS=km)Wң^-@ R/C-pJS3IJTF(FX!`?'݃i&!" 4 {Zݻws*H+{S 3(]WZ} + RL z@=P; )rI+LmXcy"ǎ8n&˒(ɈNjB:E@hµB'bYɵ!h#r}P+)(>@0jB9V SP}aoQ+B !" 4 VX&/7z~J~X؋gOh- pcyHi'srֳZNAQ+777z9|n}Ku%nsK .&ڎ< oxjB:EJ{Z?i^z+,Sj0mнޅ$\OAɴIG )g5gM2^YΣGkɐV SXc/V+J&qP+7|Η_Xrg2 1 yqWll<|o.]lMrDv2+锠 _W8TsqZ"8ǗoaLg%H yL ^sA޴ 1 ]A@HD?` -e1] jB:%5F@9 tJkZr锠X ZfMeq_S#Ү1lk3O,o/$\3n7oQr>n`cHd锠YY  K]e[ɋTar<-)XAѶr9mc t tJkZᬄz63ѐ:Tʞab׮nc/yi@]c5\=9 ̏UyBz 3Z 4";0U=p3+L tJkLu0jS IyY^H@@# D'`'+md 6͒H1Ո@HFC^!f V SXc g%z[ïgu1)uNhwDX]0I!fҺ6c@جz^!jAN&M%Fɍԯ20F79B jB:%5F@VKaT9$@@Hƨ!ZN :`=#֯V SXcK+B6{,Wls~U0l~ps7?)CH_]c1[HIf?c1<rԾ!tKZ +G|EZ0G_351˖2TU=pWkGQ˽4 P+)Agʵ{Xٓʕ_d9WectsHKmhfi4piYpP6K{g=pt<H锠s_W@Qc zF:쇿t/&0@x؈֞A;"o?!jB:%5aLU,1~X]kz0-9X۾7풞01fjsImq931覜Oރ SP+)A1~[@U1}$B tJkZv#$@@HT+S+B tJkZr锠!P+)A1jB9V SXcI+` GB@Hƨ!ZN :`Q+B!tV jB:%5F@9 tJklVh4zV SXc+!!P+)A1jB?NNIENDB`
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IDynamicInvocationExpression.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IDynamicInvocationExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_DynamicArgument() { string source = @" class C { void M(C c, dynamic d) { /*<bind>*/c.M2(d)/*</bind>*/; } public void M2(int i) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_MultipleApplicableSymbols() { string source = @" class C { void M(C c, dynamic d) { var x = /*<bind>*/c.M2(d)/*</bind>*/; } public void M2(int i) { } public void M2(long i) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_MultipleArgumentsAndApplicableSymbols() { string source = @" class C { void M(C c, dynamic d) { char ch = 'c'; var x = /*<bind>*/c.M2(d, ch)/*</bind>*/; } public void M2(int i, char ch) { } public void M2(long i, char ch) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d, ch)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(2): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ILocalReferenceOperation: ch (OperationKind.LocalReference, Type: System.Char) (Syntax: 'ch') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_ArgumentNames() { string source = @" class C { void M(C c, dynamic d, dynamic e) { var x = /*<bind>*/c.M2(i: d, ch: e)/*</bind>*/; } public void M2(int i, char ch) { } public void M2(long i, char ch) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(i: d, ch: e)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(2): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'e') ArgumentNames(2): ""i"" ""ch"" ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_ArgumentRefKinds() { string source = @" class C { void M(C c, object d, dynamic e) { int k; var x = /*<bind>*/c.M2(ref d, out k, e)/*</bind>*/; } public void M2(ref object i, out int j, char c) { j = 0; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(ref d, out k, e)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(3): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'd') ILocalReferenceOperation: k (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'k') IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'e') ArgumentNames(0) ArgumentRefKinds(3): Ref Out None "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_DelegateInvocation() { string source = @" using System; class C { public Action<object> F; void M(dynamic i) { var x = /*<bind>*/F(i)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'F(i)') Expression: IFieldReferenceOperation: System.Action<System.Object> C.F (OperationKind.FieldReference, Type: System.Action<System.Object>) (Syntax: 'F') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'F') Arguments(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'i') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0649: Field 'C.F' is never assigned to, and will always have its default value null // public Action<object> F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("C.F", "null").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_WithDynamicReceiver() { string source = @" class C { void M(dynamic d, int i) { var x = /*<bind>*/d(i)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'd(i)') Expression: IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') Arguments(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_WithDynamicMemberReceiver() { string source = @" class C { void M(dynamic c, int i) { var x = /*<bind>*/c.M2(i)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(i)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: dynamic) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'c') Arguments(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_WithDynamicTypedMemberReceiver() { string source = @" class C { dynamic M2 = null; void M(C c, int i) { var x = /*<bind>*/c.M2(i)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(i)') Expression: IFieldReferenceOperation: dynamic C.M2 (OperationKind.FieldReference, Type: dynamic) (Syntax: 'c.M2') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_AllFields() { string source = @" class C { void M(C c, dynamic d) { int i = 0; var x = /*<bind>*/c.M2(ref i, c: d)/*</bind>*/; } public void M2(ref int i, char c) { } public void M2(ref int i, long c) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(ref i, c: d)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(2): ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(2): ""null"" ""c"" ArgumentRefKinds(2): Ref None "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_ErrorBadDynamicMethodArgLambda() { string source = @" using System; class C { public void M(C c) { dynamic y = null; var x = /*<bind>*/c.M2(delegate { }, y)/*</bind>*/; } public void M2(Action a, Action y) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic, IsInvalid) (Syntax: 'c.M2(delegate { }, y)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(2): IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'delegate { }') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }') IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '{ }') ReturnedValue: null ILocalReferenceOperation: y (OperationKind.LocalReference, Type: dynamic) (Syntax: 'y') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. // var x = /*<bind>*/c.M2(delegate { }, y)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "delegate { }").WithLocation(9, 32) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_OverloadResolutionFailure() { string source = @" class C { void M(C c, dynamic d) { var x = /*<bind>*/c.M2(d)/*</bind>*/; } public void M2() { } public void M2(int i, int j) { } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'c.M2(d)') Children(2): IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c') IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic, IsInvalid) (Syntax: 'd') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS7036: There is no argument given that corresponds to the required formal parameter 'j' of 'C.M2(int, int)' // var x = /*<bind>*/c.M2(d)/*</bind>*/; Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M2").WithArguments("j", "C.M2(int, int)").WithLocation(6, 29), // CS0815: Cannot assign void to an implicitly-typed variable // var x = /*<bind>*/c.M2(d)/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "x = /*<bind>*/c.M2(d)").WithArguments("void").WithLocation(6, 13) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_InConstructorInitializer() { string source = @" class B { protected B(int x) { } } class C : B { C(dynamic x) : base((int)/*<bind>*/Goo(x)/*</bind>*/) { } static object Goo(object x) { return x; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'Goo(x)') Expression: IDynamicMemberReferenceOperation (Member Name: ""Goo"", Containing Type: C) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'Goo') Type Arguments(0) Instance Receiver: null Arguments(1): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'x') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_NoControlFlow() { string source = @" class C { void M(C c, dynamic d) /*<bind>*/{ c.M2(d); }/*</bind>*/ public void M2(int i) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c.M2(d);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowNullReceiver() { // Also tests non-zero TypeArguments and non-null ContainingType for IDynamicMemberReferenceOperation string source = @" class C { void M(dynamic d1, dynamic d2) /*<bind>*/{ C.M2<int>(d1 ?? d2); }/*</bind>*/ public static void M2<T>(int i) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'C.M2<int>(d1 ?? d2);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'C.M2<int>(d1 ?? d2)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: C) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'C.M2<int>') Type Arguments(1): Symbol: System.Int32 Instance Receiver: null Arguments(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1 ?? d2') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInReceiver() { string source = @" class C { void M(C c1, C c2, dynamic d) /*<bind>*/{ (c1 ?? c2).M2(d); }/*</bind>*/ public void M2(int i) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(c1 ?? c2).M2(d);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: '(c1 ?? c2).M2(d)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: '(c1 ?? c2).M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1 ?? c2') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInReceiverEmptyArgList() { string source = @" class C { void M(dynamic d1, dynamic d2) /*<bind>*/{ (d1 ?? d2).M2(); }/*</bind>*/ public void M2() { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(d1 ?? d2).M2();') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: '(d1 ?? d2).M2()') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: dynamic) (Syntax: '(d1 ?? d2).M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1 ?? d2') Arguments(0) ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInFirstArgument() { string source = @" class C { void M(char ch, C c, dynamic d1, dynamic d2) /*<bind>*/{ c.M2(d1 ?? d2, ch); }/*</bind>*/ public void M2(int i, char ch) { } public void M2(long i, char ch) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c.M2(d1 ?? d2, ch);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d1 ?? d2, ch)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Arguments(2): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1 ?? d2') IParameterReferenceOperation: ch (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'ch') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInSecondArgument() { string source = @" class C { void M(C c, dynamic d1, char? ch1, char ch2) /*<bind>*/{ c.M2(d1, ch1 ?? ch2); }/*</bind>*/ public void M2(int i, char ch) { } public void M2(long i, char ch) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [3] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'ch1') Value: IParameterReferenceOperation: ch1 (OperationKind.ParameterReference, Type: System.Char?) (Syntax: 'ch1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'ch1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Char?, IsImplicit) (Syntax: 'ch1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'ch1') Value: IInvocationOperation ( System.Char System.Char?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Char, IsImplicit) (Syntax: 'ch1') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Char?, IsImplicit) (Syntax: 'ch1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'ch2') Value: IParameterReferenceOperation: ch2 (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'ch2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c.M2(d1, ch1 ?? ch2);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d1, ch1 ?? ch2)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Arguments(2): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Char, IsImplicit) (Syntax: 'ch1 ?? ch2') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInMultipleArguments() { string source = @" class C { void M(bool flag, char ch1, char ch2, C c, dynamic d1, dynamic d2) /*<bind>*/{ c.M2(d1 ?? d2, flag ? ch1 : ch2); }/*</bind>*/ public void M2(int i, char ch) { } public void M2(long i, char ch) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: flag (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'flag') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'ch1') Value: IParameterReferenceOperation: ch1 (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'ch1') Next (Regular) Block[B8] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'ch2') Value: IParameterReferenceOperation: ch2 (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'ch2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c.M2(d1 ?? ... ch1 : ch2);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d1 ?? ... ch1 : ch2)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Arguments(2): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1 ?? d2') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Char, IsImplicit) (Syntax: 'flag ? ch1 : ch2') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInReceiverAndArgument() { // Control flow in receiver and argument. // Also includes use of argument names and RefKinds. string source = @" class C { void M(C c1, C c2, dynamic d1, dynamic d2, int i) /*<bind>*/{ (c1 ?? c2).M2(ref i, c: d1 ?? d2); }/*</bind>*/ public void M2(ref int i, char c) { } public void M2(ref int i, long c) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] [2] [4] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B5] Entering: {R3} .locals {R3} { CaptureIds: [3] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Leaving: {R3} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B8] Leaving: {R3} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(c1 ?? c2). ... d1 ?? d2);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: '(c1 ?? c2). ... : d1 ?? d2)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: '(c1 ?? c2).M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1 ?? c2') Arguments(2): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1 ?? d2') ArgumentNames(2): ""null"" ""c"" ArgumentRefKinds(2): Ref None Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowWithDynamicTypedMemberReceiver() { string source = @" class C { dynamic M2 = null; void M(C c, int? i1, int i2) /*<bind>*/{ c.M2(i1 ?? i2); }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c.M2') Value: IFieldReferenceOperation: dynamic C.M2 (OperationKind.FieldReference, Type: dynamic) (Syntax: 'c.M2') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2') Value: IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c.M2(i1 ?? i2);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(i1 ?? i2)') Expression: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'c.M2') Arguments(1): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i1 ?? i2') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IDynamicInvocationExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_DynamicArgument() { string source = @" class C { void M(C c, dynamic d) { /*<bind>*/c.M2(d)/*</bind>*/; } public void M2(int i) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_MultipleApplicableSymbols() { string source = @" class C { void M(C c, dynamic d) { var x = /*<bind>*/c.M2(d)/*</bind>*/; } public void M2(int i) { } public void M2(long i) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_MultipleArgumentsAndApplicableSymbols() { string source = @" class C { void M(C c, dynamic d) { char ch = 'c'; var x = /*<bind>*/c.M2(d, ch)/*</bind>*/; } public void M2(int i, char ch) { } public void M2(long i, char ch) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d, ch)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(2): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ILocalReferenceOperation: ch (OperationKind.LocalReference, Type: System.Char) (Syntax: 'ch') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_ArgumentNames() { string source = @" class C { void M(C c, dynamic d, dynamic e) { var x = /*<bind>*/c.M2(i: d, ch: e)/*</bind>*/; } public void M2(int i, char ch) { } public void M2(long i, char ch) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(i: d, ch: e)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(2): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'e') ArgumentNames(2): ""i"" ""ch"" ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_ArgumentRefKinds() { string source = @" class C { void M(C c, object d, dynamic e) { int k; var x = /*<bind>*/c.M2(ref d, out k, e)/*</bind>*/; } public void M2(ref object i, out int j, char c) { j = 0; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(ref d, out k, e)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(3): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'd') ILocalReferenceOperation: k (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'k') IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'e') ArgumentNames(0) ArgumentRefKinds(3): Ref Out None "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_DelegateInvocation() { string source = @" using System; class C { public Action<object> F; void M(dynamic i) { var x = /*<bind>*/F(i)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'F(i)') Expression: IFieldReferenceOperation: System.Action<System.Object> C.F (OperationKind.FieldReference, Type: System.Action<System.Object>) (Syntax: 'F') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'F') Arguments(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'i') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0649: Field 'C.F' is never assigned to, and will always have its default value null // public Action<object> F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("C.F", "null").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_WithDynamicReceiver() { string source = @" class C { void M(dynamic d, int i) { var x = /*<bind>*/d(i)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'd(i)') Expression: IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') Arguments(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_WithDynamicMemberReceiver() { string source = @" class C { void M(dynamic c, int i) { var x = /*<bind>*/c.M2(i)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(i)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: dynamic) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'c') Arguments(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_WithDynamicTypedMemberReceiver() { string source = @" class C { dynamic M2 = null; void M(C c, int i) { var x = /*<bind>*/c.M2(i)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(i)') Expression: IFieldReferenceOperation: dynamic C.M2 (OperationKind.FieldReference, Type: dynamic) (Syntax: 'c.M2') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_AllFields() { string source = @" class C { void M(C c, dynamic d) { int i = 0; var x = /*<bind>*/c.M2(ref i, c: d)/*</bind>*/; } public void M2(ref int i, char c) { } public void M2(ref int i, long c) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(ref i, c: d)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(2): ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(2): ""null"" ""c"" ArgumentRefKinds(2): Ref None "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_ErrorBadDynamicMethodArgLambda() { string source = @" using System; class C { public void M(C c) { dynamic y = null; var x = /*<bind>*/c.M2(delegate { }, y)/*</bind>*/; } public void M2(Action a, Action y) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic, IsInvalid) (Syntax: 'c.M2(delegate { }, y)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(2): IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'delegate { }') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }') IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '{ }') ReturnedValue: null ILocalReferenceOperation: y (OperationKind.LocalReference, Type: dynamic) (Syntax: 'y') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. // var x = /*<bind>*/c.M2(delegate { }, y)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "delegate { }").WithLocation(9, 32) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_OverloadResolutionFailure() { string source = @" class C { void M(C c, dynamic d) { var x = /*<bind>*/c.M2(d)/*</bind>*/; } public void M2() { } public void M2(int i, int j) { } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'c.M2(d)') Children(2): IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c') IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic, IsInvalid) (Syntax: 'd') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS7036: There is no argument given that corresponds to the required formal parameter 'j' of 'C.M2(int, int)' // var x = /*<bind>*/c.M2(d)/*</bind>*/; Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M2").WithArguments("j", "C.M2(int, int)").WithLocation(6, 29), // CS0815: Cannot assign void to an implicitly-typed variable // var x = /*<bind>*/c.M2(d)/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "x = /*<bind>*/c.M2(d)").WithArguments("void").WithLocation(6, 13) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_InConstructorInitializer() { string source = @" class B { protected B(int x) { } } class C : B { C(dynamic x) : base((int)/*<bind>*/Goo(x)/*</bind>*/) { } static object Goo(object x) { return x; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'Goo(x)') Expression: IDynamicMemberReferenceOperation (Member Name: ""Goo"", Containing Type: C) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'Goo') Type Arguments(0) Instance Receiver: null Arguments(1): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'x') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_NoControlFlow() { string source = @" class C { void M(C c, dynamic d) /*<bind>*/{ c.M2(d); }/*</bind>*/ public void M2(int i) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c.M2(d);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowNullReceiver() { // Also tests non-zero TypeArguments and non-null ContainingType for IDynamicMemberReferenceOperation string source = @" class C { void M(dynamic d1, dynamic d2) /*<bind>*/{ C.M2<int>(d1 ?? d2); }/*</bind>*/ public static void M2<T>(int i) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'C.M2<int>(d1 ?? d2);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'C.M2<int>(d1 ?? d2)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: C) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'C.M2<int>') Type Arguments(1): Symbol: System.Int32 Instance Receiver: null Arguments(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1 ?? d2') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInReceiver() { string source = @" class C { void M(C c1, C c2, dynamic d) /*<bind>*/{ (c1 ?? c2).M2(d); }/*</bind>*/ public void M2(int i) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(c1 ?? c2).M2(d);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: '(c1 ?? c2).M2(d)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: '(c1 ?? c2).M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1 ?? c2') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInReceiverEmptyArgList() { string source = @" class C { void M(dynamic d1, dynamic d2) /*<bind>*/{ (d1 ?? d2).M2(); }/*</bind>*/ public void M2() { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(d1 ?? d2).M2();') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: '(d1 ?? d2).M2()') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: dynamic) (Syntax: '(d1 ?? d2).M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1 ?? d2') Arguments(0) ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInFirstArgument() { string source = @" class C { void M(char ch, C c, dynamic d1, dynamic d2) /*<bind>*/{ c.M2(d1 ?? d2, ch); }/*</bind>*/ public void M2(int i, char ch) { } public void M2(long i, char ch) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c.M2(d1 ?? d2, ch);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d1 ?? d2, ch)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Arguments(2): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1 ?? d2') IParameterReferenceOperation: ch (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'ch') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInSecondArgument() { string source = @" class C { void M(C c, dynamic d1, char? ch1, char ch2) /*<bind>*/{ c.M2(d1, ch1 ?? ch2); }/*</bind>*/ public void M2(int i, char ch) { } public void M2(long i, char ch) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [3] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'ch1') Value: IParameterReferenceOperation: ch1 (OperationKind.ParameterReference, Type: System.Char?) (Syntax: 'ch1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'ch1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Char?, IsImplicit) (Syntax: 'ch1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'ch1') Value: IInvocationOperation ( System.Char System.Char?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Char, IsImplicit) (Syntax: 'ch1') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Char?, IsImplicit) (Syntax: 'ch1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'ch2') Value: IParameterReferenceOperation: ch2 (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'ch2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c.M2(d1, ch1 ?? ch2);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d1, ch1 ?? ch2)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Arguments(2): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Char, IsImplicit) (Syntax: 'ch1 ?? ch2') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInMultipleArguments() { string source = @" class C { void M(bool flag, char ch1, char ch2, C c, dynamic d1, dynamic d2) /*<bind>*/{ c.M2(d1 ?? d2, flag ? ch1 : ch2); }/*</bind>*/ public void M2(int i, char ch) { } public void M2(long i, char ch) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: flag (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'flag') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'ch1') Value: IParameterReferenceOperation: ch1 (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'ch1') Next (Regular) Block[B8] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'ch2') Value: IParameterReferenceOperation: ch2 (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'ch2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c.M2(d1 ?? ... ch1 : ch2);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d1 ?? ... ch1 : ch2)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Arguments(2): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1 ?? d2') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Char, IsImplicit) (Syntax: 'flag ? ch1 : ch2') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInReceiverAndArgument() { // Control flow in receiver and argument. // Also includes use of argument names and RefKinds. string source = @" class C { void M(C c1, C c2, dynamic d1, dynamic d2, int i) /*<bind>*/{ (c1 ?? c2).M2(ref i, c: d1 ?? d2); }/*</bind>*/ public void M2(ref int i, char c) { } public void M2(ref int i, long c) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] [2] [4] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B5] Entering: {R3} .locals {R3} { CaptureIds: [3] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Leaving: {R3} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B8] Leaving: {R3} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(c1 ?? c2). ... d1 ?? d2);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: '(c1 ?? c2). ... : d1 ?? d2)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: '(c1 ?? c2).M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1 ?? c2') Arguments(2): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1 ?? d2') ArgumentNames(2): ""null"" ""c"" ArgumentRefKinds(2): Ref None Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowWithDynamicTypedMemberReceiver() { string source = @" class C { dynamic M2 = null; void M(C c, int? i1, int i2) /*<bind>*/{ c.M2(i1 ?? i2); }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c.M2') Value: IFieldReferenceOperation: dynamic C.M2 (OperationKind.FieldReference, Type: dynamic) (Syntax: 'c.M2') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2') Value: IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c.M2(i1 ?? i2);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(i1 ?? i2)') Expression: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'c.M2') Arguments(1): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i1 ?? i2') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Options passed to <see cref="DiagnosticAnalyzer"/>. /// </summary> public class AnalyzerOptions { internal static readonly AnalyzerOptions Empty = new AnalyzerOptions(ImmutableArray<AdditionalText>.Empty); /// <summary> /// A set of additional non-code text files that can be used by analyzers. /// </summary> public ImmutableArray<AdditionalText> AdditionalFiles { get; } /// <summary> /// A set of options keyed to <see cref="SyntaxTree"/> or <see cref="AdditionalText"/>. /// </summary> public AnalyzerConfigOptionsProvider AnalyzerConfigOptionsProvider { get; } /// <summary> /// Creates analyzer options to be passed to <see cref="DiagnosticAnalyzer"/>. /// </summary> /// <param name="additionalFiles">A set of additional non-code text files that can be used by analyzers.</param> /// <param name="optionsProvider">A set of per-tree options that can be used by analyzers.</param> public AnalyzerOptions(ImmutableArray<AdditionalText> additionalFiles, AnalyzerConfigOptionsProvider optionsProvider) { if (optionsProvider is null) { throw new ArgumentNullException(nameof(optionsProvider)); } AdditionalFiles = additionalFiles.NullToEmpty(); AnalyzerConfigOptionsProvider = optionsProvider; } /// <summary> /// Creates analyzer options to be passed to <see cref="DiagnosticAnalyzer"/>. /// </summary> /// <param name="additionalFiles">A set of additional non-code text files that can be used by analyzers.</param> public AnalyzerOptions(ImmutableArray<AdditionalText> additionalFiles) : this(additionalFiles, CompilerAnalyzerConfigOptionsProvider.Empty) { } /// <summary> /// Returns analyzer options with the given <paramref name="additionalFiles"/>. /// </summary> public AnalyzerOptions WithAdditionalFiles(ImmutableArray<AdditionalText> additionalFiles) { if (this.AdditionalFiles == additionalFiles) { return this; } return new AnalyzerOptions(additionalFiles); } public override bool Equals(object? obj) { if (ReferenceEquals(this, obj)) { return true; } var other = obj as AnalyzerOptions; return other != null && (this.AdditionalFiles == other.AdditionalFiles || this.AdditionalFiles.SequenceEqual(other.AdditionalFiles, ReferenceEquals)); } public override int GetHashCode() { return Hash.CombineValues(this.AdditionalFiles); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Options passed to <see cref="DiagnosticAnalyzer"/>. /// </summary> public class AnalyzerOptions { internal static readonly AnalyzerOptions Empty = new AnalyzerOptions(ImmutableArray<AdditionalText>.Empty); /// <summary> /// A set of additional non-code text files that can be used by analyzers. /// </summary> public ImmutableArray<AdditionalText> AdditionalFiles { get; } /// <summary> /// A set of options keyed to <see cref="SyntaxTree"/> or <see cref="AdditionalText"/>. /// </summary> public AnalyzerConfigOptionsProvider AnalyzerConfigOptionsProvider { get; } /// <summary> /// Creates analyzer options to be passed to <see cref="DiagnosticAnalyzer"/>. /// </summary> /// <param name="additionalFiles">A set of additional non-code text files that can be used by analyzers.</param> /// <param name="optionsProvider">A set of per-tree options that can be used by analyzers.</param> public AnalyzerOptions(ImmutableArray<AdditionalText> additionalFiles, AnalyzerConfigOptionsProvider optionsProvider) { if (optionsProvider is null) { throw new ArgumentNullException(nameof(optionsProvider)); } AdditionalFiles = additionalFiles.NullToEmpty(); AnalyzerConfigOptionsProvider = optionsProvider; } /// <summary> /// Creates analyzer options to be passed to <see cref="DiagnosticAnalyzer"/>. /// </summary> /// <param name="additionalFiles">A set of additional non-code text files that can be used by analyzers.</param> public AnalyzerOptions(ImmutableArray<AdditionalText> additionalFiles) : this(additionalFiles, CompilerAnalyzerConfigOptionsProvider.Empty) { } /// <summary> /// Returns analyzer options with the given <paramref name="additionalFiles"/>. /// </summary> public AnalyzerOptions WithAdditionalFiles(ImmutableArray<AdditionalText> additionalFiles) { if (this.AdditionalFiles == additionalFiles) { return this; } return new AnalyzerOptions(additionalFiles); } public override bool Equals(object? obj) { if (ReferenceEquals(this, obj)) { return true; } var other = obj as AnalyzerOptions; return other != null && (this.AdditionalFiles == other.AdditionalFiles || this.AdditionalFiles.SequenceEqual(other.AdditionalFiles, ReferenceEquals)); } public override int GetHashCode() { return Hash.CombineValues(this.AdditionalFiles); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IEventReferenceOperation.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.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IEventReference_AddHandlerSharedEvent() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared Event E1 As EventHandler Shared Sub S2() AddHandler E1, Sub(sender, args)'BIND:"E1" End Sub End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IEventReferenceOperation: Event M1.C1.E1 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'E1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IEventReference_AddHandlerSharedEventWithInstanceReference() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared Event E1 As EventHandler Shared Sub S2() Dim c1Instance As New C1 AddHandler c1Instance.E1, Sub(sender, arg) Console.WriteLine()'BIND:"c1Instance.E1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IEventReferenceOperation: Event M1.C1.E1 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'c1Instance.E1') Instance Receiver: ILocalReferenceOperation: c1Instance (OperationKind.LocalReference, Type: M1.C1) (Syntax: 'c1Instance') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. AddHandler c1Instance.E1, Sub(sender, arg) Console.WriteLine()'BIND:"c1Instance.E1" ~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IEventReference_AddHandlerSharedEventAccessOnClass() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared Event E1 As EventHandler Shared Sub S2() Dim c1Instance As New C1 AddHandler C1.E1, Sub(sender, arg) Console.WriteLine()'BIND:"C1.E1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IEventReferenceOperation: Event M1.C1.E1 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'C1.E1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IEventReference_AddHandlerInstanceEventAccessOnClass() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Event E1 As EventHandler Shared Sub S2() Dim c1Instance As New C1 AddHandler C1.E1, Sub(sender, arg) Console.WriteLine()'BIND:"C1.E1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IEventReferenceOperation: Event M1.C1.E1 As System.EventHandler (OperationKind.EventReference, Type: System.EventHandler, IsInvalid) (Syntax: 'C1.E1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30469: Reference to a non-shared member requires an object reference. AddHandler C1.E1, Sub(sender, arg) Console.WriteLine()'BIND:"C1.E1" ~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub EventReference_NoControlFlow() ' Verify event references with different kinds of instance references. Dim source = <![CDATA[ Option Strict On Imports System Class C1 Public Event Event1 As EventHandler Public Shared Event Event2 As EventHandler Public Sub M1(c As C1, handler1 As EventHandler, handler2 As EventHandler, handler3 As EventHandler)'BIND:"Public Sub M1(c As C1, handler1 As EventHandler, handler2 As EventHandler, handler3 As EventHandler)" AddHandler Me.Event1, handler1 AddHandler c.Event1, handler2 AddHandler Event2, handler3 End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (3) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... 1, handler1') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... 1, handler1') Event Reference: IEventReferenceOperation: Event C1.Event1 As System.EventHandler (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'Me.Event1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C1) (Syntax: 'Me') Handler: IParameterReferenceOperation: handler1 (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... 1, handler2') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... 1, handler2') Event Reference: IEventReferenceOperation: Event C1.Event1 As System.EventHandler (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'c.Event1') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C1) (Syntax: 'c') Handler: IParameterReferenceOperation: handler2 (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler2') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... 2, handler3') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... 2, handler3') Event Reference: IEventReferenceOperation: Event C1.Event2 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'Event2') Instance Receiver: null Handler: IParameterReferenceOperation: handler3 (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler3') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub EventReference_ControlFlowInReceiver() Dim source = <![CDATA[ Option Strict On Imports System Class C1 Public Event Event1 As EventHandler Public Sub M1(c1 As C1, c2 As C1, handler As EventHandler) 'BIND:"Public Sub M1(c1 As C1, c2 As C1, handler As EventHandler)" AddHandler If(c1, c2).Event1, handler End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... t1, handler') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... t1, handler') Event Reference: IEventReferenceOperation: Event C1.Event1 As System.EventHandler (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'If(c1, c2).Event1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'If(c1, c2)') Handler: IParameterReferenceOperation: handler (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub EventReference_ControlFlowInReceiver_StaticEvent() Dim source = <![CDATA[ Option Strict On Imports System Class C1 Public Shared Event Event1 As EventHandler Public Sub M1(c As C1, c2 As C1, handler1 As EventHandler, handler2 As EventHandler) 'BIND:"Public Sub M1(c As C1, c2 As C1, handler1 As EventHandler, handler2 As EventHandler)" AddHandler c.Event1, handler1 AddHandler If(c, c2).Event1, handler2 End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... 1, handler1') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... 1, handler1') Event Reference: IEventReferenceOperation: Event C1.Event1 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'c.Event1') Instance Receiver: null Handler: IParameterReferenceOperation: handler1 (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... 1, handler2') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... 1, handler2') Event Reference: IEventReferenceOperation: Event C1.Event1 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'If(c, c2).Event1') Instance Receiver: null Handler: IParameterReferenceOperation: handler2 (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler2') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. AddHandler c.Event1, handler1 ~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. AddHandler If(c, c2).Event1, handler2 ~~~~~~~~~~~~~~~~ ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IEventReference_AddHandlerSharedEvent() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared Event E1 As EventHandler Shared Sub S2() AddHandler E1, Sub(sender, args)'BIND:"E1" End Sub End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IEventReferenceOperation: Event M1.C1.E1 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'E1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IEventReference_AddHandlerSharedEventWithInstanceReference() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared Event E1 As EventHandler Shared Sub S2() Dim c1Instance As New C1 AddHandler c1Instance.E1, Sub(sender, arg) Console.WriteLine()'BIND:"c1Instance.E1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IEventReferenceOperation: Event M1.C1.E1 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'c1Instance.E1') Instance Receiver: ILocalReferenceOperation: c1Instance (OperationKind.LocalReference, Type: M1.C1) (Syntax: 'c1Instance') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. AddHandler c1Instance.E1, Sub(sender, arg) Console.WriteLine()'BIND:"c1Instance.E1" ~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IEventReference_AddHandlerSharedEventAccessOnClass() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared Event E1 As EventHandler Shared Sub S2() Dim c1Instance As New C1 AddHandler C1.E1, Sub(sender, arg) Console.WriteLine()'BIND:"C1.E1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IEventReferenceOperation: Event M1.C1.E1 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'C1.E1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IEventReference_AddHandlerInstanceEventAccessOnClass() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Event E1 As EventHandler Shared Sub S2() Dim c1Instance As New C1 AddHandler C1.E1, Sub(sender, arg) Console.WriteLine()'BIND:"C1.E1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IEventReferenceOperation: Event M1.C1.E1 As System.EventHandler (OperationKind.EventReference, Type: System.EventHandler, IsInvalid) (Syntax: 'C1.E1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30469: Reference to a non-shared member requires an object reference. AddHandler C1.E1, Sub(sender, arg) Console.WriteLine()'BIND:"C1.E1" ~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub EventReference_NoControlFlow() ' Verify event references with different kinds of instance references. Dim source = <![CDATA[ Option Strict On Imports System Class C1 Public Event Event1 As EventHandler Public Shared Event Event2 As EventHandler Public Sub M1(c As C1, handler1 As EventHandler, handler2 As EventHandler, handler3 As EventHandler)'BIND:"Public Sub M1(c As C1, handler1 As EventHandler, handler2 As EventHandler, handler3 As EventHandler)" AddHandler Me.Event1, handler1 AddHandler c.Event1, handler2 AddHandler Event2, handler3 End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (3) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... 1, handler1') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... 1, handler1') Event Reference: IEventReferenceOperation: Event C1.Event1 As System.EventHandler (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'Me.Event1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C1) (Syntax: 'Me') Handler: IParameterReferenceOperation: handler1 (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... 1, handler2') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... 1, handler2') Event Reference: IEventReferenceOperation: Event C1.Event1 As System.EventHandler (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'c.Event1') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C1) (Syntax: 'c') Handler: IParameterReferenceOperation: handler2 (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler2') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... 2, handler3') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... 2, handler3') Event Reference: IEventReferenceOperation: Event C1.Event2 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'Event2') Instance Receiver: null Handler: IParameterReferenceOperation: handler3 (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler3') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub EventReference_ControlFlowInReceiver() Dim source = <![CDATA[ Option Strict On Imports System Class C1 Public Event Event1 As EventHandler Public Sub M1(c1 As C1, c2 As C1, handler As EventHandler) 'BIND:"Public Sub M1(c1 As C1, c2 As C1, handler As EventHandler)" AddHandler If(c1, c2).Event1, handler End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... t1, handler') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... t1, handler') Event Reference: IEventReferenceOperation: Event C1.Event1 As System.EventHandler (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'If(c1, c2).Event1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'If(c1, c2)') Handler: IParameterReferenceOperation: handler (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub EventReference_ControlFlowInReceiver_StaticEvent() Dim source = <![CDATA[ Option Strict On Imports System Class C1 Public Shared Event Event1 As EventHandler Public Sub M1(c As C1, c2 As C1, handler1 As EventHandler, handler2 As EventHandler) 'BIND:"Public Sub M1(c As C1, c2 As C1, handler1 As EventHandler, handler2 As EventHandler)" AddHandler c.Event1, handler1 AddHandler If(c, c2).Event1, handler2 End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... 1, handler1') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... 1, handler1') Event Reference: IEventReferenceOperation: Event C1.Event1 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'c.Event1') Instance Receiver: null Handler: IParameterReferenceOperation: handler1 (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'AddHandler ... 1, handler2') Expression: IEventAssignmentOperation (EventAdd) (OperationKind.EventAssignment, Type: null, IsImplicit) (Syntax: 'AddHandler ... 1, handler2') Event Reference: IEventReferenceOperation: Event C1.Event1 As System.EventHandler (Static) (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'If(c, c2).Event1') Instance Receiver: null Handler: IParameterReferenceOperation: handler2 (OperationKind.ParameterReference, Type: System.EventHandler) (Syntax: 'handler2') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. AddHandler c.Event1, handler1 ~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. AddHandler If(c, c2).Event1, handler2 ~~~~~~~~~~~~~~~~ ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub End Class End Namespace
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/EditorFeatures/Core/Implementation/RenameTracking/RenameTrackingCancellationCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking { [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [Name(PredefinedCommandHandlerNames.RenameTrackingCancellation)] [Order(After = PredefinedCommandHandlerNames.SignatureHelpBeforeCompletion)] [Order(After = PredefinedCommandHandlerNames.SignatureHelpAfterCompletion)] [Order(After = PredefinedCommandHandlerNames.AutomaticCompletion)] [Order(After = PredefinedCompletionNames.CompletionCommandHandler)] [Order(After = PredefinedCommandHandlerNames.QuickInfo)] [Order(After = PredefinedCommandHandlerNames.EventHookup)] internal class RenameTrackingCancellationCommandHandler : ICommandHandler<EscapeKeyCommandArgs> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public RenameTrackingCancellationCommandHandler() { } public string DisplayName => EditorFeaturesResources.Rename_Tracking_Cancellation; public bool ExecuteCommand(EscapeKeyCommandArgs args, CommandExecutionContext context) { var document = args.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); return document != null && RenameTrackingDismisser.DismissVisibleRenameTracking(document.Project.Solution.Workspace, document.Id); } public CommandState GetCommandState(EscapeKeyCommandArgs args) => CommandState.Unspecified; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking { [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [Name(PredefinedCommandHandlerNames.RenameTrackingCancellation)] [Order(After = PredefinedCommandHandlerNames.SignatureHelpBeforeCompletion)] [Order(After = PredefinedCommandHandlerNames.SignatureHelpAfterCompletion)] [Order(After = PredefinedCommandHandlerNames.AutomaticCompletion)] [Order(After = PredefinedCompletionNames.CompletionCommandHandler)] [Order(After = PredefinedCommandHandlerNames.QuickInfo)] [Order(After = PredefinedCommandHandlerNames.EventHookup)] internal class RenameTrackingCancellationCommandHandler : ICommandHandler<EscapeKeyCommandArgs> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public RenameTrackingCancellationCommandHandler() { } public string DisplayName => EditorFeaturesResources.Rename_Tracking_Cancellation; public bool ExecuteCommand(EscapeKeyCommandArgs args, CommandExecutionContext context) { var document = args.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); return document != null && RenameTrackingDismisser.DismissVisibleRenameTracking(document.Project.Solution.Workspace, document.Id); } public CommandState GetCommandState(EscapeKeyCommandArgs args) => CommandState.Unspecified; } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/VisualStudioDiagnosticsWindow.vsct
<?xml version="1.0" encoding="utf-8"?> <CommandTable xmlns="http://schemas.microsoft.com/VisualStudio/2005-10-18/CommandTable" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <!-- This is the file that defines the actual layout and type of the commands. It is divided in different sections (e.g. command definition, command placement, ...), with each defining a specific set of properties. See the comment before each section for more details about how to use it. --> <!-- The VSCT compiler (the tool that translates this file into the binary format that VisualStudio will consume) has the ability to run a preprocessor on the vsct file; this preprocessor is (usually) the C++ preprocessor, so it is possible to define includes and macros with the same syntax used in C++ files. Using this ability of the compiler here, we include some files defining some of the constants that we will use inside the file. --> <!--This is the file that defines the IDs for all the commands exposed by VisualStudio. --> <Extern href="stdidcmd.h"/> <!--This header contains the command ids for the menus provided by the shell. --> <Extern href="vsshlids.h"/> <!--The Commands section is where we the commands, menus and menu groups are defined. This section uses a Guid to identify the package that provides the command defined inside it. --> <Commands package="guidVisualStudioDiagnosticsWindowPkg"> <!-- Inside this section we have different sub-sections: one for the menus, another for the menu groups, one for the buttons (the actual commands), one for the combos and the last one for the bitmaps used. Each element is identified by a command id that is a unique pair of guid and numeric identifier; the guid part of the identifier is usually called "command set" and is used to group different command inside a logically related group; your package should define its own command set in order to avoid collisions with command ids defined by other packages. --> <!-- In this section you can define new menu groups. A menu group is a container for other menus or buttons (commands); from a visual point of view you can see the group as the part of a menu contained between two lines. The parent of a group must be a menu. --> <Groups> </Groups> <!--Buttons section. --> <!--This section defines the elements the user can interact with, like a menu command or a button or combo box in a toolbar. --> <Buttons> <!--To define a menu group you have to specify its ID, the parent menu and its display priority. The command is visible and enabled by default. If you need to change the visibility, status, etc, you can use the CommandFlag node. You can add more than one CommandFlag node e.g.: <CommandFlag>DefaultInvisible</CommandFlag> <CommandFlag>DynamicVisibility</CommandFlag> If you do not want an image next to your command, remove the Icon node /> --> <Button guid="guidVisualStudioDiagnosticsWindowCmdSet" id="cmdIDRoslynDiagnosticWindow" priority="0x0100" type="Button"> <Parent guid="guidSHLMainMenu" id="IDG_VS_WNDO_OTRWNDWS1"/> <Icon guid="guidImages" id="bmpPic2" /> <Strings> <CommandName>cmdIDRoslynDiagnosticWindow</CommandName> <ButtonText>Roslyn Diagnostics</ButtonText> </Strings> </Button> </Buttons> <!--The bitmaps section is used to define the bitmaps that are used for the commands.--> <Bitmaps> <!-- The bitmap id is defined in a way that is a little bit different from the others: the declaration starts with a guid for the bitmap strip, then there is the resource id of the bitmap strip containing the bitmaps and then there are the numeric ids of the elements used inside a button definition. An important aspect of this declaration is that the element id must be the actual index (1-based) of the bitmap inside the bitmap strip. --> <Bitmap guid="guidImages" href="Resources\Images.png" usedList="bmpPic1, bmpPic2, bmpPicSearch, bmpPicX, bmpPicArrows"/> </Bitmaps> </Commands> <Symbols> <!-- This is the package guid. --> <GuidSymbol name="guidVisualStudioDiagnosticsWindowPkg" value="{49e24138-9ee3-49e0-8ede-6b39f49303bf}" /> <!-- This is the guid used to group the menu commands together --> <GuidSymbol name="guidVisualStudioDiagnosticsWindowCmdSet" value="{f22c2499-790a-4b6c-b0fd-b6f0491e1c9c}"> <IDSymbol name="cmdIDRoslynDiagnosticWindow" value="0x0101" /> </GuidSymbol> <GuidSymbol name="guidImages" value="{75897d86-48c4-40ca-85b5-cfdbedd011b8}" > <IDSymbol name="bmpPic1" value="1" /> <IDSymbol name="bmpPic2" value="2" /> <IDSymbol name="bmpPicSearch" value="3" /> <IDSymbol name="bmpPicX" value="4" /> <IDSymbol name="bmpPicArrows" value="5" /> <IDSymbol name="bmpPicStrikethrough" value="6" /> </GuidSymbol> </Symbols> </CommandTable>
<?xml version="1.0" encoding="utf-8"?> <CommandTable xmlns="http://schemas.microsoft.com/VisualStudio/2005-10-18/CommandTable" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <!-- This is the file that defines the actual layout and type of the commands. It is divided in different sections (e.g. command definition, command placement, ...), with each defining a specific set of properties. See the comment before each section for more details about how to use it. --> <!-- The VSCT compiler (the tool that translates this file into the binary format that VisualStudio will consume) has the ability to run a preprocessor on the vsct file; this preprocessor is (usually) the C++ preprocessor, so it is possible to define includes and macros with the same syntax used in C++ files. Using this ability of the compiler here, we include some files defining some of the constants that we will use inside the file. --> <!--This is the file that defines the IDs for all the commands exposed by VisualStudio. --> <Extern href="stdidcmd.h"/> <!--This header contains the command ids for the menus provided by the shell. --> <Extern href="vsshlids.h"/> <!--The Commands section is where we the commands, menus and menu groups are defined. This section uses a Guid to identify the package that provides the command defined inside it. --> <Commands package="guidVisualStudioDiagnosticsWindowPkg"> <!-- Inside this section we have different sub-sections: one for the menus, another for the menu groups, one for the buttons (the actual commands), one for the combos and the last one for the bitmaps used. Each element is identified by a command id that is a unique pair of guid and numeric identifier; the guid part of the identifier is usually called "command set" and is used to group different command inside a logically related group; your package should define its own command set in order to avoid collisions with command ids defined by other packages. --> <!-- In this section you can define new menu groups. A menu group is a container for other menus or buttons (commands); from a visual point of view you can see the group as the part of a menu contained between two lines. The parent of a group must be a menu. --> <Groups> </Groups> <!--Buttons section. --> <!--This section defines the elements the user can interact with, like a menu command or a button or combo box in a toolbar. --> <Buttons> <!--To define a menu group you have to specify its ID, the parent menu and its display priority. The command is visible and enabled by default. If you need to change the visibility, status, etc, you can use the CommandFlag node. You can add more than one CommandFlag node e.g.: <CommandFlag>DefaultInvisible</CommandFlag> <CommandFlag>DynamicVisibility</CommandFlag> If you do not want an image next to your command, remove the Icon node /> --> <Button guid="guidVisualStudioDiagnosticsWindowCmdSet" id="cmdIDRoslynDiagnosticWindow" priority="0x0100" type="Button"> <Parent guid="guidSHLMainMenu" id="IDG_VS_WNDO_OTRWNDWS1"/> <Icon guid="guidImages" id="bmpPic2" /> <Strings> <CommandName>cmdIDRoslynDiagnosticWindow</CommandName> <ButtonText>Roslyn Diagnostics</ButtonText> </Strings> </Button> </Buttons> <!--The bitmaps section is used to define the bitmaps that are used for the commands.--> <Bitmaps> <!-- The bitmap id is defined in a way that is a little bit different from the others: the declaration starts with a guid for the bitmap strip, then there is the resource id of the bitmap strip containing the bitmaps and then there are the numeric ids of the elements used inside a button definition. An important aspect of this declaration is that the element id must be the actual index (1-based) of the bitmap inside the bitmap strip. --> <Bitmap guid="guidImages" href="Resources\Images.png" usedList="bmpPic1, bmpPic2, bmpPicSearch, bmpPicX, bmpPicArrows"/> </Bitmaps> </Commands> <Symbols> <!-- This is the package guid. --> <GuidSymbol name="guidVisualStudioDiagnosticsWindowPkg" value="{49e24138-9ee3-49e0-8ede-6b39f49303bf}" /> <!-- This is the guid used to group the menu commands together --> <GuidSymbol name="guidVisualStudioDiagnosticsWindowCmdSet" value="{f22c2499-790a-4b6c-b0fd-b6f0491e1c9c}"> <IDSymbol name="cmdIDRoslynDiagnosticWindow" value="0x0101" /> </GuidSymbol> <GuidSymbol name="guidImages" value="{75897d86-48c4-40ca-85b5-cfdbedd011b8}" > <IDSymbol name="bmpPic1" value="1" /> <IDSymbol name="bmpPic2" value="2" /> <IDSymbol name="bmpPicSearch" value="3" /> <IDSymbol name="bmpPicX" value="4" /> <IDSymbol name="bmpPicArrows" value="5" /> <IDSymbol name="bmpPicStrikethrough" value="6" /> </GuidSymbol> </Symbols> </CommandTable>
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SymbolDisplayFormats.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class SymbolDisplayFormats { /// <summary> /// Standard format for displaying to the user. /// </summary> /// <remarks> /// No return type. /// </remarks> public static readonly SymbolDisplayFormat NameFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); /// <summary> /// Contains enough information to determine whether two symbols have the same signature. /// </summary> public static readonly SymbolDisplayFormat SignatureFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeType, kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class SymbolDisplayFormats { /// <summary> /// Standard format for displaying to the user. /// </summary> /// <remarks> /// No return type. /// </remarks> public static readonly SymbolDisplayFormat NameFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); /// <summary> /// Contains enough information to determine whether two symbols have the same signature. /// </summary> public static readonly SymbolDisplayFormat SignatureFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeType, kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType); } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/VisualBasic/Test/Syntax/Scanner/ScannerTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports System.Threading.Thread Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities <CLSCompliant(False)> Public Class ScannerTests Inherits BasicTestBase Private Function ScanOnce(str As String, Optional startStatement As Boolean = False) As SyntaxToken Return SyntaxFactory.ParseToken(str, startStatement:=startStatement) End Function Private Function ScanOnce(str As String, languageVersion As VisualBasic.LanguageVersion) As SyntaxToken Return SyntaxFactory.ParseTokens(str, options:=New VisualBasicParseOptions(languageVersion:=languageVersion)).First() End Function Private Function AsString(tokens As IEnumerable(Of SyntaxToken)) As String Dim str = String.Concat(From t In tokens Select t.ToFullString()) Return str End Function Private Function MakeDwString(str As String) As String Return (From c In str Select If(c < ChrW(&H21S) OrElse c > ChrW(&H7ES), c, ChrW(AscW(c) + &HFF00US - &H20US))).ToArray End Function Private Function ScanAllCheckDw(str As String) As IEnumerable(Of SyntaxToken) Dim tokens = SyntaxFactory.ParseTokens(str) ' test that token have the same text as it was. Assert.Equal(str, AsString(tokens)) ' test that we get same with doublewidth string Dim doubleWidthStr = MakeDwString(str) Dim doubleWidthTokens = ScanAllNoDwCheck(doubleWidthStr) Assert.Equal(tokens.Count, doubleWidthTokens.Count) For Each t In tokens.Zip(doubleWidthTokens, Function(t1, t2) Tuple.Create(t1, t2)) Assert.Equal(t.Item1.Kind, t.Item2.Kind) Assert.Equal(t.Item1.Span, t.Item2.Span) Assert.Equal(t.Item1.FullSpan, t.Item2.FullSpan) Assert.Equal(MakeDwString(t.Item1.ToFullString()), t.Item2.ToFullString()) Next Return tokens End Function Private Function ScanAllNoDwCheck(str As String) As IEnumerable(Of SyntaxToken) Dim tokens = SyntaxFactory.ParseTokens(str) ' test that token have the same text as it was. Assert.Equal(str, AsString(tokens)) Return tokens End Function <Fact> Public Sub TestLessThanConflictMarker1() ' Needs to be followed by a space. Dim token = SyntaxFactory.ParseTokens("<<<<<<<").First() Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind()) ' Has to be the start of a line. token = SyntaxFactory.ParseTokens(" <<<<<<<").First() Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia) ' Has to have at least seven characters. token = SyntaxFactory.ParseTokens("<<<<<< ").First() Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind()) ' Start of line, seven characters, ends with space. token = SyntaxFactory.ParseTokens("<<<<<<< ").First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Dim trivia = token.LeadingTrivia.Single() Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.True(trivia.ContainsDiagnostics) Dim err = trivia.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) End Sub <Fact> Public Sub TestLessThanConflictMarker2() Dim token = SyntaxFactory.ParseTokens("{" & vbCrLf & "<<<<<<<").Skip(2).First() Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind()) token = SyntaxFactory.ParseTokens("{" & vbCrLf & " <<<<<<<").Skip(2).First() Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia) token = SyntaxFactory.ParseTokens("{" & vbCrLf & "<<<<<< ").Skip(2).First() Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind()) token = SyntaxFactory.ParseTokens("{" & vbCrLf & "<<<<<<< ").Skip(2).First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Dim trivia = token.LeadingTrivia.Single() Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.True(trivia.SpanStart = 3) Assert.True(trivia.Span.Length = 8) Assert.True(trivia.ContainsDiagnostics) Dim err = trivia.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) End Sub <Fact> Public Sub TestGreaterThanConflictMarker1() ' Needs to be followed by a space. Dim token = SyntaxFactory.ParseTokens(">>>>>>>").First() Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind()) ' Has to be the start of a line. token = SyntaxFactory.ParseTokens(" >>>>>>>").First() Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia) ' Has to have at least seven characters. token = SyntaxFactory.ParseTokens(">>>>>> ").First() Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind()) ' Start of line, seven characters, ends with space. token = SyntaxFactory.ParseTokens(">>>>>>> ").First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Dim trivia = token.LeadingTrivia.Single() Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.True(trivia.ContainsDiagnostics) Dim err = trivia.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) End Sub <Fact> Public Sub TestGreaterThanConflictMarker2() Dim token = SyntaxFactory.ParseTokens("{" & vbCrLf & ">>>>>>>").Skip(2).First() Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind()) token = SyntaxFactory.ParseTokens("{" & vbCrLf & " >>>>>>>").Skip(2).First() Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia) token = SyntaxFactory.ParseTokens("{" & vbCrLf & ">>>>>> ").Skip(2).First() Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind()) token = SyntaxFactory.ParseTokens("{" & vbCrLf & ">>>>>>> ").Skip(2).First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Dim trivia = token.LeadingTrivia.Single() Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.True(trivia.SpanStart = 3) Assert.True(trivia.Span.Length = 8) Assert.True(trivia.ContainsDiagnostics) Dim err = trivia.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) End Sub <Fact> Public Sub TestEqualsConflictMarker1() ' Has to be the start of a line. Dim token = SyntaxFactory.ParseTokens(" =======").First() Assert.Equal(SyntaxKind.EqualsToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia) ' Has to have at least seven characters. token = SyntaxFactory.ParseTokens("====== ").First() Assert.Equal(SyntaxKind.EqualsToken, token.Kind()) ' Start of line, seven characters token = SyntaxFactory.ParseTokens("=======").First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.ConflictMarkerTrivia) ' Start of line, seven characters token = SyntaxFactory.ParseTokens("======= trailing chars").First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Dim trivia = token.LeadingTrivia.Single() Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.Equal(trivia.Span.Length, 22) Assert.True(trivia.ContainsDiagnostics) Dim err = trivia.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) token = SyntaxFactory.ParseTokens("======= Trailing" & vbCrLf & "disabled text").First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.Equal(3, token.LeadingTrivia.Count) trivia = token.LeadingTrivia(0) Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.Equal(trivia.Span.Length, 16) Assert.True(trivia.ContainsDiagnostics) err = trivia.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) trivia = token.LeadingTrivia(1) Assert.True(trivia.Kind() = SyntaxKind.EndOfLineTrivia) Assert.Equal(trivia.Span.Start, 16) Assert.Equal(trivia.Span.Length, 2) trivia = token.LeadingTrivia(2) Assert.True(trivia.Kind() = SyntaxKind.DisabledTextTrivia) Assert.Equal(trivia.Span.Start, 18) Assert.Equal(trivia.Span.Length, 13) token = SyntaxFactory.ParseTokens("======= Trailing" & vbCrLf & "disabled text" & vbCrLf & ">>>> still disabled").First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.Equal(3, token.LeadingTrivia.Count) trivia = token.LeadingTrivia(0) Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.Equal(trivia.Span.Length, 16) Assert.True(trivia.ContainsDiagnostics) err = trivia.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) trivia = token.LeadingTrivia(1) Assert.True(trivia.Kind() = SyntaxKind.EndOfLineTrivia) Assert.Equal(trivia.Span.Length, 2) trivia = token.LeadingTrivia(2) Assert.True(trivia.Kind() = SyntaxKind.DisabledTextTrivia) Assert.Equal(trivia.Span.Length, 34) token = SyntaxFactory.ParseTokens("======= Trailing" & vbCrLf & "disabled text" & vbCrLf & ">>>>>>> Actually the end").First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.Equal(token.LeadingTrivia.Count, 4) Dim trivia1 = token.LeadingTrivia(0) Assert.True(trivia1.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.Equal(trivia1.Span.Length, 16) Assert.True(trivia1.ContainsDiagnostics) err = trivia1.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) Dim trivia2 = token.LeadingTrivia(1) Assert.True(trivia2.Kind() = SyntaxKind.EndOfLineTrivia) Assert.Equal(trivia2.Span.Start, 16) Assert.Equal(trivia2.Span.Length, 2) Dim trivia3 = token.LeadingTrivia(2) Assert.True(trivia3.Kind() = SyntaxKind.DisabledTextTrivia) Assert.Equal(trivia3.Span.Start, 18) Assert.Equal(trivia3.Span.Length, 15) Dim trivia4 = token.LeadingTrivia(3) Assert.True(trivia4.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.Equal(trivia4.Span.Start, 33) Assert.Equal(trivia4.Span.Length, 24) Assert.True(trivia4.ContainsDiagnostics) err = trivia4.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) End Sub <Fact> Public Sub TestEqualsConflictMarker2() ' Has to be the start of a line. Dim token = SyntaxFactory.ParseTokens("{" & vbCrLf & " =======").Skip(2).First() Assert.Equal(SyntaxKind.EqualsToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia) ' Has to have at least seven characters. token = SyntaxFactory.ParseTokens("{" & vbCrLf & "====== ").Skip(2).First() Assert.Equal(SyntaxKind.EqualsToken, token.Kind()) ' Start of line, seven characters token = SyntaxFactory.ParseTokens("{" & vbCrLf & "=======").Skip(2).First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Dim trivia = token.LeadingTrivia.Single() Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.True(trivia.ContainsDiagnostics) Dim err = trivia.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) ' Start of line, seven characters token = SyntaxFactory.ParseTokens("{" & vbCrLf & "======= trailing chars").Skip(2).First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) trivia = token.LeadingTrivia.Single() Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.Equal(trivia.Span.Length, 22) Assert.True(trivia.ContainsDiagnostics) err = trivia.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) token = SyntaxFactory.ParseTokens("{" & vbCrLf & "======= Trailing" & vbCrLf & "disabled text").Skip(2).First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.Equal(3, token.LeadingTrivia.Count) trivia = token.LeadingTrivia(0) Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.Equal(trivia.Span.Length, 16) Assert.True(trivia.ContainsDiagnostics) err = trivia.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) trivia = token.LeadingTrivia(1) Assert.True(trivia.Kind() = SyntaxKind.EndOfLineTrivia) Assert.Equal(trivia.Span.Start, 19) Assert.Equal(trivia.Span.Length, 2) trivia = token.LeadingTrivia(2) Assert.True(trivia.Kind() = SyntaxKind.DisabledTextTrivia) Assert.Equal(trivia.Span.Start, 21) Assert.Equal(trivia.Span.Length, 13) token = SyntaxFactory.ParseTokens("{" & vbCrLf & "======= Trailing" & vbCrLf & "disabled text" & vbCrLf & ">>>> still disabled").Skip(2).First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.Equal(3, token.LeadingTrivia.Count) trivia = token.LeadingTrivia(0) Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.Equal(trivia.Span.Length, 16) Assert.True(trivia.ContainsDiagnostics) err = trivia.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) trivia = token.LeadingTrivia(1) Assert.True(trivia.Kind() = SyntaxKind.EndOfLineTrivia) Assert.Equal(trivia.Span.Length, 2) trivia = token.LeadingTrivia(2) Assert.True(trivia.Kind() = SyntaxKind.DisabledTextTrivia) Assert.Equal(trivia.Span.Length, 34) token = SyntaxFactory.ParseTokens("{" & vbCrLf & "======= Trailing" & vbCrLf & "disabled text" & vbCrLf & ">>>>>>> Actually the end").Skip(2).First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.Equal(token.LeadingTrivia.Count, 4) Dim trivia1 = token.LeadingTrivia(0) Assert.True(trivia1.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.Equal(trivia1.Span.Length, 16) Assert.True(trivia1.ContainsDiagnostics) err = trivia1.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) Dim trivia2 = token.LeadingTrivia(1) Assert.True(trivia2.Kind() = SyntaxKind.EndOfLineTrivia) Assert.Equal(trivia2.Span.Start, 19) Assert.Equal(trivia2.Span.Length, 2) Dim trivia3 = token.LeadingTrivia(2) Assert.True(trivia3.Kind() = SyntaxKind.DisabledTextTrivia) Assert.Equal(trivia3.Span.Start, 21) Assert.Equal(trivia3.Span.Length, 15) Dim trivia4 = token.LeadingTrivia(3) Assert.True(trivia4.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.Equal(trivia4.Span.Start, 36) Assert.Equal(trivia4.Span.Length, 24) Assert.True(trivia4.ContainsDiagnostics) err = trivia4.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) End Sub <Fact> Public Sub Scanner_EndOfText() Dim tk = ScanOnce("") Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal("", tk.ToFullString()) tk = ScanOnce(" ") Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(" ", tk.ToFullString()) tk = ScanOnce(" ") Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(" ", tk.ToFullString()) tk = ScanOnce("'") Assert.Equal(SyntaxKind.EmptyToken, tk.Kind) Assert.Equal(SyntaxKind.CommentTrivia, tk.TrailingTrivia(0).Kind) Assert.Equal("'", tk.ToFullString()) tk = ScanOnce("'", startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(0).Kind) Assert.Equal("'", tk.ToFullString()) tk = ScanOnce(" ' ") Assert.Equal(SyntaxKind.EmptyToken, tk.Kind) Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind) Assert.Equal(SyntaxKind.CommentTrivia, tk.TrailingTrivia(0).Kind) Assert.Equal(" ", tk.LeadingTrivia(0).ToString()) Assert.Equal("' ", tk.TrailingTrivia(0).ToString()) Assert.Equal(" ' ", tk.ToFullString()) tk = ScanOnce(" ' ", startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind) Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(1).Kind) Assert.Equal(" ", tk.LeadingTrivia(0).ToString()) Assert.Equal("' ", tk.LeadingTrivia(1).ToString()) Assert.Equal(" ' ", tk.ToFullString()) End Sub <Fact> Public Sub Scanner_StatementTerminator() Dim tk = ScanOnce(vbCr) Assert.Equal(SyntaxKind.EmptyToken, tk.Kind) Assert.Equal(vbCr, tk.ToFullString()) tk = ScanOnce(vbCr, startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(vbCr, tk.ToFullString()) Dim tks = ScanAllCheckDw(vbCr) Assert.Equal(1, tks.Count) Assert.Equal(SyntaxKind.EndOfFileToken, tks(0).Kind) Assert.Equal(vbCr, tks(0).ToFullString()) tks = ScanAllCheckDw(" " & vbLf) Assert.Equal(1, tks.Count) Assert.Equal(SyntaxKind.EndOfFileToken, tks(0).Kind) Assert.Equal(" " & vbLf, tks(0).ToFullString()) tks = ScanAllCheckDw(" A" & vbCrLf & " ") Assert.Equal(3, tks.Count) Assert.Equal(SyntaxKind.IdentifierToken, tks(0).Kind) Assert.Equal(" A" & vbCrLf, tks(0).ToFullString()) Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(1).Kind) Assert.Equal("", tks(1).ToFullString()) Assert.Equal(SyntaxKind.EndOfFileToken, tks(2).Kind) Assert.Equal(" ", tks(2).ToFullString()) End Sub <Fact> Public Sub Scanner_StartStatement() Dim tk = ScanOnce(vbCr, startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(vbCr, tk.ToFullString()) tk = ScanOnce(" " & vbLf, startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(" " & vbLf, tk.ToFullString()) Dim str = " " & vbCrLf & " " & vbCr & "'2 " & vbLf & " (" tk = ScanOnce(str, startStatement:=True) Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind) Assert.Equal(str, tk.ToFullString()) str = "'(" tk = ScanOnce(str, startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(str, tk.ToFullString()) str = "'" & vbCrLf & "(" tk = ScanOnce(str, startStatement:=False) Assert.Equal(SyntaxKind.EmptyToken, tk.Kind) Assert.Equal("'" & vbCrLf, tk.ToFullString()) str = "'" & vbCrLf & "(" tk = ScanOnce(str, startStatement:=True) Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind) Assert.Equal(str, tk.ToFullString()) str = "' " & vbCrLf & " '(" & vbCrLf & "(" tk = ScanOnce(str, startStatement:=True) Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind) Assert.Equal(str, tk.ToFullString()) End Sub <Fact> Public Sub Scanner_LineContWhenExpectingNewStatement() Dim tk = ScanOnce("_", startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal("_", tk.ToFullString()) tk = ScanOnce(" _", startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(" _", tk.ToFullString()) tk = ScanOnce(" _ ", startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(" _ ", tk.ToFullString()) tk = ScanOnce(" _'", startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(" _'", tk.ToFullString()) Assert.Equal(3, tk.LeadingTrivia.Count) Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind) Assert.Equal(SyntaxKind.LineContinuationTrivia, tk.LeadingTrivia(1).Kind) Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(2).Kind) Assert.Equal(0, tk.Errors.Count) tk = ScanOnce(" _'", LanguageVersion.VisualBasic16) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(" _'", tk.ToFullString()) Assert.Equal(3, tk.LeadingTrivia.Count) Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind) Assert.Equal(SyntaxKind.LineContinuationTrivia, tk.LeadingTrivia(1).Kind) Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(2).Kind) Assert.Equal(0, tk.Errors.Count) tk = ScanOnce(" _' Comment", LanguageVersion.VisualBasic15_3) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(" _' Comment", tk.ToFullString()) Assert.Equal(3, tk.LeadingTrivia.Count) Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind) Assert.False(tk.LeadingTrivia(0).ContainsDiagnostics) Assert.Equal(SyntaxKind.LineContinuationTrivia, tk.LeadingTrivia(1).Kind) Assert.False(tk.LeadingTrivia(1).ContainsDiagnostics) Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(2).Kind) Assert.True(tk.LeadingTrivia(2).ContainsDiagnostics) Assert.Equal(1, tk.Errors.Count) Assert.Equal(ERRID.ERR_CommentsAfterLineContinuationNotAvailable1, tk.Errors.First().Code) tk = ScanOnce(" _' Comment", LanguageVersion.VisualBasic16) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(" _' Comment", tk.ToFullString()) Assert.Equal(3, tk.LeadingTrivia.Count) Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind) Assert.Equal(SyntaxKind.LineContinuationTrivia, tk.LeadingTrivia(1).Kind) Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(2).Kind) Assert.Equal(0, tk.Errors.Count) tk = ScanOnce(" _ ' Comment" & vbCrLf, LanguageVersion.VisualBasic16) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(" _ ' Comment" & vbCrLf, tk.ToFullString()) Assert.Equal(5, tk.LeadingTrivia.Count) Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind) Assert.Equal(SyntaxKind.LineContinuationTrivia, tk.LeadingTrivia(1).Kind) Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(2).Kind) Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(3).Kind) Assert.Equal(SyntaxKind.EndOfLineTrivia, tk.LeadingTrivia(4).Kind) Assert.Equal(0, tk.Errors.Count) tk = ScanOnce(" _ rem", startStatement:=True) Assert.Equal(SyntaxKind.BadToken, tk.Kind) Assert.Equal(" _ rem", tk.ToFullString()) Assert.Equal(30999, tk.Errors.First().Code) tk = ScanOnce(" _ abc", startStatement:=True) Assert.Equal(SyntaxKind.BadToken, tk.Kind) Assert.Equal(" _ ", tk.ToFullString()) Assert.Equal(30203, tk.Errors.First().Code) Dim tks = ScanAllCheckDw(" _ rem") Assert.Equal(SyntaxKind.BadToken, tks(0).Kind) Assert.Equal(" _ rem", tks(0).ToFullString()) Assert.Equal(30999, tks(0).Errors.First().Code) tk = ScanOnce("_" & vbLf, startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal("_" & vbLf, tk.ToFullString()) tk = ScanOnce(" _" & vbLf, startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(" _" & vbLf, tk.ToFullString()) Dim str = " _" & vbCrLf & " _" & vbCr & "'2 " & vbLf & " (" tk = ScanOnce(str, startStatement:=True) Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind) Assert.Equal(str, tk.ToFullString()) str = " _" & vbCrLf & " _" & vbCrLf & "(" tk = ScanOnce(str, startStatement:=True) Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind) Assert.Equal(str, tk.ToFullString()) End Sub <Fact> Public Sub Scanner_LineContInsideStatement() ' this would be a case of )_ ' valid _ would have been consumed by ) Dim tk = ScanOnce("_" & vbLf, False) Assert.Equal(SyntaxKind.BadToken, tk.Kind) Assert.Equal("_" + vbLf, tk.ToFullString) Dim Str = "'_" & vbCrLf & "(" tk = ScanOnce(Str, False) Assert.Equal(SyntaxKind.EmptyToken, tk.Kind) Assert.Equal("'_" & vbCrLf, tk.ToFullString()) Str = " _" & vbCrLf & "(" tk = ScanOnce(Str, False) Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) ' _ is invalid here, should not be consumed by ( Str = " _" & vbCrLf & "(" & "_" & vbCrLf & "'qq" tk = ScanOnce(Str, False) Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind) Assert.Equal(" _" & vbCrLf & "(", tk.ToFullString()) ' _ is valid here, but we should not go past the Eol Str = " _" & vbCrLf & "(" & " _" & vbCrLf & "'qq" tk = ScanOnce(Str, False) Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind) Assert.Equal(" _" & vbCrLf & "(" & " _" & vbCrLf, tk.ToFullString()) End Sub <Fact> Public Sub Scanner_RemComment() Dim str = " " & vbCrLf & " " & vbCr & "REM " & vbLf & " (" Dim tk = ScanOnce(str, True) Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind) Assert.Equal(str, tk.ToFullString()) str = "A REM Hello " tk = ScanOnce(str, True) Assert.Equal(SyntaxKind.IdentifierToken, tk.Kind) Assert.Equal(str, tk.ToFullString()) str = "A A REM Hello " & vbCrLf & "A Rem Hello " Dim tks = ScanAllCheckDw(str) Assert.Equal(SyntaxKind.IdentifierToken, tks(0).Kind) Assert.Equal("A ", tks(0).ToFullString) Assert.Equal(SyntaxKind.IdentifierToken, tks(1).Kind) Assert.NotEqual("A ", tks(1).ToFullString) Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(2).Kind) Assert.Equal(SyntaxKind.IdentifierToken, tks(3).Kind) Assert.NotEqual("A ", tks(1).ToFullString) Assert.Equal(SyntaxKind.EndOfFileToken, tks(4).Kind) Assert.Equal(5, tks.Count) REM( str = "REM(" tk = ScanOnce(str, True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(str, tk.ToFullString()) str = "ReM" & vbCrLf & "(" tk = ScanOnce(str, False) Assert.Equal(SyntaxKind.EmptyToken, tk.Kind) Assert.Equal("ReM" & vbCrLf, tk.ToFullString()) str = "rEM" & vbCrLf & "(" tk = ScanOnce(str, True) Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind) Assert.Equal(str, tk.ToFullString()) str = "rem " & vbCrLf & " REM(" & vbCrLf & "(" tk = ScanOnce(str, True) Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind) Assert.Equal(str, tk.ToFullString()) End Sub ''' <summary> ''' EmptyToken is generated by the Scanner in a single-line ''' If or lambda with an empty statement to avoid generating ''' a statement terminator with leading or trailing trivia. ''' </summary> <Fact> Public Sub Scanner_EmptyToken() ' No EmptyToken required because no trivia before EOF. ParseTokensAndVerify("If True Then Else Return :", SyntaxKind.IfKeyword, SyntaxKind.TrueKeyword, SyntaxKind.ThenKeyword, SyntaxKind.ElseKeyword, SyntaxKind.ReturnKeyword, SyntaxKind.ColonToken, SyntaxKind.EndOfFileToken) ' No EmptyToken required because no trailing trivia before EOF. ' (The space after the colon is leading trivia on EOF.) ParseTokensAndVerify("If True Then Else : ", SyntaxKind.IfKeyword, SyntaxKind.TrueKeyword, SyntaxKind.ThenKeyword, SyntaxKind.ElseKeyword, SyntaxKind.ColonToken, SyntaxKind.EndOfFileToken) ' EmptyToken required because comment is trailing ' trivia between the colon and EOL. ParseTokensAndVerify(<![CDATA[If True Then Else :'Comment Return]]>.Value, SyntaxKind.IfKeyword, SyntaxKind.TrueKeyword, SyntaxKind.ThenKeyword, SyntaxKind.ElseKeyword, SyntaxKind.ColonToken, SyntaxKind.EmptyToken, SyntaxKind.StatementTerminatorToken, SyntaxKind.ReturnKeyword, SyntaxKind.EndOfFileToken) ' EmptyToken required because comment is trailing ' trivia between the colon and EOF. ParseTokensAndVerify("Sub() If True Then Return : REM", SyntaxKind.SubKeyword, SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken, SyntaxKind.IfKeyword, SyntaxKind.TrueKeyword, SyntaxKind.ThenKeyword, SyntaxKind.ReturnKeyword, SyntaxKind.ColonToken, SyntaxKind.EmptyToken, SyntaxKind.EndOfFileToken) ' No EmptyToken required because colon, space, comment ' and EOL are all treated as multi-line leading trivia on EndKeyword. ParseTokensAndVerify(<![CDATA[If True Then : 'Comment End If]]>.Value, SyntaxKind.IfKeyword, SyntaxKind.TrueKeyword, SyntaxKind.ThenKeyword, SyntaxKind.StatementTerminatorToken, SyntaxKind.EndKeyword, SyntaxKind.IfKeyword, SyntaxKind.EndOfFileToken) End Sub Private Sub ParseTokensAndVerify(str As String, ParamArray kinds As SyntaxKind()) Dim tokens = SyntaxFactory.ParseTokens(str).ToArray() Dim result = String.Join("", tokens.Select(Function(t) t.ToFullString())) Assert.Equal(str, result) Assert.Equal(tokens.Length, kinds.Length) For i = 0 To tokens.Length - 1 Assert.Equal(tokens(i).Kind, kinds(i)) Next End Sub <Fact> Public Sub Scanner_DimKeyword() Dim Str = " " & vbCrLf & " " & vbCr & "DIM " & vbLf & " (" Dim tk = ScanOnce(Str, True) Assert.Equal(SyntaxKind.DimKeyword, tk.Kind) Assert.Equal(" " & vbCrLf & " " & vbCr & "DIM " + vbLf, tk.ToFullString) Str = "Dim(" tk = ScanOnce(Str, True) Assert.Equal(SyntaxKind.DimKeyword, tk.Kind) Assert.Equal("Dim", tk.ToFullString()) Str = "DiM" & vbCrLf & "(" tk = ScanOnce(Str, False) Assert.Equal(SyntaxKind.DimKeyword, tk.Kind) Assert.Equal("DiM" + vbCrLf, tk.ToFullString) Str = "dIM" & " _" & vbCrLf & "(" tk = ScanOnce(Str, True) Assert.Equal(SyntaxKind.DimKeyword, tk.Kind) Assert.Equal("dIM" & " _" & vbCrLf, tk.ToFullString()) Str = "dim " & vbCrLf & " DIMM" & vbCrLf & "(" Dim tks = ScanAllNoDwCheck(Str) Assert.Equal(SyntaxKind.DimKeyword, tks(0).Kind) Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(1).Kind) Assert.Equal(SyntaxKind.IdentifierToken, tks(2).Kind) Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(3).Kind) Assert.Equal(SyntaxKind.OpenParenToken, tks(4).Kind) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact> Public Sub StaticKeyword() Dim Str = " " & vbCrLf & " " & vbCr & "STATIC " & vbLf & " (" Dim tk = ScanOnce(Str, True) Assert.Equal(SyntaxKind.StaticKeyword, tk.Kind) Assert.Equal(" " & vbCrLf & " " & vbCr & "STATIC " & vbLf, tk.ToFullString()) Str = "Static(" tk = ScanOnce(Str, True) Assert.Equal(SyntaxKind.StaticKeyword, tk.Kind) Assert.Equal("Static", tk.ToFullString()) Str = "StatiC" & vbCrLf & "(" tk = ScanOnce(Str, False) Assert.Equal(SyntaxKind.StaticKeyword, tk.Kind) Assert.Equal("StatiC" & vbCrLf, tk.ToFullString()) Str = "sTATIC" & " _" & vbCrLf & "(" tk = ScanOnce(Str, True) Assert.Equal(SyntaxKind.StaticKeyword, tk.Kind) Assert.Equal("sTATIC" & " _" & vbCrLf, tk.ToFullString()) Str = "static " & vbCrLf & " STATICC" & vbCrLf & "(" Dim tks = ScanAllNoDwCheck(Str) Assert.Equal(SyntaxKind.StaticKeyword, tks(0).Kind) Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(1).Kind) Assert.Equal(SyntaxKind.IdentifierToken, tks(2).Kind) Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(3).Kind) Assert.Equal(SyntaxKind.OpenParenToken, tks(4).Kind) End Sub <Fact> Public Sub Scanner_FrequentKeywords() Dim Str = "End " Dim tk = ScanOnce(Str, True) Assert.Equal(SyntaxKind.EndKeyword, tk.Kind) Assert.Equal(3, tk.Span.Length) Assert.Equal(4, tk.FullSpan.Length) Assert.Equal("End ", tk.ToFullString()) Str = "As " tk = ScanOnce(Str, False) Assert.Equal(SyntaxKind.AsKeyword, tk.Kind) Assert.Equal(2, tk.Span.Length) Assert.Equal(3, tk.FullSpan.Length) Assert.Equal("As ", tk.ToFullString()) Str = "If " tk = ScanOnce(Str, False) Assert.Equal(SyntaxKind.IfKeyword, tk.Kind) Assert.Equal(2, tk.Span.Length) Assert.Equal(3, tk.FullSpan.Length) Assert.Equal("If ", tk.ToFullString()) End Sub <Fact> Public Sub Scanner_PlusToken() Dim Str = "+" Dim tk = ScanOnce(Str, True) Assert.Equal(SyntaxKind.PlusToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) Str = "+ =" tk = ScanOnce(Str, True) Assert.Equal(SyntaxKind.PlusEqualsToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) End Sub <Fact> Public Sub Scanner_PowerToken() Dim Str = "^" Dim tk = ScanOnce(Str, False) Assert.Equal(SyntaxKind.CaretToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) Str = "^ =^" Dim tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.CaretEqualsToken, tks(0).Kind) Assert.Equal(SyntaxKind.CaretToken, tks(1).Kind) End Sub <Fact> Public Sub Scanner_GreaterThanToken() Dim Str = "> " Dim tk = ScanOnce(Str, False) Assert.Equal(SyntaxKind.GreaterThanToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) Str = " >= 'qqqq" tk = ScanOnce(Str, True) Assert.Equal(SyntaxKind.GreaterThanEqualsToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) Str = " > =" tk = ScanOnce(Str, True) Assert.Equal(SyntaxKind.GreaterThanEqualsToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) 'Str = " >" & vbCrLf & "=" 'tk = ScanOnce(Str, True) 'Assert.Equal(NodeKind.GreaterToken, tk.Kind) 'Assert.Equal(" >" & vbCrLf, tk.ToFullString()) 'Str = ">" & " _" & vbCrLf & "=" 'tk = ScanOnce(Str, True) 'Assert.Equal(NodeKind.GreaterToken, tk.Kind) 'Assert.Equal(">" & " _" & vbCrLf, tk.ToFullString()) End Sub <Fact> Public Sub Scanner_LessThanToken() Dim Str = "> <" Dim tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.GreaterThanToken, tks(0).Kind) Assert.Equal(SyntaxKind.LessThanToken, tks(1).Kind) Str = "<<<<%" tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.LessThanLessThanToken, tks(0).Kind) Assert.Equal(SyntaxKind.LessThanToken, tks(1).Kind) Assert.Equal(SyntaxKind.LessThanToken, tks(2).Kind) Assert.Equal(SyntaxKind.BadToken, tks(3).Kind) Assert.Equal(SyntaxKind.EndOfFileToken, tks(4).Kind) Str = " < << <% " tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.LessThanLessThanToken, tks(0).Kind) Assert.Equal(SyntaxKind.LessThanToken, tks(1).Kind) Assert.Equal(SyntaxKind.LessThanToken, tks(2).Kind) Assert.Equal(SyntaxKind.BadToken, tks(3).Kind) Assert.Equal(SyntaxKind.EndOfFileToken, tks(4).Kind) End Sub <Fact> Public Sub Scanner_ShiftLeftToken() Dim Str = "<<<<=" Dim tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.LessThanLessThanToken, tks(0).Kind) Assert.Equal(SyntaxKind.LessThanLessThanEqualsToken, tks(1).Kind) Assert.Equal(SyntaxKind.EndOfFileToken, tks(2).Kind) 'Str = "<" & vbLf & " < < = " 'tks = ScanAllCheckDw(Str) 'Assert.Equal(NodeKind.LessToken, tks(0).Kind) 'Assert.Equal(NodeKind.LeftShiftEqualsToken, tks(1).Kind) 'Assert.Equal(NodeKind.EndOfTextToken, tks(2).Kind) '' left shift does not allow implicit line continuation 'Str = "<<" & vbLf & "<<=" 'tks = ScanAllCheckDw(Str) 'Assert.Equal(NodeKind.LeftShiftToken, tks(0).Kind) 'Assert.Equal(NodeKind.StatementTerminatorToken, tks(1).Kind) 'Assert.Equal(NodeKind.LeftShiftEqualsToken, tks(2).Kind) 'Assert.Equal(NodeKind.EndOfTextToken, tks(3).Kind) End Sub <Fact> Public Sub Scanner_NotEqualsToken() Dim Str = "<>" Dim tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.LessThanGreaterThanToken, tks(0).Kind) Assert.Equal(SyntaxKind.EndOfFileToken, tks(1).Kind) Str = "<>=" tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.LessThanGreaterThanToken, tks(0).Kind) Assert.Equal(SyntaxKind.EqualsToken, tks(1).Kind) Assert.Equal(SyntaxKind.EndOfFileToken, tks(2).Kind) 'Str = "<" & vbLf & " > " 'tks = ScanAllCheckDw(Str) 'Assert.Equal(NodeKind.LessToken, tks(0).Kind) 'Assert.Equal(NodeKind.GreaterToken, tks(1).Kind) 'Assert.Equal(NodeKind.EndOfTextToken, tks(2).Kind) '' left shift does not allow implicit line continuation 'Str = "< > <" & " _" & vbLf & ">" 'tks = ScanAllCheckDw(Str) 'Assert.Equal(NodeKind.NotEqualToken, tks(0).Kind) 'Assert.Equal(NodeKind.LessToken, tks(1).Kind) 'Assert.Equal(NodeKind.GreaterToken, tks(2).Kind) 'Assert.Equal(NodeKind.EndOfTextToken, tks(3).Kind) End Sub Private Sub CheckCharTkValue(tk As SyntaxToken, expected As Char) Dim val = DirectCast(tk.Value, Char) Assert.Equal(expected, val) End Sub <Fact> Public Sub Scanner_CharLiteralToken() Dim Str = <text>"Q"c</text>.Value Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.CharacterLiteralToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) CheckCharTkValue(tk, "Q"c) Str = <text>""""c</text>.Value tk = ScanOnce(Str) Assert.Equal(SyntaxKind.CharacterLiteralToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) CheckCharTkValue(tk, """"c) Str = <text>""c</text>.Value tk = ScanOnce(Str) Assert.Equal(SyntaxKind.BadToken, tk.Kind) Assert.Equal(30004, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(Str, tk.ToFullString()) Str = <text>"""c</text>.Value tk = ScanOnce(Str) Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind) Assert.Equal(30648, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(Str, tk.ToFullString()) CheckStrTkValue(tk, """c") Str = <text>"QQ"c</text>.Value tk = ScanOnce(Str) Assert.Equal(SyntaxKind.BadToken, tk.Kind) Assert.Equal(30004, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(Str, tk.ToFullString()) Str = <text>"Q"c "Q"c"Q"c "Q"c _ "Q"c """"c</text>.Value Dim doubleWidthStr = MakeDwString(Str) Dim tks = ScanAllNoDwCheck(doubleWidthStr) Assert.Equal(10, tks.Count) Assert.Equal(True, tks.Any(Function(t) t.ContainsDiagnostics)) End Sub Private Sub CheckStrTkValue(tk As SyntaxToken, expected As String) Dim str = DirectCast(tk.Value, String) Assert.Equal(expected, str) End Sub <Fact> Public Sub Scanner_StringLiteralToken() Dim Str = <text>""</text>.Value Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) CheckStrTkValue(tk, "") Str = <text>"Q"</text>.Value tk = ScanOnce(Str) Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) CheckStrTkValue(tk, "Q") Str = <text>""""</text>.Value tk = ScanOnce(Str) Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) CheckStrTkValue(tk, """") Str = <text>""""""""</text>.Value tk = ScanOnce(Str) Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) CheckStrTkValue(tk, """""""") Str = <text>"""" """"</text>.Value Dim tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.StringLiteralToken, tks(0).Kind) Assert.Equal(SyntaxKind.StringLiteralToken, tks(1).Kind) Str = <text>"AA" "BB"</text>.Value tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.StringLiteralToken, tks(0).Kind) Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(1).Kind) Assert.Equal(SyntaxKind.StringLiteralToken, tks(2).Kind) End Sub <Fact> Public Sub Scanner_IntegerLiteralToken() Dim Str = "42" Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Decimal, tk.GetBase()) Assert.Equal(42, tk.Value) Str = " 42 " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Decimal, tk.GetBase()) Assert.Equal(42, tk.Value) Assert.Equal(" 42 ", tk.ToFullString()) Str = " 4_2 " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Decimal, tk.GetBase()) Assert.Equal(42, tk.Value) Assert.Equal(" 4_2 ", tk.ToFullString()) Assert.Equal(0, tk.Errors().Count) Str = " &H42L " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Hexadecimal, tk.GetBase()) Assert.Equal(&H42L, tk.Value) Assert.Equal(" &H42L ", tk.ToFullString()) Str = " &H4_2L " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Hexadecimal, tk.GetBase()) Assert.Equal(&H42L, tk.Value) Assert.Equal(" &H4_2L ", tk.ToFullString()) Str = " &H_1 " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Hexadecimal, tk.GetBase()) Assert.Equal(&H1, tk.Value) Assert.Equal(" &H_1 ", tk.ToFullString()) Str = " &B_1 " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Binary, tk.GetBase()) Assert.Equal(&B1, tk.Value) Assert.Equal(" &B_1 ", tk.ToFullString()) Str = " &O_1 " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Octal, tk.GetBase()) Assert.Equal(&O1, tk.Value) Assert.Equal(" &O_1 ", tk.ToFullString()) Str = " &H__1_1L " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Hexadecimal, tk.GetBase()) Assert.Equal(&H11L, tk.Value) Assert.Equal(" &H__1_1L ", tk.ToFullString()) Str = " &B__1_1L " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Binary, tk.GetBase()) Assert.Equal(&B11L, tk.Value) Assert.Equal(" &B__1_1L ", tk.ToFullString()) Str = " &O__1_1L " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Octal, tk.GetBase()) Assert.Equal(&O11L, tk.Value) Assert.Equal(" &O__1_1L ", tk.ToFullString()) Str = " &H42L &H42& " Dim tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tks(0).Kind) Assert.Equal(LiteralBase.Hexadecimal, tks(1).GetBase()) Assert.Equal(&H42L, tks(1).Value) Assert.Equal(TypeCharacter.Long, tks(1).GetTypeCharacter()) Str = " &B1010L " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Binary, tk.GetBase()) Assert.Equal(&HAL, tk.Value) Assert.Equal(" &B1010L ", tk.ToFullString()) Assert.Equal(0, tk.Errors().Count) Str = " &B1_0_1_0L " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Binary, tk.GetBase()) Assert.Equal(&HAL, tk.Value) Assert.Equal(" &B1_0_1_0L ", tk.ToFullString()) Assert.Equal(0, tk.Errors().Count) End Sub <Fact> Public Sub Scanner_FloatingLiteralToken() Dim Str = "4.2" Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(4.2, tk.Value) Str = " 0.42 " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(0.42, tk.Value) Assert.IsType(Of Double)(tk.Value) Assert.Equal(" 0.42 ", tk.ToFullString()) Str = " 0_0.4_2 " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(0.42, tk.Value) Assert.IsType(Of Double)(tk.Value) Assert.Equal(" 0_0.4_2 ", tk.ToFullString()) Str = " 0.42# " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(0.42, tk.Value) Assert.IsType(Of Double)(tk.Value) Assert.Equal(" 0.42# ", tk.ToFullString()) Str = " 0.42R " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(0.42, tk.Value) Assert.IsType(Of Double)(tk.Value) Assert.Equal(" 0.42R ", tk.ToFullString()) Str = " 0.42! " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(0.42!, tk.Value) Assert.IsType(Of Single)(tk.Value) Assert.Equal(" 0.42! ", tk.ToFullString()) Str = " 0.42F " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(0.42F, tk.Value) Assert.IsType(Of Single)(tk.Value) Assert.Equal(" 0.42F ", tk.ToFullString()) Str = " .42 42# " Dim tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tks(1).Kind) Assert.Equal(42.0#, tks(1).Value) Assert.Equal(0.42, tks(0).Value) Assert.IsType(Of Double)(tks(1).Value) Assert.Equal(TypeCharacter.Double, tks(1).GetTypeCharacter()) End Sub <Fact> Public Sub Scanner_DecimalLiteralToken() Dim Str = "4.2D" Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.DecimalLiteralToken, tk.Kind) Assert.Equal(TypeCharacter.DecimalLiteral, tk.GetTypeCharacter()) Assert.Equal(4.2D, tk.Value) Str = " 0.42@ " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.DecimalLiteralToken, tk.Kind) Assert.Equal(0.42@, tk.Value) Assert.Equal(" 0.42@ ", tk.ToFullString()) Str = " .42D 4242424242424242424242424242@ " Dim tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.DecimalLiteralToken, tks(1).Kind) Assert.Equal(4242424242424242424242424242D, tks(1).Value) Assert.Equal(0.42D, tks(0).Value) Assert.Equal(TypeCharacter.Decimal, tks(1).GetTypeCharacter()) End Sub <WorkItem(538543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538543")> <Fact> Public Sub Scanner_DecimalLiteralExpToken() Dim Str = "1E1D" Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.DecimalLiteralToken, tk.Kind) Assert.Equal(TypeCharacter.DecimalLiteral, tk.GetTypeCharacter()) Assert.Equal(10D, tk.Value) End Sub <Fact> Public Sub Scanner_Overflow() Dim Str = "2147483647I" Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(2147483647I, CInt(tk.Value)) Str = "2147483648I" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(30036, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(0, CInt(tk.Value)) Str = "&H7FFFFFFFI" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(&H7FFFFFFFI, CInt(tk.Value)) Str = "&HFFFFFFFFI" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(&HFFFFFFFFI, tk.Value) Str = "&HFFFFFFFFS" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(30036, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(0, CInt(tk.Value)) Str = "&B111111111111111111111111111111111I" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(30036, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(0, CInt(tk.Value)) Str = "&B11111111111111111111111111111111UI" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(&HFFFFFFFFUI, CUInt(tk.Value)) Str = "&B1111111111111111111111111111111I" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(&H7FFFFFFFI, CInt(tk.Value)) Str = "1.7976931348623157E+308d" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.DecimalLiteralToken, tk.Kind) Assert.Equal(30036, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(0D, tk.Value) Str = "1.797693134862315456489789797987987897897987987E+308F" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(30036, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(0.0F, tk.Value) End Sub <Fact> Public Sub Scanner_UnderscoreWrongLocation() Dim Str = "_1" Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IdentifierToken, tk.Kind) Assert.Equal(0, tk.GetSyntaxErrorsNoTree().Count()) Str = "1_" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(30035, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(0, CInt(tk.Value)) Str = "&H1_" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(30035, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(0, CInt(tk.Value)) Str = "1_.1" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(30035, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(0, CInt(tk.Value)) Str = "1.1_" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(30035, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(0, CInt(tk.Value)) Str = "&H_" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Dim errors = tk.Errors() Assert.Equal(1, errors.Count) Assert.Equal(30035, errors.First().Code) Assert.Equal(0, CInt(tk.Value)) Str = "&H_2_" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) errors = tk.Errors() Assert.Equal(1, errors.Count) Assert.Equal(30035, errors.First().Code) Assert.Equal(0, CInt(tk.Value)) End Sub <Fact> Public Sub Scanner_UnderscoreFeatureFlag() Dim Str = "&H_1" Dim tk = ScanOnce(Str, LanguageVersion.VisualBasic14) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Dim errors = tk.Errors() Assert.Equal(1, errors.Count) Assert.Equal(36716, errors.First().Code) Assert.Equal(1, CInt(tk.Value)) Str = "&H_123_456_789_ABC_DEF_123" tk = ScanOnce(Str, LanguageVersion.VisualBasic14) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) errors = tk.Errors() Assert.Equal(2, errors.Count) Assert.Equal(30036, errors.ElementAt(0).Code) Assert.Equal(36716, errors.ElementAt(1).Code) Assert.Equal(0, CInt(tk.Value)) End Sub <Fact> Public Sub Scanner_DateLiteralToken() Dim Str = "#10/10/2010#" Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.DateLiteralToken, tk.Kind) Assert.Equal(#10/10/2010#, tk.Value) Str = "#10/10/1#" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.DateLiteralToken, tk.Kind) Assert.Equal(#10/10/0001#, tk.Value) Str = "#10/10/101#" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.DateLiteralToken, tk.Kind) Assert.Equal(#10/10/0101#, tk.Value) Str = "#10/10/0#" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.BadToken, tk.Kind) Assert.Equal(31085, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal("#10/10/0#", tk.ToFullString()) Str = " #10/10/2010 10:10:00 PM# " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.DateLiteralToken, tk.Kind) Assert.Equal(#10/10/2010 10:10:00 PM#, tk.Value) Str = "x = #10/10/2010##10/10/2010 10:10:00 PM# " Dim tks = ScanAllCheckDw(Str) Assert.Equal(#10/10/2010#, tks(2).Value) Assert.Equal(#10/10/2010 10:10:00 PM#, tks(3).Value) End Sub <Fact> Public Sub Scanner_DateLiteralTokenWithYearFirst() Dim text = "#1984-10-12#" Dim token = ScanOnce(text) Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind) Assert.Equal(#10/12/1984#, token.Value) ' May use slash as separator in dates. text = "#1984/10/12#" token = ScanOnce(text) Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind) Assert.Equal(#10/12/1984#, token.Value) ' Years must be four digits. text = "#84-10-12#" token = ScanOnce(text) Assert.Equal(SyntaxKind.BadToken, token.Kind) Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code) text = "#84/10/12#" token = ScanOnce(text) Assert.Equal(SyntaxKind.BadToken, token.Kind) Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code) ' Months may be one digit. text = "#2010-4-12#" token = ScanOnce(text) Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind) Assert.Equal(#4/12/2010#, token.Value) ' Days may be one digit. text = "#1955/11/5#" token = ScanOnce(text) Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind) Assert.Equal(#11/5/1955#, token.Value) ' Time only. text = " #09:45:01# " token = ScanOnce(text) Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind) Assert.Equal(#1/1/1 9:45:01 AM#, token.Value) ' Date and time. text = " # 2010-04-12 9:00 # " token = ScanOnce(text) Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind) Assert.Equal(#4/12/2010 9:00:00 AM#, token.Value) text = " #2010/04/12 9:00# " token = ScanOnce(text) Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind) Assert.Equal(#4/12/2010 9:00:00 AM#, token.Value) text = "x = #2010-04-12##2010-04-12 09:00:00 # " Dim tokens = ScanAllCheckDw(text) Assert.Equal(#4/12/2010#, tokens(2).Value) Assert.Equal(#4/12/2010 9:00:00 AM#, tokens(3).Value) text = "#01984/10/12#" token = ScanOnce(text) Assert.Equal(SyntaxKind.BadToken, token.Kind) Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code) text = "#984/10/12#" token = ScanOnce(text) Assert.Equal(SyntaxKind.BadToken, token.Kind) Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code) text = "#1984/10/#" token = ScanOnce(text) Assert.Equal(SyntaxKind.BadToken, token.Kind) Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code) text = "#1984//12#" token = ScanOnce(text) Assert.Equal(SyntaxKind.BadToken, token.Kind) Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code) text = "#1984/10-12#" token = ScanOnce(text) Assert.Equal(SyntaxKind.BadToken, token.Kind) Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code) text = "#1984-10/12#" token = ScanOnce(text) Assert.Equal(SyntaxKind.BadToken, token.Kind) Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code) End Sub <Fact, WorkItem(529782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529782")> Public Sub DateAndDecimalCultureIndependentTokens() Dim SavedCultureInfo = CurrentThread.CurrentCulture Try CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("de-DE", False) Dim Str = "4.2" Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(4.2, tk.Value) Str = "4.2F" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(4.2F, tk.Value) Assert.IsType(Of Single)(tk.Value) Str = "4.2R" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(4.2R, tk.Value) Assert.IsType(Of Double)(tk.Value) Str = "4.2D" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.DecimalLiteralToken, tk.Kind) Assert.Equal(4.2D, tk.Value) Assert.IsType(Of Decimal)(tk.Value) Str = "#8/23/1970 3:35:39AM#" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.DateLiteralToken, tk.Kind) Assert.Equal(#8/23/1970 3:35:39 AM#, tk.Value) Finally CurrentThread.CurrentCulture = SavedCultureInfo End Try End Sub <Fact> Public Sub Scanner_BracketedIdentToken() Dim Str = "[Goo123]" Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IdentifierToken, tk.Kind) Assert.True(tk.IsBracketed) Assert.Equal("Goo123", tk.ValueText) Assert.Equal("Goo123", tk.Value) Assert.Equal("[Goo123]", tk.ToFullString()) Str = "[__]" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IdentifierToken, tk.Kind) Assert.True(tk.IsBracketed) Assert.Equal("__", tk.ValueText) Assert.Equal("[__]", tk.ToFullString()) Str = "[Goo ]" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.BadToken, tk.Kind) Assert.Equal(30034, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal("[Goo ", tk.ToFullString()) Str = "[]" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.BadToken, tk.Kind) Assert.Equal(30203, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal("[]", tk.ToFullString()) Str = "[_]" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.BadToken, tk.Kind) Assert.Equal(30203, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal("[_]", tk.ToFullString()) End Sub <Fact> Public Sub Scanner_StringLiteralValueText() Dim str = """Hello, World!""" Dim tk = ScanOnce(str) Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind) Assert.Equal("Hello, World!", tk.ValueText) Assert.Equal("""Hello, World!""", tk.ToFullString()) End Sub <Fact> Public Sub Scanner_MultiLineStringLiteral() Dim text = <text>"Hello, World!"</text>.Value Dim token = ScanOnce(text) Assert.Equal(SyntaxKind.StringLiteralToken, token.Kind) Assert.Equal("Hello," & vbLf & "World!", token.ValueText) Assert.Equal("""Hello," & vbLf & "World!""", token.ToString()) End Sub Private Function Repeat(str As String, num As Integer) As String Dim arr(num - 1) As String For i As Integer = 0 To num - 1 arr(i) = str Next Return String.Join("", arr) End Function <Fact> Public Sub Scanner_BufferTest() For i As Integer = 0 To 12 Dim TokenStr = New String("+"c, i) Dim tks = ScanAllCheckDw(TokenStr) Assert.Equal(i + 1, tks.Count) TokenStr = Repeat(" SomeIdentifier ", i) tks = ScanAllCheckDw(TokenStr) Assert.Equal(i + 1, tks.Count) ' trying to place space after "someIdent" on ^2 boundary Dim identLen = Math.Max(1, CInt(2 ^ i) - 11) TokenStr = Repeat("X", identLen) & " someIdent " & Repeat("X", identLen + 11) tks = ScanAllNoDwCheck(TokenStr) Assert.Equal(4, tks.Count) Next For i As Integer = 100 To 5000 Step 250 Dim TokenStr = New String("+"c, i) Dim tks = ScanAllCheckDw(TokenStr) Assert.Equal(i + 1, tks.Count) TokenStr = Repeat(" SomeIdentifier ", i) tks = ScanAllCheckDw(TokenStr) Assert.Equal(i + 1, tks.Count) Next End Sub <Fact> Public Sub Scanner_Bug866445() Dim x = &HFF00110001020408L Dim Str = "&HFF00110001020408L" Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) End Sub <Fact> Public Sub Bug869260() Dim tk = ScanOnce(ChrW(0)) Assert.Equal(SyntaxKind.BadToken, tk.Kind) Assert.Equal(CInt(ERRID.ERR_IllegalChar), tk.GetSyntaxErrorsNoTree(0).Code) End Sub <Fact> Public Sub Bug869081() ParseAndVerify(<![CDATA[ <Obsolete()> _ _ _ _ _ <CLSCompliant(False)> Class Class1 End Class ]]>) End Sub <Fact> Public Sub Bug658441() ParseAndVerify(<![CDATA[ #If False Then #If False Then # _ #End If # _ End If #End If ]]>) End Sub <WorkItem(538747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538747")> <Fact> Public Sub OghamSpacemark() ParseAndVerify(<![CDATA[ Module M End Module ]]>) End Sub <WorkItem(531175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531175")> <Fact> Public Sub Bug17703() ParseAndVerify(<![CDATA[ Dim x = < ”' ]]>, <errors> <error id="31151" message="Element is missing an end tag." start="9" end="23"/> <error id="31146" message="XML name expected." start="10" end="10"/> <error id="31146" message="XML name expected." start="10" end="10"/> <error id="30249" message="'=' expected." start="10" end="10"/> <error id="31164" message="Expected matching closing double quote for XML attribute value." start="23" end="23"/> <error id="31165" message="Expected beginning &lt; for an XML tag." start="23" end="23"/> <error id="30636" message="'>' expected." start="23" end="23"/> </errors>) End Sub <WorkItem(530916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530916")> <Fact> Public Sub Bug17189() ParseAndVerify(<![CDATA[ a< -' - ]]>, <errors> <error id="30689" message="Statement cannot appear outside of a method body." start="1" end="17"/> <error id="30800" message="Method arguments must be enclosed in parentheses." start="2" end="17"/> <error id="31151" message="Element is missing an end tag." start="2" end="17"/> <error id="31177" message="White space cannot appear here." start="3" end="4"/> <error id="31169" message="Character '-' (&amp;H2D) is not allowed at the beginning of an XML name." start="4" end="5"/> <error id="31146" message="XML name expected." start="5" end="5"/> <error id="30249" message="'=' expected." start="5" end="5"/> <error id="31163" message="Expected matching closing single quote for XML attribute value." start="17" end="17"/> <error id="31165" message="Expected beginning '&lt;' for an XML tag." start="17" end="17"/> <error id="30636" message="'>' expected." start="17" end="17"/> </errors>) End Sub <WorkItem(530682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530682")> <Fact> Public Sub Bug16698() ParseAndVerify(<![CDATA[#Const x = <!-- ]]>, Diagnostic(ERRID.ERR_BadCCExpression, "<!--")) End Sub <WorkItem(865832, "DevDiv/Personal")> <Fact> Public Sub ParseSpecialKeywords() ParseAndVerify(<![CDATA[ Module M1 Dim x As Integer Sub Main If True End If End Sub End Module ]]>). VerifyNoWhitespaceInKeywords() End Sub <WorkItem(547317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547317")> <Fact> Public Sub ParseHugeNumber() ParseAndVerify(<![CDATA[ Module M Sub Main Dim x = CompareDouble(-7.92281625142643E337593543950335D) End Sub EndModule ]]>, <errors> <error id="30625" message="'Module' statement must end with a matching 'End Module'." start="1" end="9"/> <error id="30036" message="Overflow." start="52" end="85"/> <error id="30188" message="Declaration expected." start="100" end="109"/> </errors>). VerifyNoWhitespaceInKeywords() End Sub <WorkItem(547317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547317")> <Fact> Public Sub ParseHugeNumberLabel() ParseAndVerify(<![CDATA[ Module M Sub Main 678901234567890123456789012345678901234567456789012345678901234567890123456789012345 End Sub EndModule ]]>, <errors> <error id="30625" message="'Module' statement must end with a matching 'End Module'." start="1" end="9"/> <error id="30801" message="Labels that are numbers must be followed by colons." start="30" end="114"/> <error id="30036" message="Overflow." start="30" end="114"/> <error id="30188" message="Declaration expected." start="128" end="137"/> </errors>). VerifyNoWhitespaceInKeywords() End Sub <WorkItem(926612, "DevDiv/Personal")> <Fact> Public Sub ScanMultilinesTriviaWithCRLFs() ParseAndVerify(<![CDATA[Option Compare Text Public Class Assembly001bDll Sub main() Dim Asb As System.Reflection.Assembly Asb = System.Reflection.Assembly.GetExecutingAssembly() apcompare(Left(CurDir(), 1) & ":\School\assembly001bdll.dll", Asb.Location, "location") End Sub End Class]]>) End Sub <Fact> Public Sub IsWhiteSpace() Assert.False(SyntaxFacts.IsWhitespace("A"c)) Assert.True(SyntaxFacts.IsWhitespace(" "c)) Assert.True(SyntaxFacts.IsWhitespace(ChrW(9))) Assert.False(SyntaxFacts.IsWhitespace(ChrW(0))) Assert.False(SyntaxFacts.IsWhitespace(ChrW(128))) Assert.False(SyntaxFacts.IsWhitespace(ChrW(129))) Assert.False(SyntaxFacts.IsWhitespace(ChrW(127))) Assert.True(SyntaxFacts.IsWhitespace(ChrW(160))) Assert.True(SyntaxFacts.IsWhitespace(ChrW(12288))) Assert.True(SyntaxFacts.IsWhitespace(ChrW(8192))) Assert.True(SyntaxFacts.IsWhitespace(ChrW(8203))) End Sub <Fact> Public Sub IsNewline() Assert.True(SyntaxFacts.IsNewLine(ChrW(13))) Assert.True(SyntaxFacts.IsNewLine(ChrW(10))) Assert.True(SyntaxFacts.IsNewLine(ChrW(133))) Assert.True(SyntaxFacts.IsNewLine(ChrW(8232))) Assert.True(SyntaxFacts.IsNewLine(ChrW(8233))) Assert.False(SyntaxFacts.IsNewLine(ChrW(132))) Assert.False(SyntaxFacts.IsNewLine(ChrW(160))) Assert.False(SyntaxFacts.IsNewLine(" "c)) Assert.Equal(String.Empty, SyntaxFacts.MakeHalfWidthIdentifier(String.Empty)) Assert.Null(SyntaxFacts.MakeHalfWidthIdentifier(Nothing)) Assert.Equal("ABC", SyntaxFacts.MakeHalfWidthIdentifier("ABC")) Assert.Equal(ChrW(65280), SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65280))) Assert.NotEqual(ChrW(65281), SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65281))) Assert.Equal(1, SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65281)).Length) End Sub <Fact> Public Sub MakeHalfWidthIdentifier() Assert.Equal(String.Empty, SyntaxFacts.MakeHalfWidthIdentifier(String.Empty)) Assert.Equal(Nothing, SyntaxFacts.MakeHalfWidthIdentifier(Nothing)) Assert.Equal("ABC", SyntaxFacts.MakeHalfWidthIdentifier("ABC")) Assert.Equal(ChrW(65280), SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65280))) Assert.NotEqual(ChrW(65281), SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65281))) Assert.Equal(1, SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65281)).Length) End Sub End Class Module SyntaxDiagnosticInfoListExtensions <Extension> Public Function Count(list As SyntaxDiagnosticInfoList) As Integer Dim result = 0 For Each v In list result += 1 Next Return result End Function <Extension> Public Function First(list As SyntaxDiagnosticInfoList) As DiagnosticInfo For Each v In list Return v Next Throw New InvalidOperationException() End Function <Extension> Public Function ElementAt(list As SyntaxDiagnosticInfoList, index As Integer) As DiagnosticInfo Dim i = 0 For Each v In list If i = index Then Return v End If i += 1 Next Throw New IndexOutOfRangeException() End Function End Module
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports System.Threading.Thread Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities <CLSCompliant(False)> Public Class ScannerTests Inherits BasicTestBase Private Function ScanOnce(str As String, Optional startStatement As Boolean = False) As SyntaxToken Return SyntaxFactory.ParseToken(str, startStatement:=startStatement) End Function Private Function ScanOnce(str As String, languageVersion As VisualBasic.LanguageVersion) As SyntaxToken Return SyntaxFactory.ParseTokens(str, options:=New VisualBasicParseOptions(languageVersion:=languageVersion)).First() End Function Private Function AsString(tokens As IEnumerable(Of SyntaxToken)) As String Dim str = String.Concat(From t In tokens Select t.ToFullString()) Return str End Function Private Function MakeDwString(str As String) As String Return (From c In str Select If(c < ChrW(&H21S) OrElse c > ChrW(&H7ES), c, ChrW(AscW(c) + &HFF00US - &H20US))).ToArray End Function Private Function ScanAllCheckDw(str As String) As IEnumerable(Of SyntaxToken) Dim tokens = SyntaxFactory.ParseTokens(str) ' test that token have the same text as it was. Assert.Equal(str, AsString(tokens)) ' test that we get same with doublewidth string Dim doubleWidthStr = MakeDwString(str) Dim doubleWidthTokens = ScanAllNoDwCheck(doubleWidthStr) Assert.Equal(tokens.Count, doubleWidthTokens.Count) For Each t In tokens.Zip(doubleWidthTokens, Function(t1, t2) Tuple.Create(t1, t2)) Assert.Equal(t.Item1.Kind, t.Item2.Kind) Assert.Equal(t.Item1.Span, t.Item2.Span) Assert.Equal(t.Item1.FullSpan, t.Item2.FullSpan) Assert.Equal(MakeDwString(t.Item1.ToFullString()), t.Item2.ToFullString()) Next Return tokens End Function Private Function ScanAllNoDwCheck(str As String) As IEnumerable(Of SyntaxToken) Dim tokens = SyntaxFactory.ParseTokens(str) ' test that token have the same text as it was. Assert.Equal(str, AsString(tokens)) Return tokens End Function <Fact> Public Sub TestLessThanConflictMarker1() ' Needs to be followed by a space. Dim token = SyntaxFactory.ParseTokens("<<<<<<<").First() Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind()) ' Has to be the start of a line. token = SyntaxFactory.ParseTokens(" <<<<<<<").First() Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia) ' Has to have at least seven characters. token = SyntaxFactory.ParseTokens("<<<<<< ").First() Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind()) ' Start of line, seven characters, ends with space. token = SyntaxFactory.ParseTokens("<<<<<<< ").First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Dim trivia = token.LeadingTrivia.Single() Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.True(trivia.ContainsDiagnostics) Dim err = trivia.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) End Sub <Fact> Public Sub TestLessThanConflictMarker2() Dim token = SyntaxFactory.ParseTokens("{" & vbCrLf & "<<<<<<<").Skip(2).First() Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind()) token = SyntaxFactory.ParseTokens("{" & vbCrLf & " <<<<<<<").Skip(2).First() Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia) token = SyntaxFactory.ParseTokens("{" & vbCrLf & "<<<<<< ").Skip(2).First() Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind()) token = SyntaxFactory.ParseTokens("{" & vbCrLf & "<<<<<<< ").Skip(2).First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Dim trivia = token.LeadingTrivia.Single() Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.True(trivia.SpanStart = 3) Assert.True(trivia.Span.Length = 8) Assert.True(trivia.ContainsDiagnostics) Dim err = trivia.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) End Sub <Fact> Public Sub TestGreaterThanConflictMarker1() ' Needs to be followed by a space. Dim token = SyntaxFactory.ParseTokens(">>>>>>>").First() Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind()) ' Has to be the start of a line. token = SyntaxFactory.ParseTokens(" >>>>>>>").First() Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia) ' Has to have at least seven characters. token = SyntaxFactory.ParseTokens(">>>>>> ").First() Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind()) ' Start of line, seven characters, ends with space. token = SyntaxFactory.ParseTokens(">>>>>>> ").First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Dim trivia = token.LeadingTrivia.Single() Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.True(trivia.ContainsDiagnostics) Dim err = trivia.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) End Sub <Fact> Public Sub TestGreaterThanConflictMarker2() Dim token = SyntaxFactory.ParseTokens("{" & vbCrLf & ">>>>>>>").Skip(2).First() Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind()) token = SyntaxFactory.ParseTokens("{" & vbCrLf & " >>>>>>>").Skip(2).First() Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia) token = SyntaxFactory.ParseTokens("{" & vbCrLf & ">>>>>> ").Skip(2).First() Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind()) token = SyntaxFactory.ParseTokens("{" & vbCrLf & ">>>>>>> ").Skip(2).First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Dim trivia = token.LeadingTrivia.Single() Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.True(trivia.SpanStart = 3) Assert.True(trivia.Span.Length = 8) Assert.True(trivia.ContainsDiagnostics) Dim err = trivia.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) End Sub <Fact> Public Sub TestEqualsConflictMarker1() ' Has to be the start of a line. Dim token = SyntaxFactory.ParseTokens(" =======").First() Assert.Equal(SyntaxKind.EqualsToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia) ' Has to have at least seven characters. token = SyntaxFactory.ParseTokens("====== ").First() Assert.Equal(SyntaxKind.EqualsToken, token.Kind()) ' Start of line, seven characters token = SyntaxFactory.ParseTokens("=======").First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.ConflictMarkerTrivia) ' Start of line, seven characters token = SyntaxFactory.ParseTokens("======= trailing chars").First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Dim trivia = token.LeadingTrivia.Single() Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.Equal(trivia.Span.Length, 22) Assert.True(trivia.ContainsDiagnostics) Dim err = trivia.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) token = SyntaxFactory.ParseTokens("======= Trailing" & vbCrLf & "disabled text").First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.Equal(3, token.LeadingTrivia.Count) trivia = token.LeadingTrivia(0) Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.Equal(trivia.Span.Length, 16) Assert.True(trivia.ContainsDiagnostics) err = trivia.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) trivia = token.LeadingTrivia(1) Assert.True(trivia.Kind() = SyntaxKind.EndOfLineTrivia) Assert.Equal(trivia.Span.Start, 16) Assert.Equal(trivia.Span.Length, 2) trivia = token.LeadingTrivia(2) Assert.True(trivia.Kind() = SyntaxKind.DisabledTextTrivia) Assert.Equal(trivia.Span.Start, 18) Assert.Equal(trivia.Span.Length, 13) token = SyntaxFactory.ParseTokens("======= Trailing" & vbCrLf & "disabled text" & vbCrLf & ">>>> still disabled").First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.Equal(3, token.LeadingTrivia.Count) trivia = token.LeadingTrivia(0) Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.Equal(trivia.Span.Length, 16) Assert.True(trivia.ContainsDiagnostics) err = trivia.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) trivia = token.LeadingTrivia(1) Assert.True(trivia.Kind() = SyntaxKind.EndOfLineTrivia) Assert.Equal(trivia.Span.Length, 2) trivia = token.LeadingTrivia(2) Assert.True(trivia.Kind() = SyntaxKind.DisabledTextTrivia) Assert.Equal(trivia.Span.Length, 34) token = SyntaxFactory.ParseTokens("======= Trailing" & vbCrLf & "disabled text" & vbCrLf & ">>>>>>> Actually the end").First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.Equal(token.LeadingTrivia.Count, 4) Dim trivia1 = token.LeadingTrivia(0) Assert.True(trivia1.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.Equal(trivia1.Span.Length, 16) Assert.True(trivia1.ContainsDiagnostics) err = trivia1.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) Dim trivia2 = token.LeadingTrivia(1) Assert.True(trivia2.Kind() = SyntaxKind.EndOfLineTrivia) Assert.Equal(trivia2.Span.Start, 16) Assert.Equal(trivia2.Span.Length, 2) Dim trivia3 = token.LeadingTrivia(2) Assert.True(trivia3.Kind() = SyntaxKind.DisabledTextTrivia) Assert.Equal(trivia3.Span.Start, 18) Assert.Equal(trivia3.Span.Length, 15) Dim trivia4 = token.LeadingTrivia(3) Assert.True(trivia4.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.Equal(trivia4.Span.Start, 33) Assert.Equal(trivia4.Span.Length, 24) Assert.True(trivia4.ContainsDiagnostics) err = trivia4.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) End Sub <Fact> Public Sub TestEqualsConflictMarker2() ' Has to be the start of a line. Dim token = SyntaxFactory.ParseTokens("{" & vbCrLf & " =======").Skip(2).First() Assert.Equal(SyntaxKind.EqualsToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia) ' Has to have at least seven characters. token = SyntaxFactory.ParseTokens("{" & vbCrLf & "====== ").Skip(2).First() Assert.Equal(SyntaxKind.EqualsToken, token.Kind()) ' Start of line, seven characters token = SyntaxFactory.ParseTokens("{" & vbCrLf & "=======").Skip(2).First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Dim trivia = token.LeadingTrivia.Single() Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.True(trivia.ContainsDiagnostics) Dim err = trivia.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) ' Start of line, seven characters token = SyntaxFactory.ParseTokens("{" & vbCrLf & "======= trailing chars").Skip(2).First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) trivia = token.LeadingTrivia.Single() Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.Equal(trivia.Span.Length, 22) Assert.True(trivia.ContainsDiagnostics) err = trivia.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) token = SyntaxFactory.ParseTokens("{" & vbCrLf & "======= Trailing" & vbCrLf & "disabled text").Skip(2).First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.Equal(3, token.LeadingTrivia.Count) trivia = token.LeadingTrivia(0) Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.Equal(trivia.Span.Length, 16) Assert.True(trivia.ContainsDiagnostics) err = trivia.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) trivia = token.LeadingTrivia(1) Assert.True(trivia.Kind() = SyntaxKind.EndOfLineTrivia) Assert.Equal(trivia.Span.Start, 19) Assert.Equal(trivia.Span.Length, 2) trivia = token.LeadingTrivia(2) Assert.True(trivia.Kind() = SyntaxKind.DisabledTextTrivia) Assert.Equal(trivia.Span.Start, 21) Assert.Equal(trivia.Span.Length, 13) token = SyntaxFactory.ParseTokens("{" & vbCrLf & "======= Trailing" & vbCrLf & "disabled text" & vbCrLf & ">>>> still disabled").Skip(2).First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.Equal(3, token.LeadingTrivia.Count) trivia = token.LeadingTrivia(0) Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.Equal(trivia.Span.Length, 16) Assert.True(trivia.ContainsDiagnostics) err = trivia.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) trivia = token.LeadingTrivia(1) Assert.True(trivia.Kind() = SyntaxKind.EndOfLineTrivia) Assert.Equal(trivia.Span.Length, 2) trivia = token.LeadingTrivia(2) Assert.True(trivia.Kind() = SyntaxKind.DisabledTextTrivia) Assert.Equal(trivia.Span.Length, 34) token = SyntaxFactory.ParseTokens("{" & vbCrLf & "======= Trailing" & vbCrLf & "disabled text" & vbCrLf & ">>>>>>> Actually the end").Skip(2).First() Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind()) Assert.True(token.HasLeadingTrivia) Assert.Equal(token.LeadingTrivia.Count, 4) Dim trivia1 = token.LeadingTrivia(0) Assert.True(trivia1.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.Equal(trivia1.Span.Length, 16) Assert.True(trivia1.ContainsDiagnostics) err = trivia1.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) Dim trivia2 = token.LeadingTrivia(1) Assert.True(trivia2.Kind() = SyntaxKind.EndOfLineTrivia) Assert.Equal(trivia2.Span.Start, 19) Assert.Equal(trivia2.Span.Length, 2) Dim trivia3 = token.LeadingTrivia(2) Assert.True(trivia3.Kind() = SyntaxKind.DisabledTextTrivia) Assert.Equal(trivia3.Span.Start, 21) Assert.Equal(trivia3.Span.Length, 15) Dim trivia4 = token.LeadingTrivia(3) Assert.True(trivia4.Kind() = SyntaxKind.ConflictMarkerTrivia) Assert.Equal(trivia4.Span.Start, 36) Assert.Equal(trivia4.Span.Length, 24) Assert.True(trivia4.ContainsDiagnostics) err = trivia4.Errors().First Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code) End Sub <Fact> Public Sub Scanner_EndOfText() Dim tk = ScanOnce("") Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal("", tk.ToFullString()) tk = ScanOnce(" ") Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(" ", tk.ToFullString()) tk = ScanOnce(" ") Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(" ", tk.ToFullString()) tk = ScanOnce("'") Assert.Equal(SyntaxKind.EmptyToken, tk.Kind) Assert.Equal(SyntaxKind.CommentTrivia, tk.TrailingTrivia(0).Kind) Assert.Equal("'", tk.ToFullString()) tk = ScanOnce("'", startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(0).Kind) Assert.Equal("'", tk.ToFullString()) tk = ScanOnce(" ' ") Assert.Equal(SyntaxKind.EmptyToken, tk.Kind) Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind) Assert.Equal(SyntaxKind.CommentTrivia, tk.TrailingTrivia(0).Kind) Assert.Equal(" ", tk.LeadingTrivia(0).ToString()) Assert.Equal("' ", tk.TrailingTrivia(0).ToString()) Assert.Equal(" ' ", tk.ToFullString()) tk = ScanOnce(" ' ", startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind) Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(1).Kind) Assert.Equal(" ", tk.LeadingTrivia(0).ToString()) Assert.Equal("' ", tk.LeadingTrivia(1).ToString()) Assert.Equal(" ' ", tk.ToFullString()) End Sub <Fact> Public Sub Scanner_StatementTerminator() Dim tk = ScanOnce(vbCr) Assert.Equal(SyntaxKind.EmptyToken, tk.Kind) Assert.Equal(vbCr, tk.ToFullString()) tk = ScanOnce(vbCr, startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(vbCr, tk.ToFullString()) Dim tks = ScanAllCheckDw(vbCr) Assert.Equal(1, tks.Count) Assert.Equal(SyntaxKind.EndOfFileToken, tks(0).Kind) Assert.Equal(vbCr, tks(0).ToFullString()) tks = ScanAllCheckDw(" " & vbLf) Assert.Equal(1, tks.Count) Assert.Equal(SyntaxKind.EndOfFileToken, tks(0).Kind) Assert.Equal(" " & vbLf, tks(0).ToFullString()) tks = ScanAllCheckDw(" A" & vbCrLf & " ") Assert.Equal(3, tks.Count) Assert.Equal(SyntaxKind.IdentifierToken, tks(0).Kind) Assert.Equal(" A" & vbCrLf, tks(0).ToFullString()) Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(1).Kind) Assert.Equal("", tks(1).ToFullString()) Assert.Equal(SyntaxKind.EndOfFileToken, tks(2).Kind) Assert.Equal(" ", tks(2).ToFullString()) End Sub <Fact> Public Sub Scanner_StartStatement() Dim tk = ScanOnce(vbCr, startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(vbCr, tk.ToFullString()) tk = ScanOnce(" " & vbLf, startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(" " & vbLf, tk.ToFullString()) Dim str = " " & vbCrLf & " " & vbCr & "'2 " & vbLf & " (" tk = ScanOnce(str, startStatement:=True) Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind) Assert.Equal(str, tk.ToFullString()) str = "'(" tk = ScanOnce(str, startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(str, tk.ToFullString()) str = "'" & vbCrLf & "(" tk = ScanOnce(str, startStatement:=False) Assert.Equal(SyntaxKind.EmptyToken, tk.Kind) Assert.Equal("'" & vbCrLf, tk.ToFullString()) str = "'" & vbCrLf & "(" tk = ScanOnce(str, startStatement:=True) Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind) Assert.Equal(str, tk.ToFullString()) str = "' " & vbCrLf & " '(" & vbCrLf & "(" tk = ScanOnce(str, startStatement:=True) Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind) Assert.Equal(str, tk.ToFullString()) End Sub <Fact> Public Sub Scanner_LineContWhenExpectingNewStatement() Dim tk = ScanOnce("_", startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal("_", tk.ToFullString()) tk = ScanOnce(" _", startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(" _", tk.ToFullString()) tk = ScanOnce(" _ ", startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(" _ ", tk.ToFullString()) tk = ScanOnce(" _'", startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(" _'", tk.ToFullString()) Assert.Equal(3, tk.LeadingTrivia.Count) Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind) Assert.Equal(SyntaxKind.LineContinuationTrivia, tk.LeadingTrivia(1).Kind) Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(2).Kind) Assert.Equal(0, tk.Errors.Count) tk = ScanOnce(" _'", LanguageVersion.VisualBasic16) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(" _'", tk.ToFullString()) Assert.Equal(3, tk.LeadingTrivia.Count) Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind) Assert.Equal(SyntaxKind.LineContinuationTrivia, tk.LeadingTrivia(1).Kind) Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(2).Kind) Assert.Equal(0, tk.Errors.Count) tk = ScanOnce(" _' Comment", LanguageVersion.VisualBasic15_3) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(" _' Comment", tk.ToFullString()) Assert.Equal(3, tk.LeadingTrivia.Count) Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind) Assert.False(tk.LeadingTrivia(0).ContainsDiagnostics) Assert.Equal(SyntaxKind.LineContinuationTrivia, tk.LeadingTrivia(1).Kind) Assert.False(tk.LeadingTrivia(1).ContainsDiagnostics) Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(2).Kind) Assert.True(tk.LeadingTrivia(2).ContainsDiagnostics) Assert.Equal(1, tk.Errors.Count) Assert.Equal(ERRID.ERR_CommentsAfterLineContinuationNotAvailable1, tk.Errors.First().Code) tk = ScanOnce(" _' Comment", LanguageVersion.VisualBasic16) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(" _' Comment", tk.ToFullString()) Assert.Equal(3, tk.LeadingTrivia.Count) Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind) Assert.Equal(SyntaxKind.LineContinuationTrivia, tk.LeadingTrivia(1).Kind) Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(2).Kind) Assert.Equal(0, tk.Errors.Count) tk = ScanOnce(" _ ' Comment" & vbCrLf, LanguageVersion.VisualBasic16) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(" _ ' Comment" & vbCrLf, tk.ToFullString()) Assert.Equal(5, tk.LeadingTrivia.Count) Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind) Assert.Equal(SyntaxKind.LineContinuationTrivia, tk.LeadingTrivia(1).Kind) Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(2).Kind) Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(3).Kind) Assert.Equal(SyntaxKind.EndOfLineTrivia, tk.LeadingTrivia(4).Kind) Assert.Equal(0, tk.Errors.Count) tk = ScanOnce(" _ rem", startStatement:=True) Assert.Equal(SyntaxKind.BadToken, tk.Kind) Assert.Equal(" _ rem", tk.ToFullString()) Assert.Equal(30999, tk.Errors.First().Code) tk = ScanOnce(" _ abc", startStatement:=True) Assert.Equal(SyntaxKind.BadToken, tk.Kind) Assert.Equal(" _ ", tk.ToFullString()) Assert.Equal(30203, tk.Errors.First().Code) Dim tks = ScanAllCheckDw(" _ rem") Assert.Equal(SyntaxKind.BadToken, tks(0).Kind) Assert.Equal(" _ rem", tks(0).ToFullString()) Assert.Equal(30999, tks(0).Errors.First().Code) tk = ScanOnce("_" & vbLf, startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal("_" & vbLf, tk.ToFullString()) tk = ScanOnce(" _" & vbLf, startStatement:=True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(" _" & vbLf, tk.ToFullString()) Dim str = " _" & vbCrLf & " _" & vbCr & "'2 " & vbLf & " (" tk = ScanOnce(str, startStatement:=True) Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind) Assert.Equal(str, tk.ToFullString()) str = " _" & vbCrLf & " _" & vbCrLf & "(" tk = ScanOnce(str, startStatement:=True) Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind) Assert.Equal(str, tk.ToFullString()) End Sub <Fact> Public Sub Scanner_LineContInsideStatement() ' this would be a case of )_ ' valid _ would have been consumed by ) Dim tk = ScanOnce("_" & vbLf, False) Assert.Equal(SyntaxKind.BadToken, tk.Kind) Assert.Equal("_" + vbLf, tk.ToFullString) Dim Str = "'_" & vbCrLf & "(" tk = ScanOnce(Str, False) Assert.Equal(SyntaxKind.EmptyToken, tk.Kind) Assert.Equal("'_" & vbCrLf, tk.ToFullString()) Str = " _" & vbCrLf & "(" tk = ScanOnce(Str, False) Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) ' _ is invalid here, should not be consumed by ( Str = " _" & vbCrLf & "(" & "_" & vbCrLf & "'qq" tk = ScanOnce(Str, False) Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind) Assert.Equal(" _" & vbCrLf & "(", tk.ToFullString()) ' _ is valid here, but we should not go past the Eol Str = " _" & vbCrLf & "(" & " _" & vbCrLf & "'qq" tk = ScanOnce(Str, False) Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind) Assert.Equal(" _" & vbCrLf & "(" & " _" & vbCrLf, tk.ToFullString()) End Sub <Fact> Public Sub Scanner_RemComment() Dim str = " " & vbCrLf & " " & vbCr & "REM " & vbLf & " (" Dim tk = ScanOnce(str, True) Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind) Assert.Equal(str, tk.ToFullString()) str = "A REM Hello " tk = ScanOnce(str, True) Assert.Equal(SyntaxKind.IdentifierToken, tk.Kind) Assert.Equal(str, tk.ToFullString()) str = "A A REM Hello " & vbCrLf & "A Rem Hello " Dim tks = ScanAllCheckDw(str) Assert.Equal(SyntaxKind.IdentifierToken, tks(0).Kind) Assert.Equal("A ", tks(0).ToFullString) Assert.Equal(SyntaxKind.IdentifierToken, tks(1).Kind) Assert.NotEqual("A ", tks(1).ToFullString) Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(2).Kind) Assert.Equal(SyntaxKind.IdentifierToken, tks(3).Kind) Assert.NotEqual("A ", tks(1).ToFullString) Assert.Equal(SyntaxKind.EndOfFileToken, tks(4).Kind) Assert.Equal(5, tks.Count) REM( str = "REM(" tk = ScanOnce(str, True) Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind) Assert.Equal(str, tk.ToFullString()) str = "ReM" & vbCrLf & "(" tk = ScanOnce(str, False) Assert.Equal(SyntaxKind.EmptyToken, tk.Kind) Assert.Equal("ReM" & vbCrLf, tk.ToFullString()) str = "rEM" & vbCrLf & "(" tk = ScanOnce(str, True) Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind) Assert.Equal(str, tk.ToFullString()) str = "rem " & vbCrLf & " REM(" & vbCrLf & "(" tk = ScanOnce(str, True) Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind) Assert.Equal(str, tk.ToFullString()) End Sub ''' <summary> ''' EmptyToken is generated by the Scanner in a single-line ''' If or lambda with an empty statement to avoid generating ''' a statement terminator with leading or trailing trivia. ''' </summary> <Fact> Public Sub Scanner_EmptyToken() ' No EmptyToken required because no trivia before EOF. ParseTokensAndVerify("If True Then Else Return :", SyntaxKind.IfKeyword, SyntaxKind.TrueKeyword, SyntaxKind.ThenKeyword, SyntaxKind.ElseKeyword, SyntaxKind.ReturnKeyword, SyntaxKind.ColonToken, SyntaxKind.EndOfFileToken) ' No EmptyToken required because no trailing trivia before EOF. ' (The space after the colon is leading trivia on EOF.) ParseTokensAndVerify("If True Then Else : ", SyntaxKind.IfKeyword, SyntaxKind.TrueKeyword, SyntaxKind.ThenKeyword, SyntaxKind.ElseKeyword, SyntaxKind.ColonToken, SyntaxKind.EndOfFileToken) ' EmptyToken required because comment is trailing ' trivia between the colon and EOL. ParseTokensAndVerify(<![CDATA[If True Then Else :'Comment Return]]>.Value, SyntaxKind.IfKeyword, SyntaxKind.TrueKeyword, SyntaxKind.ThenKeyword, SyntaxKind.ElseKeyword, SyntaxKind.ColonToken, SyntaxKind.EmptyToken, SyntaxKind.StatementTerminatorToken, SyntaxKind.ReturnKeyword, SyntaxKind.EndOfFileToken) ' EmptyToken required because comment is trailing ' trivia between the colon and EOF. ParseTokensAndVerify("Sub() If True Then Return : REM", SyntaxKind.SubKeyword, SyntaxKind.OpenParenToken, SyntaxKind.CloseParenToken, SyntaxKind.IfKeyword, SyntaxKind.TrueKeyword, SyntaxKind.ThenKeyword, SyntaxKind.ReturnKeyword, SyntaxKind.ColonToken, SyntaxKind.EmptyToken, SyntaxKind.EndOfFileToken) ' No EmptyToken required because colon, space, comment ' and EOL are all treated as multi-line leading trivia on EndKeyword. ParseTokensAndVerify(<![CDATA[If True Then : 'Comment End If]]>.Value, SyntaxKind.IfKeyword, SyntaxKind.TrueKeyword, SyntaxKind.ThenKeyword, SyntaxKind.StatementTerminatorToken, SyntaxKind.EndKeyword, SyntaxKind.IfKeyword, SyntaxKind.EndOfFileToken) End Sub Private Sub ParseTokensAndVerify(str As String, ParamArray kinds As SyntaxKind()) Dim tokens = SyntaxFactory.ParseTokens(str).ToArray() Dim result = String.Join("", tokens.Select(Function(t) t.ToFullString())) Assert.Equal(str, result) Assert.Equal(tokens.Length, kinds.Length) For i = 0 To tokens.Length - 1 Assert.Equal(tokens(i).Kind, kinds(i)) Next End Sub <Fact> Public Sub Scanner_DimKeyword() Dim Str = " " & vbCrLf & " " & vbCr & "DIM " & vbLf & " (" Dim tk = ScanOnce(Str, True) Assert.Equal(SyntaxKind.DimKeyword, tk.Kind) Assert.Equal(" " & vbCrLf & " " & vbCr & "DIM " + vbLf, tk.ToFullString) Str = "Dim(" tk = ScanOnce(Str, True) Assert.Equal(SyntaxKind.DimKeyword, tk.Kind) Assert.Equal("Dim", tk.ToFullString()) Str = "DiM" & vbCrLf & "(" tk = ScanOnce(Str, False) Assert.Equal(SyntaxKind.DimKeyword, tk.Kind) Assert.Equal("DiM" + vbCrLf, tk.ToFullString) Str = "dIM" & " _" & vbCrLf & "(" tk = ScanOnce(Str, True) Assert.Equal(SyntaxKind.DimKeyword, tk.Kind) Assert.Equal("dIM" & " _" & vbCrLf, tk.ToFullString()) Str = "dim " & vbCrLf & " DIMM" & vbCrLf & "(" Dim tks = ScanAllNoDwCheck(Str) Assert.Equal(SyntaxKind.DimKeyword, tks(0).Kind) Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(1).Kind) Assert.Equal(SyntaxKind.IdentifierToken, tks(2).Kind) Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(3).Kind) Assert.Equal(SyntaxKind.OpenParenToken, tks(4).Kind) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact> Public Sub StaticKeyword() Dim Str = " " & vbCrLf & " " & vbCr & "STATIC " & vbLf & " (" Dim tk = ScanOnce(Str, True) Assert.Equal(SyntaxKind.StaticKeyword, tk.Kind) Assert.Equal(" " & vbCrLf & " " & vbCr & "STATIC " & vbLf, tk.ToFullString()) Str = "Static(" tk = ScanOnce(Str, True) Assert.Equal(SyntaxKind.StaticKeyword, tk.Kind) Assert.Equal("Static", tk.ToFullString()) Str = "StatiC" & vbCrLf & "(" tk = ScanOnce(Str, False) Assert.Equal(SyntaxKind.StaticKeyword, tk.Kind) Assert.Equal("StatiC" & vbCrLf, tk.ToFullString()) Str = "sTATIC" & " _" & vbCrLf & "(" tk = ScanOnce(Str, True) Assert.Equal(SyntaxKind.StaticKeyword, tk.Kind) Assert.Equal("sTATIC" & " _" & vbCrLf, tk.ToFullString()) Str = "static " & vbCrLf & " STATICC" & vbCrLf & "(" Dim tks = ScanAllNoDwCheck(Str) Assert.Equal(SyntaxKind.StaticKeyword, tks(0).Kind) Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(1).Kind) Assert.Equal(SyntaxKind.IdentifierToken, tks(2).Kind) Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(3).Kind) Assert.Equal(SyntaxKind.OpenParenToken, tks(4).Kind) End Sub <Fact> Public Sub Scanner_FrequentKeywords() Dim Str = "End " Dim tk = ScanOnce(Str, True) Assert.Equal(SyntaxKind.EndKeyword, tk.Kind) Assert.Equal(3, tk.Span.Length) Assert.Equal(4, tk.FullSpan.Length) Assert.Equal("End ", tk.ToFullString()) Str = "As " tk = ScanOnce(Str, False) Assert.Equal(SyntaxKind.AsKeyword, tk.Kind) Assert.Equal(2, tk.Span.Length) Assert.Equal(3, tk.FullSpan.Length) Assert.Equal("As ", tk.ToFullString()) Str = "If " tk = ScanOnce(Str, False) Assert.Equal(SyntaxKind.IfKeyword, tk.Kind) Assert.Equal(2, tk.Span.Length) Assert.Equal(3, tk.FullSpan.Length) Assert.Equal("If ", tk.ToFullString()) End Sub <Fact> Public Sub Scanner_PlusToken() Dim Str = "+" Dim tk = ScanOnce(Str, True) Assert.Equal(SyntaxKind.PlusToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) Str = "+ =" tk = ScanOnce(Str, True) Assert.Equal(SyntaxKind.PlusEqualsToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) End Sub <Fact> Public Sub Scanner_PowerToken() Dim Str = "^" Dim tk = ScanOnce(Str, False) Assert.Equal(SyntaxKind.CaretToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) Str = "^ =^" Dim tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.CaretEqualsToken, tks(0).Kind) Assert.Equal(SyntaxKind.CaretToken, tks(1).Kind) End Sub <Fact> Public Sub Scanner_GreaterThanToken() Dim Str = "> " Dim tk = ScanOnce(Str, False) Assert.Equal(SyntaxKind.GreaterThanToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) Str = " >= 'qqqq" tk = ScanOnce(Str, True) Assert.Equal(SyntaxKind.GreaterThanEqualsToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) Str = " > =" tk = ScanOnce(Str, True) Assert.Equal(SyntaxKind.GreaterThanEqualsToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) 'Str = " >" & vbCrLf & "=" 'tk = ScanOnce(Str, True) 'Assert.Equal(NodeKind.GreaterToken, tk.Kind) 'Assert.Equal(" >" & vbCrLf, tk.ToFullString()) 'Str = ">" & " _" & vbCrLf & "=" 'tk = ScanOnce(Str, True) 'Assert.Equal(NodeKind.GreaterToken, tk.Kind) 'Assert.Equal(">" & " _" & vbCrLf, tk.ToFullString()) End Sub <Fact> Public Sub Scanner_LessThanToken() Dim Str = "> <" Dim tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.GreaterThanToken, tks(0).Kind) Assert.Equal(SyntaxKind.LessThanToken, tks(1).Kind) Str = "<<<<%" tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.LessThanLessThanToken, tks(0).Kind) Assert.Equal(SyntaxKind.LessThanToken, tks(1).Kind) Assert.Equal(SyntaxKind.LessThanToken, tks(2).Kind) Assert.Equal(SyntaxKind.BadToken, tks(3).Kind) Assert.Equal(SyntaxKind.EndOfFileToken, tks(4).Kind) Str = " < << <% " tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.LessThanLessThanToken, tks(0).Kind) Assert.Equal(SyntaxKind.LessThanToken, tks(1).Kind) Assert.Equal(SyntaxKind.LessThanToken, tks(2).Kind) Assert.Equal(SyntaxKind.BadToken, tks(3).Kind) Assert.Equal(SyntaxKind.EndOfFileToken, tks(4).Kind) End Sub <Fact> Public Sub Scanner_ShiftLeftToken() Dim Str = "<<<<=" Dim tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.LessThanLessThanToken, tks(0).Kind) Assert.Equal(SyntaxKind.LessThanLessThanEqualsToken, tks(1).Kind) Assert.Equal(SyntaxKind.EndOfFileToken, tks(2).Kind) 'Str = "<" & vbLf & " < < = " 'tks = ScanAllCheckDw(Str) 'Assert.Equal(NodeKind.LessToken, tks(0).Kind) 'Assert.Equal(NodeKind.LeftShiftEqualsToken, tks(1).Kind) 'Assert.Equal(NodeKind.EndOfTextToken, tks(2).Kind) '' left shift does not allow implicit line continuation 'Str = "<<" & vbLf & "<<=" 'tks = ScanAllCheckDw(Str) 'Assert.Equal(NodeKind.LeftShiftToken, tks(0).Kind) 'Assert.Equal(NodeKind.StatementTerminatorToken, tks(1).Kind) 'Assert.Equal(NodeKind.LeftShiftEqualsToken, tks(2).Kind) 'Assert.Equal(NodeKind.EndOfTextToken, tks(3).Kind) End Sub <Fact> Public Sub Scanner_NotEqualsToken() Dim Str = "<>" Dim tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.LessThanGreaterThanToken, tks(0).Kind) Assert.Equal(SyntaxKind.EndOfFileToken, tks(1).Kind) Str = "<>=" tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.LessThanGreaterThanToken, tks(0).Kind) Assert.Equal(SyntaxKind.EqualsToken, tks(1).Kind) Assert.Equal(SyntaxKind.EndOfFileToken, tks(2).Kind) 'Str = "<" & vbLf & " > " 'tks = ScanAllCheckDw(Str) 'Assert.Equal(NodeKind.LessToken, tks(0).Kind) 'Assert.Equal(NodeKind.GreaterToken, tks(1).Kind) 'Assert.Equal(NodeKind.EndOfTextToken, tks(2).Kind) '' left shift does not allow implicit line continuation 'Str = "< > <" & " _" & vbLf & ">" 'tks = ScanAllCheckDw(Str) 'Assert.Equal(NodeKind.NotEqualToken, tks(0).Kind) 'Assert.Equal(NodeKind.LessToken, tks(1).Kind) 'Assert.Equal(NodeKind.GreaterToken, tks(2).Kind) 'Assert.Equal(NodeKind.EndOfTextToken, tks(3).Kind) End Sub Private Sub CheckCharTkValue(tk As SyntaxToken, expected As Char) Dim val = DirectCast(tk.Value, Char) Assert.Equal(expected, val) End Sub <Fact> Public Sub Scanner_CharLiteralToken() Dim Str = <text>"Q"c</text>.Value Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.CharacterLiteralToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) CheckCharTkValue(tk, "Q"c) Str = <text>""""c</text>.Value tk = ScanOnce(Str) Assert.Equal(SyntaxKind.CharacterLiteralToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) CheckCharTkValue(tk, """"c) Str = <text>""c</text>.Value tk = ScanOnce(Str) Assert.Equal(SyntaxKind.BadToken, tk.Kind) Assert.Equal(30004, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(Str, tk.ToFullString()) Str = <text>"""c</text>.Value tk = ScanOnce(Str) Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind) Assert.Equal(30648, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(Str, tk.ToFullString()) CheckStrTkValue(tk, """c") Str = <text>"QQ"c</text>.Value tk = ScanOnce(Str) Assert.Equal(SyntaxKind.BadToken, tk.Kind) Assert.Equal(30004, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(Str, tk.ToFullString()) Str = <text>"Q"c "Q"c"Q"c "Q"c _ "Q"c """"c</text>.Value Dim doubleWidthStr = MakeDwString(Str) Dim tks = ScanAllNoDwCheck(doubleWidthStr) Assert.Equal(10, tks.Count) Assert.Equal(True, tks.Any(Function(t) t.ContainsDiagnostics)) End Sub Private Sub CheckStrTkValue(tk As SyntaxToken, expected As String) Dim str = DirectCast(tk.Value, String) Assert.Equal(expected, str) End Sub <Fact> Public Sub Scanner_StringLiteralToken() Dim Str = <text>""</text>.Value Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) CheckStrTkValue(tk, "") Str = <text>"Q"</text>.Value tk = ScanOnce(Str) Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) CheckStrTkValue(tk, "Q") Str = <text>""""</text>.Value tk = ScanOnce(Str) Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) CheckStrTkValue(tk, """") Str = <text>""""""""</text>.Value tk = ScanOnce(Str) Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind) Assert.Equal(Str, tk.ToFullString()) CheckStrTkValue(tk, """""""") Str = <text>"""" """"</text>.Value Dim tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.StringLiteralToken, tks(0).Kind) Assert.Equal(SyntaxKind.StringLiteralToken, tks(1).Kind) Str = <text>"AA" "BB"</text>.Value tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.StringLiteralToken, tks(0).Kind) Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(1).Kind) Assert.Equal(SyntaxKind.StringLiteralToken, tks(2).Kind) End Sub <Fact> Public Sub Scanner_IntegerLiteralToken() Dim Str = "42" Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Decimal, tk.GetBase()) Assert.Equal(42, tk.Value) Str = " 42 " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Decimal, tk.GetBase()) Assert.Equal(42, tk.Value) Assert.Equal(" 42 ", tk.ToFullString()) Str = " 4_2 " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Decimal, tk.GetBase()) Assert.Equal(42, tk.Value) Assert.Equal(" 4_2 ", tk.ToFullString()) Assert.Equal(0, tk.Errors().Count) Str = " &H42L " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Hexadecimal, tk.GetBase()) Assert.Equal(&H42L, tk.Value) Assert.Equal(" &H42L ", tk.ToFullString()) Str = " &H4_2L " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Hexadecimal, tk.GetBase()) Assert.Equal(&H42L, tk.Value) Assert.Equal(" &H4_2L ", tk.ToFullString()) Str = " &H_1 " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Hexadecimal, tk.GetBase()) Assert.Equal(&H1, tk.Value) Assert.Equal(" &H_1 ", tk.ToFullString()) Str = " &B_1 " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Binary, tk.GetBase()) Assert.Equal(&B1, tk.Value) Assert.Equal(" &B_1 ", tk.ToFullString()) Str = " &O_1 " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Octal, tk.GetBase()) Assert.Equal(&O1, tk.Value) Assert.Equal(" &O_1 ", tk.ToFullString()) Str = " &H__1_1L " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Hexadecimal, tk.GetBase()) Assert.Equal(&H11L, tk.Value) Assert.Equal(" &H__1_1L ", tk.ToFullString()) Str = " &B__1_1L " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Binary, tk.GetBase()) Assert.Equal(&B11L, tk.Value) Assert.Equal(" &B__1_1L ", tk.ToFullString()) Str = " &O__1_1L " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Octal, tk.GetBase()) Assert.Equal(&O11L, tk.Value) Assert.Equal(" &O__1_1L ", tk.ToFullString()) Str = " &H42L &H42& " Dim tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tks(0).Kind) Assert.Equal(LiteralBase.Hexadecimal, tks(1).GetBase()) Assert.Equal(&H42L, tks(1).Value) Assert.Equal(TypeCharacter.Long, tks(1).GetTypeCharacter()) Str = " &B1010L " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Binary, tk.GetBase()) Assert.Equal(&HAL, tk.Value) Assert.Equal(" &B1010L ", tk.ToFullString()) Assert.Equal(0, tk.Errors().Count) Str = " &B1_0_1_0L " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(LiteralBase.Binary, tk.GetBase()) Assert.Equal(&HAL, tk.Value) Assert.Equal(" &B1_0_1_0L ", tk.ToFullString()) Assert.Equal(0, tk.Errors().Count) End Sub <Fact> Public Sub Scanner_FloatingLiteralToken() Dim Str = "4.2" Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(4.2, tk.Value) Str = " 0.42 " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(0.42, tk.Value) Assert.IsType(Of Double)(tk.Value) Assert.Equal(" 0.42 ", tk.ToFullString()) Str = " 0_0.4_2 " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(0.42, tk.Value) Assert.IsType(Of Double)(tk.Value) Assert.Equal(" 0_0.4_2 ", tk.ToFullString()) Str = " 0.42# " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(0.42, tk.Value) Assert.IsType(Of Double)(tk.Value) Assert.Equal(" 0.42# ", tk.ToFullString()) Str = " 0.42R " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(0.42, tk.Value) Assert.IsType(Of Double)(tk.Value) Assert.Equal(" 0.42R ", tk.ToFullString()) Str = " 0.42! " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(0.42!, tk.Value) Assert.IsType(Of Single)(tk.Value) Assert.Equal(" 0.42! ", tk.ToFullString()) Str = " 0.42F " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(0.42F, tk.Value) Assert.IsType(Of Single)(tk.Value) Assert.Equal(" 0.42F ", tk.ToFullString()) Str = " .42 42# " Dim tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tks(1).Kind) Assert.Equal(42.0#, tks(1).Value) Assert.Equal(0.42, tks(0).Value) Assert.IsType(Of Double)(tks(1).Value) Assert.Equal(TypeCharacter.Double, tks(1).GetTypeCharacter()) End Sub <Fact> Public Sub Scanner_DecimalLiteralToken() Dim Str = "4.2D" Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.DecimalLiteralToken, tk.Kind) Assert.Equal(TypeCharacter.DecimalLiteral, tk.GetTypeCharacter()) Assert.Equal(4.2D, tk.Value) Str = " 0.42@ " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.DecimalLiteralToken, tk.Kind) Assert.Equal(0.42@, tk.Value) Assert.Equal(" 0.42@ ", tk.ToFullString()) Str = " .42D 4242424242424242424242424242@ " Dim tks = ScanAllCheckDw(Str) Assert.Equal(SyntaxKind.DecimalLiteralToken, tks(1).Kind) Assert.Equal(4242424242424242424242424242D, tks(1).Value) Assert.Equal(0.42D, tks(0).Value) Assert.Equal(TypeCharacter.Decimal, tks(1).GetTypeCharacter()) End Sub <WorkItem(538543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538543")> <Fact> Public Sub Scanner_DecimalLiteralExpToken() Dim Str = "1E1D" Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.DecimalLiteralToken, tk.Kind) Assert.Equal(TypeCharacter.DecimalLiteral, tk.GetTypeCharacter()) Assert.Equal(10D, tk.Value) End Sub <Fact> Public Sub Scanner_Overflow() Dim Str = "2147483647I" Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(2147483647I, CInt(tk.Value)) Str = "2147483648I" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(30036, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(0, CInt(tk.Value)) Str = "&H7FFFFFFFI" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(&H7FFFFFFFI, CInt(tk.Value)) Str = "&HFFFFFFFFI" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(&HFFFFFFFFI, tk.Value) Str = "&HFFFFFFFFS" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(30036, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(0, CInt(tk.Value)) Str = "&B111111111111111111111111111111111I" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(30036, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(0, CInt(tk.Value)) Str = "&B11111111111111111111111111111111UI" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(&HFFFFFFFFUI, CUInt(tk.Value)) Str = "&B1111111111111111111111111111111I" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(&H7FFFFFFFI, CInt(tk.Value)) Str = "1.7976931348623157E+308d" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.DecimalLiteralToken, tk.Kind) Assert.Equal(30036, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(0D, tk.Value) Str = "1.797693134862315456489789797987987897897987987E+308F" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(30036, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(0.0F, tk.Value) End Sub <Fact> Public Sub Scanner_UnderscoreWrongLocation() Dim Str = "_1" Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IdentifierToken, tk.Kind) Assert.Equal(0, tk.GetSyntaxErrorsNoTree().Count()) Str = "1_" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(30035, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(0, CInt(tk.Value)) Str = "&H1_" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Assert.Equal(30035, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(0, CInt(tk.Value)) Str = "1_.1" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(30035, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(0, CInt(tk.Value)) Str = "1.1_" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(30035, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal(0, CInt(tk.Value)) Str = "&H_" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Dim errors = tk.Errors() Assert.Equal(1, errors.Count) Assert.Equal(30035, errors.First().Code) Assert.Equal(0, CInt(tk.Value)) Str = "&H_2_" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) errors = tk.Errors() Assert.Equal(1, errors.Count) Assert.Equal(30035, errors.First().Code) Assert.Equal(0, CInt(tk.Value)) End Sub <Fact> Public Sub Scanner_UnderscoreFeatureFlag() Dim Str = "&H_1" Dim tk = ScanOnce(Str, LanguageVersion.VisualBasic14) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) Dim errors = tk.Errors() Assert.Equal(1, errors.Count) Assert.Equal(36716, errors.First().Code) Assert.Equal(1, CInt(tk.Value)) Str = "&H_123_456_789_ABC_DEF_123" tk = ScanOnce(Str, LanguageVersion.VisualBasic14) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) errors = tk.Errors() Assert.Equal(2, errors.Count) Assert.Equal(30036, errors.ElementAt(0).Code) Assert.Equal(36716, errors.ElementAt(1).Code) Assert.Equal(0, CInt(tk.Value)) End Sub <Fact> Public Sub Scanner_DateLiteralToken() Dim Str = "#10/10/2010#" Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.DateLiteralToken, tk.Kind) Assert.Equal(#10/10/2010#, tk.Value) Str = "#10/10/1#" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.DateLiteralToken, tk.Kind) Assert.Equal(#10/10/0001#, tk.Value) Str = "#10/10/101#" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.DateLiteralToken, tk.Kind) Assert.Equal(#10/10/0101#, tk.Value) Str = "#10/10/0#" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.BadToken, tk.Kind) Assert.Equal(31085, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal("#10/10/0#", tk.ToFullString()) Str = " #10/10/2010 10:10:00 PM# " tk = ScanOnce(Str) Assert.Equal(SyntaxKind.DateLiteralToken, tk.Kind) Assert.Equal(#10/10/2010 10:10:00 PM#, tk.Value) Str = "x = #10/10/2010##10/10/2010 10:10:00 PM# " Dim tks = ScanAllCheckDw(Str) Assert.Equal(#10/10/2010#, tks(2).Value) Assert.Equal(#10/10/2010 10:10:00 PM#, tks(3).Value) End Sub <Fact> Public Sub Scanner_DateLiteralTokenWithYearFirst() Dim text = "#1984-10-12#" Dim token = ScanOnce(text) Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind) Assert.Equal(#10/12/1984#, token.Value) ' May use slash as separator in dates. text = "#1984/10/12#" token = ScanOnce(text) Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind) Assert.Equal(#10/12/1984#, token.Value) ' Years must be four digits. text = "#84-10-12#" token = ScanOnce(text) Assert.Equal(SyntaxKind.BadToken, token.Kind) Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code) text = "#84/10/12#" token = ScanOnce(text) Assert.Equal(SyntaxKind.BadToken, token.Kind) Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code) ' Months may be one digit. text = "#2010-4-12#" token = ScanOnce(text) Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind) Assert.Equal(#4/12/2010#, token.Value) ' Days may be one digit. text = "#1955/11/5#" token = ScanOnce(text) Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind) Assert.Equal(#11/5/1955#, token.Value) ' Time only. text = " #09:45:01# " token = ScanOnce(text) Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind) Assert.Equal(#1/1/1 9:45:01 AM#, token.Value) ' Date and time. text = " # 2010-04-12 9:00 # " token = ScanOnce(text) Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind) Assert.Equal(#4/12/2010 9:00:00 AM#, token.Value) text = " #2010/04/12 9:00# " token = ScanOnce(text) Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind) Assert.Equal(#4/12/2010 9:00:00 AM#, token.Value) text = "x = #2010-04-12##2010-04-12 09:00:00 # " Dim tokens = ScanAllCheckDw(text) Assert.Equal(#4/12/2010#, tokens(2).Value) Assert.Equal(#4/12/2010 9:00:00 AM#, tokens(3).Value) text = "#01984/10/12#" token = ScanOnce(text) Assert.Equal(SyntaxKind.BadToken, token.Kind) Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code) text = "#984/10/12#" token = ScanOnce(text) Assert.Equal(SyntaxKind.BadToken, token.Kind) Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code) text = "#1984/10/#" token = ScanOnce(text) Assert.Equal(SyntaxKind.BadToken, token.Kind) Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code) text = "#1984//12#" token = ScanOnce(text) Assert.Equal(SyntaxKind.BadToken, token.Kind) Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code) text = "#1984/10-12#" token = ScanOnce(text) Assert.Equal(SyntaxKind.BadToken, token.Kind) Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code) text = "#1984-10/12#" token = ScanOnce(text) Assert.Equal(SyntaxKind.BadToken, token.Kind) Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code) End Sub <Fact, WorkItem(529782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529782")> Public Sub DateAndDecimalCultureIndependentTokens() Dim SavedCultureInfo = CurrentThread.CurrentCulture Try CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("de-DE", False) Dim Str = "4.2" Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(4.2, tk.Value) Str = "4.2F" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(4.2F, tk.Value) Assert.IsType(Of Single)(tk.Value) Str = "4.2R" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind) Assert.Equal(4.2R, tk.Value) Assert.IsType(Of Double)(tk.Value) Str = "4.2D" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.DecimalLiteralToken, tk.Kind) Assert.Equal(4.2D, tk.Value) Assert.IsType(Of Decimal)(tk.Value) Str = "#8/23/1970 3:35:39AM#" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.DateLiteralToken, tk.Kind) Assert.Equal(#8/23/1970 3:35:39 AM#, tk.Value) Finally CurrentThread.CurrentCulture = SavedCultureInfo End Try End Sub <Fact> Public Sub Scanner_BracketedIdentToken() Dim Str = "[Goo123]" Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IdentifierToken, tk.Kind) Assert.True(tk.IsBracketed) Assert.Equal("Goo123", tk.ValueText) Assert.Equal("Goo123", tk.Value) Assert.Equal("[Goo123]", tk.ToFullString()) Str = "[__]" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IdentifierToken, tk.Kind) Assert.True(tk.IsBracketed) Assert.Equal("__", tk.ValueText) Assert.Equal("[__]", tk.ToFullString()) Str = "[Goo ]" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.BadToken, tk.Kind) Assert.Equal(30034, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal("[Goo ", tk.ToFullString()) Str = "[]" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.BadToken, tk.Kind) Assert.Equal(30203, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal("[]", tk.ToFullString()) Str = "[_]" tk = ScanOnce(Str) Assert.Equal(SyntaxKind.BadToken, tk.Kind) Assert.Equal(30203, tk.GetSyntaxErrorsNoTree()(0).Code) Assert.Equal("[_]", tk.ToFullString()) End Sub <Fact> Public Sub Scanner_StringLiteralValueText() Dim str = """Hello, World!""" Dim tk = ScanOnce(str) Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind) Assert.Equal("Hello, World!", tk.ValueText) Assert.Equal("""Hello, World!""", tk.ToFullString()) End Sub <Fact> Public Sub Scanner_MultiLineStringLiteral() Dim text = <text>"Hello, World!"</text>.Value Dim token = ScanOnce(text) Assert.Equal(SyntaxKind.StringLiteralToken, token.Kind) Assert.Equal("Hello," & vbLf & "World!", token.ValueText) Assert.Equal("""Hello," & vbLf & "World!""", token.ToString()) End Sub Private Function Repeat(str As String, num As Integer) As String Dim arr(num - 1) As String For i As Integer = 0 To num - 1 arr(i) = str Next Return String.Join("", arr) End Function <Fact> Public Sub Scanner_BufferTest() For i As Integer = 0 To 12 Dim TokenStr = New String("+"c, i) Dim tks = ScanAllCheckDw(TokenStr) Assert.Equal(i + 1, tks.Count) TokenStr = Repeat(" SomeIdentifier ", i) tks = ScanAllCheckDw(TokenStr) Assert.Equal(i + 1, tks.Count) ' trying to place space after "someIdent" on ^2 boundary Dim identLen = Math.Max(1, CInt(2 ^ i) - 11) TokenStr = Repeat("X", identLen) & " someIdent " & Repeat("X", identLen + 11) tks = ScanAllNoDwCheck(TokenStr) Assert.Equal(4, tks.Count) Next For i As Integer = 100 To 5000 Step 250 Dim TokenStr = New String("+"c, i) Dim tks = ScanAllCheckDw(TokenStr) Assert.Equal(i + 1, tks.Count) TokenStr = Repeat(" SomeIdentifier ", i) tks = ScanAllCheckDw(TokenStr) Assert.Equal(i + 1, tks.Count) Next End Sub <Fact> Public Sub Scanner_Bug866445() Dim x = &HFF00110001020408L Dim Str = "&HFF00110001020408L" Dim tk = ScanOnce(Str) Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind) End Sub <Fact> Public Sub Bug869260() Dim tk = ScanOnce(ChrW(0)) Assert.Equal(SyntaxKind.BadToken, tk.Kind) Assert.Equal(CInt(ERRID.ERR_IllegalChar), tk.GetSyntaxErrorsNoTree(0).Code) End Sub <Fact> Public Sub Bug869081() ParseAndVerify(<![CDATA[ <Obsolete()> _ _ _ _ _ <CLSCompliant(False)> Class Class1 End Class ]]>) End Sub <Fact> Public Sub Bug658441() ParseAndVerify(<![CDATA[ #If False Then #If False Then # _ #End If # _ End If #End If ]]>) End Sub <WorkItem(538747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538747")> <Fact> Public Sub OghamSpacemark() ParseAndVerify(<![CDATA[ Module M End Module ]]>) End Sub <WorkItem(531175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531175")> <Fact> Public Sub Bug17703() ParseAndVerify(<![CDATA[ Dim x = < ”' ]]>, <errors> <error id="31151" message="Element is missing an end tag." start="9" end="23"/> <error id="31146" message="XML name expected." start="10" end="10"/> <error id="31146" message="XML name expected." start="10" end="10"/> <error id="30249" message="'=' expected." start="10" end="10"/> <error id="31164" message="Expected matching closing double quote for XML attribute value." start="23" end="23"/> <error id="31165" message="Expected beginning &lt; for an XML tag." start="23" end="23"/> <error id="30636" message="'>' expected." start="23" end="23"/> </errors>) End Sub <WorkItem(530916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530916")> <Fact> Public Sub Bug17189() ParseAndVerify(<![CDATA[ a< -' - ]]>, <errors> <error id="30689" message="Statement cannot appear outside of a method body." start="1" end="17"/> <error id="30800" message="Method arguments must be enclosed in parentheses." start="2" end="17"/> <error id="31151" message="Element is missing an end tag." start="2" end="17"/> <error id="31177" message="White space cannot appear here." start="3" end="4"/> <error id="31169" message="Character '-' (&amp;H2D) is not allowed at the beginning of an XML name." start="4" end="5"/> <error id="31146" message="XML name expected." start="5" end="5"/> <error id="30249" message="'=' expected." start="5" end="5"/> <error id="31163" message="Expected matching closing single quote for XML attribute value." start="17" end="17"/> <error id="31165" message="Expected beginning '&lt;' for an XML tag." start="17" end="17"/> <error id="30636" message="'>' expected." start="17" end="17"/> </errors>) End Sub <WorkItem(530682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530682")> <Fact> Public Sub Bug16698() ParseAndVerify(<![CDATA[#Const x = <!-- ]]>, Diagnostic(ERRID.ERR_BadCCExpression, "<!--")) End Sub <WorkItem(865832, "DevDiv/Personal")> <Fact> Public Sub ParseSpecialKeywords() ParseAndVerify(<![CDATA[ Module M1 Dim x As Integer Sub Main If True End If End Sub End Module ]]>). VerifyNoWhitespaceInKeywords() End Sub <WorkItem(547317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547317")> <Fact> Public Sub ParseHugeNumber() ParseAndVerify(<![CDATA[ Module M Sub Main Dim x = CompareDouble(-7.92281625142643E337593543950335D) End Sub EndModule ]]>, <errors> <error id="30625" message="'Module' statement must end with a matching 'End Module'." start="1" end="9"/> <error id="30036" message="Overflow." start="52" end="85"/> <error id="30188" message="Declaration expected." start="100" end="109"/> </errors>). VerifyNoWhitespaceInKeywords() End Sub <WorkItem(547317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547317")> <Fact> Public Sub ParseHugeNumberLabel() ParseAndVerify(<![CDATA[ Module M Sub Main 678901234567890123456789012345678901234567456789012345678901234567890123456789012345 End Sub EndModule ]]>, <errors> <error id="30625" message="'Module' statement must end with a matching 'End Module'." start="1" end="9"/> <error id="30801" message="Labels that are numbers must be followed by colons." start="30" end="114"/> <error id="30036" message="Overflow." start="30" end="114"/> <error id="30188" message="Declaration expected." start="128" end="137"/> </errors>). VerifyNoWhitespaceInKeywords() End Sub <WorkItem(926612, "DevDiv/Personal")> <Fact> Public Sub ScanMultilinesTriviaWithCRLFs() ParseAndVerify(<![CDATA[Option Compare Text Public Class Assembly001bDll Sub main() Dim Asb As System.Reflection.Assembly Asb = System.Reflection.Assembly.GetExecutingAssembly() apcompare(Left(CurDir(), 1) & ":\School\assembly001bdll.dll", Asb.Location, "location") End Sub End Class]]>) End Sub <Fact> Public Sub IsWhiteSpace() Assert.False(SyntaxFacts.IsWhitespace("A"c)) Assert.True(SyntaxFacts.IsWhitespace(" "c)) Assert.True(SyntaxFacts.IsWhitespace(ChrW(9))) Assert.False(SyntaxFacts.IsWhitespace(ChrW(0))) Assert.False(SyntaxFacts.IsWhitespace(ChrW(128))) Assert.False(SyntaxFacts.IsWhitespace(ChrW(129))) Assert.False(SyntaxFacts.IsWhitespace(ChrW(127))) Assert.True(SyntaxFacts.IsWhitespace(ChrW(160))) Assert.True(SyntaxFacts.IsWhitespace(ChrW(12288))) Assert.True(SyntaxFacts.IsWhitespace(ChrW(8192))) Assert.True(SyntaxFacts.IsWhitespace(ChrW(8203))) End Sub <Fact> Public Sub IsNewline() Assert.True(SyntaxFacts.IsNewLine(ChrW(13))) Assert.True(SyntaxFacts.IsNewLine(ChrW(10))) Assert.True(SyntaxFacts.IsNewLine(ChrW(133))) Assert.True(SyntaxFacts.IsNewLine(ChrW(8232))) Assert.True(SyntaxFacts.IsNewLine(ChrW(8233))) Assert.False(SyntaxFacts.IsNewLine(ChrW(132))) Assert.False(SyntaxFacts.IsNewLine(ChrW(160))) Assert.False(SyntaxFacts.IsNewLine(" "c)) Assert.Equal(String.Empty, SyntaxFacts.MakeHalfWidthIdentifier(String.Empty)) Assert.Null(SyntaxFacts.MakeHalfWidthIdentifier(Nothing)) Assert.Equal("ABC", SyntaxFacts.MakeHalfWidthIdentifier("ABC")) Assert.Equal(ChrW(65280), SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65280))) Assert.NotEqual(ChrW(65281), SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65281))) Assert.Equal(1, SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65281)).Length) End Sub <Fact> Public Sub MakeHalfWidthIdentifier() Assert.Equal(String.Empty, SyntaxFacts.MakeHalfWidthIdentifier(String.Empty)) Assert.Equal(Nothing, SyntaxFacts.MakeHalfWidthIdentifier(Nothing)) Assert.Equal("ABC", SyntaxFacts.MakeHalfWidthIdentifier("ABC")) Assert.Equal(ChrW(65280), SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65280))) Assert.NotEqual(ChrW(65281), SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65281))) Assert.Equal(1, SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65281)).Length) End Sub End Class Module SyntaxDiagnosticInfoListExtensions <Extension> Public Function Count(list As SyntaxDiagnosticInfoList) As Integer Dim result = 0 For Each v In list result += 1 Next Return result End Function <Extension> Public Function First(list As SyntaxDiagnosticInfoList) As DiagnosticInfo For Each v In list Return v Next Throw New InvalidOperationException() End Function <Extension> Public Function ElementAt(list As SyntaxDiagnosticInfoList, index As Integer) As DiagnosticInfo Dim i = 0 For Each v In list If i = index Then Return v End If i += 1 Next Throw New IndexOutOfRangeException() End Function End Module
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Analyzers/VisualBasic/CodeFixes/SimplifyObjectCreation/VisualBasicSimplifyObjectCreationCodeFixProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.SimplifyObjectCreation <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.SimplifyObjectCreation), [Shared]> Friend Class VisualBasicSimplifyObjectCreationCodeFixProvider Inherits SyntaxEditorBasedCodeFixProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) = ImmutableArray.Create(IDEDiagnosticIds.SimplifyObjectCreationDiagnosticId) Friend Overrides ReadOnly Property CodeFixCategory As CodeFixCategory = CodeFixCategory.CodeStyle Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task For Each diagnostic In context.Diagnostics context.RegisterCodeFix(New MyCodeAction( VisualBasicCodeFixesResources.Simplify_object_creation, Function(ct) FixAsync(context.Document, diagnostic, ct)), diagnostic) Next Return Task.CompletedTask End Function Protected Overrides Async Function FixAllAsync(document As Document, diagnostics As ImmutableArray(Of Diagnostic), editor As SyntaxEditor, cancellationToken As CancellationToken) As Task Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) For Each diagnostic In diagnostics Dim node = DirectCast(root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie:=True), VariableDeclaratorSyntax) Dim asNewClause = SyntaxFactory.AsNewClause(node.AsClause.AsKeyword, DirectCast(node.Initializer.Value, NewExpressionSyntax)) Dim newNode = node.Update( names:=node.Names, asClause:=asNewClause, initializer:=Nothing) editor.ReplaceNode(node, newNode) Next End Function Private Class MyCodeAction Inherits CustomCodeActions.DocumentChangeAction Friend Sub New(title As String, createChangedDocument As Func(Of CancellationToken, Task(Of Document))) MyBase.New(title, createChangedDocument, NameOf(VisualBasicCodeFixesResources.Simplify_object_creation)) End Sub End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.SimplifyObjectCreation <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.SimplifyObjectCreation), [Shared]> Friend Class VisualBasicSimplifyObjectCreationCodeFixProvider Inherits SyntaxEditorBasedCodeFixProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) = ImmutableArray.Create(IDEDiagnosticIds.SimplifyObjectCreationDiagnosticId) Friend Overrides ReadOnly Property CodeFixCategory As CodeFixCategory = CodeFixCategory.CodeStyle Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task For Each diagnostic In context.Diagnostics context.RegisterCodeFix(New MyCodeAction( VisualBasicCodeFixesResources.Simplify_object_creation, Function(ct) FixAsync(context.Document, diagnostic, ct)), diagnostic) Next Return Task.CompletedTask End Function Protected Overrides Async Function FixAllAsync(document As Document, diagnostics As ImmutableArray(Of Diagnostic), editor As SyntaxEditor, cancellationToken As CancellationToken) As Task Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) For Each diagnostic In diagnostics Dim node = DirectCast(root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie:=True), VariableDeclaratorSyntax) Dim asNewClause = SyntaxFactory.AsNewClause(node.AsClause.AsKeyword, DirectCast(node.Initializer.Value, NewExpressionSyntax)) Dim newNode = node.Update( names:=node.Names, asClause:=asNewClause, initializer:=Nothing) editor.ReplaceNode(node, newNode) Next End Function Private Class MyCodeAction Inherits CustomCodeActions.DocumentChangeAction Friend Sub New(title As String, createChangedDocument As Func(Of CancellationToken, Task(Of Document))) MyBase.New(title, createChangedDocument, NameOf(VisualBasicCodeFixesResources.Simplify_object_creation)) End Sub End Class End Class End Namespace
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Workspaces/CSharp/Portable/Simplification/Reducers/CSharpNameReducer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CSharp.Simplification { internal partial class CSharpNameReducer : AbstractCSharpReducer { private static readonly ObjectPool<IReductionRewriter> s_pool = new( () => new Rewriter(s_pool)); public CSharpNameReducer() : base(s_pool) { } private static readonly Func<SyntaxNode, SemanticModel, OptionSet, CancellationToken, SyntaxNode> s_simplifyName = SimplifyName; private static SyntaxNode SimplifyName( SyntaxNode node, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) { SyntaxNode replacementNode; if (node.IsKind(SyntaxKind.QualifiedCref, out QualifiedCrefSyntax crefSyntax)) { if (!QualifiedCrefSimplifier.Instance.TrySimplify( crefSyntax, semanticModel, optionSet, out var crefReplacement, out _, cancellationToken)) { return node; } replacementNode = crefReplacement; } else { var expressionSyntax = (ExpressionSyntax)node; if (!ExpressionSimplifier.Instance.TrySimplify(expressionSyntax, semanticModel, optionSet, out var expressionReplacement, out _, cancellationToken)) { return node; } replacementNode = expressionReplacement; } node = node.CopyAnnotationsTo(replacementNode).WithAdditionalAnnotations(Formatter.Annotation); return node.WithoutAnnotations(Simplifier.Annotation); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CSharp.Simplification { internal partial class CSharpNameReducer : AbstractCSharpReducer { private static readonly ObjectPool<IReductionRewriter> s_pool = new( () => new Rewriter(s_pool)); public CSharpNameReducer() : base(s_pool) { } private static readonly Func<SyntaxNode, SemanticModel, OptionSet, CancellationToken, SyntaxNode> s_simplifyName = SimplifyName; private static SyntaxNode SimplifyName( SyntaxNode node, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) { SyntaxNode replacementNode; if (node.IsKind(SyntaxKind.QualifiedCref, out QualifiedCrefSyntax crefSyntax)) { if (!QualifiedCrefSimplifier.Instance.TrySimplify( crefSyntax, semanticModel, optionSet, out var crefReplacement, out _, cancellationToken)) { return node; } replacementNode = crefReplacement; } else { var expressionSyntax = (ExpressionSyntax)node; if (!ExpressionSimplifier.Instance.TrySimplify(expressionSyntax, semanticModel, optionSet, out var expressionReplacement, out _, cancellationToken)) { return node; } replacementNode = expressionReplacement; } node = node.CopyAnnotationsTo(replacementNode).WithAdditionalAnnotations(Formatter.Annotation); return node.WithoutAnnotations(Simplifier.Annotation); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Tools/BuildBoss/ProjectReferenceEntry.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Tasks; namespace BuildBoss { internal struct ProjectReferenceEntry { internal string FileName { get; } internal Guid? Project { get; } internal ProjectKey ProjectKey => new ProjectKey(FileName); internal ProjectReferenceEntry(string fileName, Guid? project) { FileName = fileName; Project = project; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Tasks; namespace BuildBoss { internal struct ProjectReferenceEntry { internal string FileName { get; } internal Guid? Project { get; } internal ProjectKey ProjectKey => new ProjectKey(FileName); internal ProjectReferenceEntry(string fileName, Guid? project) { FileName = fileName; Project = project; } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/VisualStudio/Core/Impl/CodeModel/MethodXml/AbstractMethodXmlBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Globalization; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml { internal abstract partial class AbstractMethodXmlBuilder { private const string ArgumentElementName = "Argument"; private const string ArrayElementName = "Array"; private const string ArrayElementAccessElementName = "ArrayElementAccess"; private const string ArrayTypeElementName = "ArrayType"; private const string AssignmentElementName = "Assignment"; private const string BaseReferenceElementName = "BaseReference"; private const string BinaryOperationElementName = "BinaryOperation"; private const string BlockElementName = "Block"; private const string BooleanElementName = "Boolean"; private const string BoundElementName = "Bound"; private const string CastElementName = "Cast"; private const string CharElementName = "Char"; private const string CommentElementName = "Comment"; private const string ExpressionElementName = "Expression"; private const string ExpressionStatementElementName = "ExpressionStatement"; private const string LiteralElementName = "Literal"; private const string LocalElementName = "Local"; private const string MethodCallElementName = "MethodCall"; private const string NameElementName = "Name"; private const string NameRefElementName = "NameRef"; private const string NewArrayElementName = "NewArray"; private const string NewClassElementName = "NewClass"; private const string NewDelegateElementName = "NewDelegate"; private const string NullElementName = "Null"; private const string NumberElementName = "Number"; private const string ParenthesesElementName = "Parentheses"; private const string QuoteElementName = "Quote"; private const string StringElementName = "String"; private const string ThisReferenceElementName = "ThisReference"; private const string TypeElementName = "Type"; private const string BinaryOperatorAttributeName = "binaryoperator"; private const string DirectCastAttributeName = "directcast"; private const string FullNameAttributeName = "fullname"; private const string ImplicitAttributeName = "implicit"; private const string LineAttributeName = "line"; private const string NameAttributeName = "name"; private const string RankAttributeName = "rank"; private const string TryCastAttributeName = "trycast"; private const string TypeAttributeName = "type"; private const string VariableKindAttributeName = "variablekind"; private static readonly char[] s_encodedChars = new[] { '<', '>', '&' }; private static readonly string[] s_encodings = new[] { "&lt;", "&gt;", "&amp;" }; private readonly StringBuilder _builder; protected readonly IMethodSymbol Symbol; protected readonly SemanticModel SemanticModel; protected readonly SourceText Text; protected AbstractMethodXmlBuilder(IMethodSymbol symbol, SemanticModel semanticModel) { _builder = new StringBuilder(); this.Symbol = symbol; this.SemanticModel = semanticModel; this.Text = semanticModel.SyntaxTree.GetText(); } public override string ToString() => _builder.ToString(); private void AppendEncoded(string text) { var length = text.Length; var startIndex = 0; int index; for (index = 0; index < length; index++) { var encodingIndex = Array.IndexOf(s_encodedChars, text[index]); if (encodingIndex >= 0) { if (index > startIndex) { _builder.Append(text, startIndex, index - startIndex); } _builder.Append(s_encodings[encodingIndex]); startIndex = index + 1; } } if (index > startIndex) { _builder.Append(text, startIndex, index - startIndex); } } private void AppendOpenTag(string name, AttributeInfo[] attributes) { _builder.Append('<'); _builder.Append(name); foreach (var attribute in attributes.Where(a => !a.IsEmpty)) { _builder.Append(' '); _builder.Append(attribute.Name); _builder.Append("=\""); AppendEncoded(attribute.Value); _builder.Append('"'); } _builder.Append('>'); } private void AppendCloseTag(string name) { _builder.Append("</"); _builder.Append(name); _builder.Append('>'); } private void AppendLeafTag(string name) { _builder.Append('<'); _builder.Append(name); _builder.Append("/>"); } private static string GetBinaryOperatorKindText(BinaryOperatorKind kind) => kind switch { BinaryOperatorKind.Plus => "plus", BinaryOperatorKind.BitwiseOr => "bitor", BinaryOperatorKind.BitwiseAnd => "bitand", BinaryOperatorKind.Concatenate => "concatenate", BinaryOperatorKind.AddDelegate => "adddelegate", _ => throw new InvalidOperationException("Invalid BinaryOperatorKind: " + kind.ToString()), }; private static string GetVariableKindText(VariableKind kind) => kind switch { VariableKind.Property => "property", VariableKind.Method => "method", VariableKind.Field => "field", VariableKind.Local => "local", VariableKind.Unknown => "unknown", _ => throw new InvalidOperationException("Invalid SymbolKind: " + kind.ToString()), }; private IDisposable Tag(string name, params AttributeInfo[] attributes) => new AutoTag(this, name, attributes); private AttributeInfo BinaryOperatorAttribute(BinaryOperatorKind kind) { if (kind == BinaryOperatorKind.None) { return AttributeInfo.Empty; } return new AttributeInfo(BinaryOperatorAttributeName, GetBinaryOperatorKindText(kind)); } private AttributeInfo FullNameAttribute(string name) { if (string.IsNullOrWhiteSpace(name)) { return AttributeInfo.Empty; } return new AttributeInfo(FullNameAttributeName, name); } private AttributeInfo ImplicitAttribute(bool? @implicit) { if (@implicit == null) { return AttributeInfo.Empty; } return new AttributeInfo(ImplicitAttributeName, @implicit.Value ? "yes" : "no"); } private AttributeInfo LineNumberAttribute(int lineNumber) => new AttributeInfo(LineAttributeName, lineNumber.ToString()); private AttributeInfo NameAttribute(string name) { if (string.IsNullOrWhiteSpace(name)) { return AttributeInfo.Empty; } return new AttributeInfo(NameAttributeName, name); } private AttributeInfo RankAttribute(int rank) => new AttributeInfo(RankAttributeName, rank.ToString()); private AttributeInfo SpecialCastKindAttribute(SpecialCastKind? specialCastKind = null) => specialCastKind switch { SpecialCastKind.DirectCast => new AttributeInfo(DirectCastAttributeName, "yes"), SpecialCastKind.TryCast => new AttributeInfo(TryCastAttributeName, "yes"), _ => AttributeInfo.Empty, }; private AttributeInfo TypeAttribute(string typeName) { if (string.IsNullOrWhiteSpace(typeName)) { return AttributeInfo.Empty; } return new AttributeInfo(TypeAttributeName, typeName); } private AttributeInfo VariableKindAttribute(VariableKind kind) { if (kind == VariableKind.None) { return AttributeInfo.Empty; } return new AttributeInfo(VariableKindAttributeName, GetVariableKindText(kind)); } protected IDisposable ArgumentTag() => Tag(ArgumentElementName); protected IDisposable ArrayElementAccessTag() => Tag(ArrayElementAccessElementName); protected IDisposable ArrayTag() => Tag(ArrayElementName); protected IDisposable ArrayTypeTag(int rank) => Tag(ArrayTypeElementName, RankAttribute(rank)); protected IDisposable AssignmentTag(BinaryOperatorKind kind = BinaryOperatorKind.None) => Tag(AssignmentElementName, BinaryOperatorAttribute(kind)); protected void BaseReferenceTag() => AppendLeafTag(BaseReferenceElementName); protected IDisposable BinaryOperationTag(BinaryOperatorKind kind) => Tag(BinaryOperationElementName, BinaryOperatorAttribute(kind)); protected IDisposable BlockTag() => Tag(BlockElementName); protected IDisposable BooleanTag() => Tag(BooleanElementName); protected IDisposable BoundTag() => Tag(BoundElementName); protected IDisposable CastTag(SpecialCastKind? specialCastKind = null) => Tag(CastElementName, SpecialCastKindAttribute(specialCastKind)); protected IDisposable CharTag() => Tag(CharElementName); protected IDisposable CommentTag() => Tag(CommentElementName); protected IDisposable ExpressionTag() => Tag(ExpressionElementName); protected IDisposable ExpressionStatementTag(int lineNumber) => Tag(ExpressionStatementElementName, LineNumberAttribute(lineNumber)); protected IDisposable LiteralTag() => Tag(LiteralElementName); protected IDisposable LocalTag(int lineNumber) => Tag(LocalElementName, LineNumberAttribute(lineNumber)); protected IDisposable MethodCallTag() => Tag(MethodCallElementName); protected IDisposable NameTag() => Tag(NameElementName); protected IDisposable NameRefTag(VariableKind kind, string name = null, string fullName = null) => Tag(NameRefElementName, VariableKindAttribute(kind), NameAttribute(name), FullNameAttribute(fullName)); protected IDisposable NewArrayTag() => Tag(NewArrayElementName); protected IDisposable NewClassTag() => Tag(NewClassElementName); protected IDisposable NewDelegateTag(string name) => Tag(NewDelegateElementName, NameAttribute(name)); protected void NullTag() => AppendLeafTag(NullElementName); protected IDisposable NumberTag(string typeName = null) => Tag(NumberElementName, TypeAttribute(typeName)); protected IDisposable ParenthesesTag() => Tag(ParenthesesElementName); protected IDisposable QuoteTag(int lineNumber) => Tag(QuoteElementName, LineNumberAttribute(lineNumber)); protected IDisposable StringTag() => Tag(StringElementName); protected void ThisReferenceTag() => AppendLeafTag(ThisReferenceElementName); protected IDisposable TypeTag(bool? @implicit = null) => Tag(TypeElementName, ImplicitAttribute(@implicit)); protected void LineBreak() => _builder.AppendLine(); protected void EncodedText(string text) => AppendEncoded(text); protected int GetMark() => _builder.Length; protected void Rewind(int mark) => _builder.Length = mark; protected virtual VariableKind GetVariableKind(ISymbol symbol) { if (symbol == null) { return VariableKind.Unknown; } switch (symbol.Kind) { case SymbolKind.Event: case SymbolKind.Field: return VariableKind.Field; case SymbolKind.Local: case SymbolKind.Parameter: return VariableKind.Local; case SymbolKind.Method: return VariableKind.Method; case SymbolKind.Property: return VariableKind.Property; default: throw new InvalidOperationException("Invalid symbol kind: " + symbol.Kind.ToString()); } } protected string GetTypeName(ITypeSymbol typeSymbol) => MetadataNameHelpers.GetMetadataName(typeSymbol); protected int GetLineNumber(SyntaxNode node) => Text.Lines.IndexOf(node.SpanStart); protected void GenerateUnknown(SyntaxNode node) { using (QuoteTag(GetLineNumber(node))) { EncodedText(node.ToString()); } } protected void GenerateName(string name) { using (NameTag()) { EncodedText(name); } } protected void GenerateType(ITypeSymbol type, bool? @implicit = null, bool assemblyQualify = false) { if (type.TypeKind == TypeKind.Array) { var arrayType = (IArrayTypeSymbol)type; using var tag = ArrayTypeTag(arrayType.Rank); GenerateType(arrayType.ElementType, @implicit, assemblyQualify); } else { using (TypeTag(@implicit)) { var typeName = assemblyQualify ? GetTypeName(type) + ", " + type.ContainingAssembly.ToDisplayString() : GetTypeName(type); EncodedText(typeName); } } } protected void GenerateType(SpecialType specialType) => GenerateType(SemanticModel.Compilation.GetSpecialType(specialType)); protected void GenerateNullLiteral() { using (LiteralTag()) { NullTag(); } } protected void GenerateNumber(object value, ITypeSymbol type) { using (NumberTag(GetTypeName(type))) { if (value is double d) { // Note: use G17 for doubles to ensure that we roundtrip properly on 64-bit EncodedText(d.ToString("G17", CultureInfo.InvariantCulture)); } else if (value is float f) { EncodedText(f.ToString("R", CultureInfo.InvariantCulture)); } else { EncodedText(Convert.ToString(value, CultureInfo.InvariantCulture)); } } } protected void GenerateNumber(object value, SpecialType specialType) => GenerateNumber(value, SemanticModel.Compilation.GetSpecialType(specialType)); protected void GenerateChar(char value) { using (CharTag()) { EncodedText(value.ToString()); } } protected void GenerateString(string value) { using (StringTag()) { EncodedText(value); } } protected void GenerateBoolean(bool value) { using (BooleanTag()) { EncodedText(value.ToString().ToLower()); } } protected void GenerateThisReference() => ThisReferenceTag(); protected void GenerateBaseReference() => BaseReferenceTag(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Globalization; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml { internal abstract partial class AbstractMethodXmlBuilder { private const string ArgumentElementName = "Argument"; private const string ArrayElementName = "Array"; private const string ArrayElementAccessElementName = "ArrayElementAccess"; private const string ArrayTypeElementName = "ArrayType"; private const string AssignmentElementName = "Assignment"; private const string BaseReferenceElementName = "BaseReference"; private const string BinaryOperationElementName = "BinaryOperation"; private const string BlockElementName = "Block"; private const string BooleanElementName = "Boolean"; private const string BoundElementName = "Bound"; private const string CastElementName = "Cast"; private const string CharElementName = "Char"; private const string CommentElementName = "Comment"; private const string ExpressionElementName = "Expression"; private const string ExpressionStatementElementName = "ExpressionStatement"; private const string LiteralElementName = "Literal"; private const string LocalElementName = "Local"; private const string MethodCallElementName = "MethodCall"; private const string NameElementName = "Name"; private const string NameRefElementName = "NameRef"; private const string NewArrayElementName = "NewArray"; private const string NewClassElementName = "NewClass"; private const string NewDelegateElementName = "NewDelegate"; private const string NullElementName = "Null"; private const string NumberElementName = "Number"; private const string ParenthesesElementName = "Parentheses"; private const string QuoteElementName = "Quote"; private const string StringElementName = "String"; private const string ThisReferenceElementName = "ThisReference"; private const string TypeElementName = "Type"; private const string BinaryOperatorAttributeName = "binaryoperator"; private const string DirectCastAttributeName = "directcast"; private const string FullNameAttributeName = "fullname"; private const string ImplicitAttributeName = "implicit"; private const string LineAttributeName = "line"; private const string NameAttributeName = "name"; private const string RankAttributeName = "rank"; private const string TryCastAttributeName = "trycast"; private const string TypeAttributeName = "type"; private const string VariableKindAttributeName = "variablekind"; private static readonly char[] s_encodedChars = new[] { '<', '>', '&' }; private static readonly string[] s_encodings = new[] { "&lt;", "&gt;", "&amp;" }; private readonly StringBuilder _builder; protected readonly IMethodSymbol Symbol; protected readonly SemanticModel SemanticModel; protected readonly SourceText Text; protected AbstractMethodXmlBuilder(IMethodSymbol symbol, SemanticModel semanticModel) { _builder = new StringBuilder(); this.Symbol = symbol; this.SemanticModel = semanticModel; this.Text = semanticModel.SyntaxTree.GetText(); } public override string ToString() => _builder.ToString(); private void AppendEncoded(string text) { var length = text.Length; var startIndex = 0; int index; for (index = 0; index < length; index++) { var encodingIndex = Array.IndexOf(s_encodedChars, text[index]); if (encodingIndex >= 0) { if (index > startIndex) { _builder.Append(text, startIndex, index - startIndex); } _builder.Append(s_encodings[encodingIndex]); startIndex = index + 1; } } if (index > startIndex) { _builder.Append(text, startIndex, index - startIndex); } } private void AppendOpenTag(string name, AttributeInfo[] attributes) { _builder.Append('<'); _builder.Append(name); foreach (var attribute in attributes.Where(a => !a.IsEmpty)) { _builder.Append(' '); _builder.Append(attribute.Name); _builder.Append("=\""); AppendEncoded(attribute.Value); _builder.Append('"'); } _builder.Append('>'); } private void AppendCloseTag(string name) { _builder.Append("</"); _builder.Append(name); _builder.Append('>'); } private void AppendLeafTag(string name) { _builder.Append('<'); _builder.Append(name); _builder.Append("/>"); } private static string GetBinaryOperatorKindText(BinaryOperatorKind kind) => kind switch { BinaryOperatorKind.Plus => "plus", BinaryOperatorKind.BitwiseOr => "bitor", BinaryOperatorKind.BitwiseAnd => "bitand", BinaryOperatorKind.Concatenate => "concatenate", BinaryOperatorKind.AddDelegate => "adddelegate", _ => throw new InvalidOperationException("Invalid BinaryOperatorKind: " + kind.ToString()), }; private static string GetVariableKindText(VariableKind kind) => kind switch { VariableKind.Property => "property", VariableKind.Method => "method", VariableKind.Field => "field", VariableKind.Local => "local", VariableKind.Unknown => "unknown", _ => throw new InvalidOperationException("Invalid SymbolKind: " + kind.ToString()), }; private IDisposable Tag(string name, params AttributeInfo[] attributes) => new AutoTag(this, name, attributes); private AttributeInfo BinaryOperatorAttribute(BinaryOperatorKind kind) { if (kind == BinaryOperatorKind.None) { return AttributeInfo.Empty; } return new AttributeInfo(BinaryOperatorAttributeName, GetBinaryOperatorKindText(kind)); } private AttributeInfo FullNameAttribute(string name) { if (string.IsNullOrWhiteSpace(name)) { return AttributeInfo.Empty; } return new AttributeInfo(FullNameAttributeName, name); } private AttributeInfo ImplicitAttribute(bool? @implicit) { if (@implicit == null) { return AttributeInfo.Empty; } return new AttributeInfo(ImplicitAttributeName, @implicit.Value ? "yes" : "no"); } private AttributeInfo LineNumberAttribute(int lineNumber) => new AttributeInfo(LineAttributeName, lineNumber.ToString()); private AttributeInfo NameAttribute(string name) { if (string.IsNullOrWhiteSpace(name)) { return AttributeInfo.Empty; } return new AttributeInfo(NameAttributeName, name); } private AttributeInfo RankAttribute(int rank) => new AttributeInfo(RankAttributeName, rank.ToString()); private AttributeInfo SpecialCastKindAttribute(SpecialCastKind? specialCastKind = null) => specialCastKind switch { SpecialCastKind.DirectCast => new AttributeInfo(DirectCastAttributeName, "yes"), SpecialCastKind.TryCast => new AttributeInfo(TryCastAttributeName, "yes"), _ => AttributeInfo.Empty, }; private AttributeInfo TypeAttribute(string typeName) { if (string.IsNullOrWhiteSpace(typeName)) { return AttributeInfo.Empty; } return new AttributeInfo(TypeAttributeName, typeName); } private AttributeInfo VariableKindAttribute(VariableKind kind) { if (kind == VariableKind.None) { return AttributeInfo.Empty; } return new AttributeInfo(VariableKindAttributeName, GetVariableKindText(kind)); } protected IDisposable ArgumentTag() => Tag(ArgumentElementName); protected IDisposable ArrayElementAccessTag() => Tag(ArrayElementAccessElementName); protected IDisposable ArrayTag() => Tag(ArrayElementName); protected IDisposable ArrayTypeTag(int rank) => Tag(ArrayTypeElementName, RankAttribute(rank)); protected IDisposable AssignmentTag(BinaryOperatorKind kind = BinaryOperatorKind.None) => Tag(AssignmentElementName, BinaryOperatorAttribute(kind)); protected void BaseReferenceTag() => AppendLeafTag(BaseReferenceElementName); protected IDisposable BinaryOperationTag(BinaryOperatorKind kind) => Tag(BinaryOperationElementName, BinaryOperatorAttribute(kind)); protected IDisposable BlockTag() => Tag(BlockElementName); protected IDisposable BooleanTag() => Tag(BooleanElementName); protected IDisposable BoundTag() => Tag(BoundElementName); protected IDisposable CastTag(SpecialCastKind? specialCastKind = null) => Tag(CastElementName, SpecialCastKindAttribute(specialCastKind)); protected IDisposable CharTag() => Tag(CharElementName); protected IDisposable CommentTag() => Tag(CommentElementName); protected IDisposable ExpressionTag() => Tag(ExpressionElementName); protected IDisposable ExpressionStatementTag(int lineNumber) => Tag(ExpressionStatementElementName, LineNumberAttribute(lineNumber)); protected IDisposable LiteralTag() => Tag(LiteralElementName); protected IDisposable LocalTag(int lineNumber) => Tag(LocalElementName, LineNumberAttribute(lineNumber)); protected IDisposable MethodCallTag() => Tag(MethodCallElementName); protected IDisposable NameTag() => Tag(NameElementName); protected IDisposable NameRefTag(VariableKind kind, string name = null, string fullName = null) => Tag(NameRefElementName, VariableKindAttribute(kind), NameAttribute(name), FullNameAttribute(fullName)); protected IDisposable NewArrayTag() => Tag(NewArrayElementName); protected IDisposable NewClassTag() => Tag(NewClassElementName); protected IDisposable NewDelegateTag(string name) => Tag(NewDelegateElementName, NameAttribute(name)); protected void NullTag() => AppendLeafTag(NullElementName); protected IDisposable NumberTag(string typeName = null) => Tag(NumberElementName, TypeAttribute(typeName)); protected IDisposable ParenthesesTag() => Tag(ParenthesesElementName); protected IDisposable QuoteTag(int lineNumber) => Tag(QuoteElementName, LineNumberAttribute(lineNumber)); protected IDisposable StringTag() => Tag(StringElementName); protected void ThisReferenceTag() => AppendLeafTag(ThisReferenceElementName); protected IDisposable TypeTag(bool? @implicit = null) => Tag(TypeElementName, ImplicitAttribute(@implicit)); protected void LineBreak() => _builder.AppendLine(); protected void EncodedText(string text) => AppendEncoded(text); protected int GetMark() => _builder.Length; protected void Rewind(int mark) => _builder.Length = mark; protected virtual VariableKind GetVariableKind(ISymbol symbol) { if (symbol == null) { return VariableKind.Unknown; } switch (symbol.Kind) { case SymbolKind.Event: case SymbolKind.Field: return VariableKind.Field; case SymbolKind.Local: case SymbolKind.Parameter: return VariableKind.Local; case SymbolKind.Method: return VariableKind.Method; case SymbolKind.Property: return VariableKind.Property; default: throw new InvalidOperationException("Invalid symbol kind: " + symbol.Kind.ToString()); } } protected string GetTypeName(ITypeSymbol typeSymbol) => MetadataNameHelpers.GetMetadataName(typeSymbol); protected int GetLineNumber(SyntaxNode node) => Text.Lines.IndexOf(node.SpanStart); protected void GenerateUnknown(SyntaxNode node) { using (QuoteTag(GetLineNumber(node))) { EncodedText(node.ToString()); } } protected void GenerateName(string name) { using (NameTag()) { EncodedText(name); } } protected void GenerateType(ITypeSymbol type, bool? @implicit = null, bool assemblyQualify = false) { if (type.TypeKind == TypeKind.Array) { var arrayType = (IArrayTypeSymbol)type; using var tag = ArrayTypeTag(arrayType.Rank); GenerateType(arrayType.ElementType, @implicit, assemblyQualify); } else { using (TypeTag(@implicit)) { var typeName = assemblyQualify ? GetTypeName(type) + ", " + type.ContainingAssembly.ToDisplayString() : GetTypeName(type); EncodedText(typeName); } } } protected void GenerateType(SpecialType specialType) => GenerateType(SemanticModel.Compilation.GetSpecialType(specialType)); protected void GenerateNullLiteral() { using (LiteralTag()) { NullTag(); } } protected void GenerateNumber(object value, ITypeSymbol type) { using (NumberTag(GetTypeName(type))) { if (value is double d) { // Note: use G17 for doubles to ensure that we roundtrip properly on 64-bit EncodedText(d.ToString("G17", CultureInfo.InvariantCulture)); } else if (value is float f) { EncodedText(f.ToString("R", CultureInfo.InvariantCulture)); } else { EncodedText(Convert.ToString(value, CultureInfo.InvariantCulture)); } } } protected void GenerateNumber(object value, SpecialType specialType) => GenerateNumber(value, SemanticModel.Compilation.GetSpecialType(specialType)); protected void GenerateChar(char value) { using (CharTag()) { EncodedText(value.ToString()); } } protected void GenerateString(string value) { using (StringTag()) { EncodedText(value); } } protected void GenerateBoolean(bool value) { using (BooleanTag()) { EncodedText(value.ToString().ToLower()); } } protected void GenerateThisReference() => ThisReferenceTag(); protected void GenerateBaseReference() => BaseReferenceTag(); } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/Core/Portable/DiaSymReader/Metadata/IMetadataEmit.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #pragma warning disable 436 // SuppressUnmanagedCodeSecurityAttribute defined in source and mscorlib using System; using System.Runtime.InteropServices; using System.Security; namespace Microsoft.DiaSymReader { [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("BA3FEE4C-ECB9-4e41-83B7-183FA41CD859")] [SuppressUnmanagedCodeSecurity] internal unsafe interface IMetadataEmit { // SymWriter doesn't use any methods from this interface except for GetTokenFromSig, which is only called when // DefineLocalVariable(2) and DefineConstant(2) don't specify signature token, or the token is nil. void __SetModuleProps(); void __Save(); void __SaveToStream(); void __GetSaveSize(); void __DefineTypeDef(); void __DefineNestedType(); void __SetHandler(); void __DefineMethod(); void __DefineMethodImpl(); void __DefineTypeRefByName(); void __DefineImportType(); void __DefineMemberRef(); void __DefineImportMember(); void __DefineEvent(); void __SetClassLayout(); void __DeleteClassLayout(); void __SetFieldMarshal(); void __DeleteFieldMarshal(); void __DefinePermissionSet(); void __SetRVA(); int GetTokenFromSig(byte* voidPointerSig, int byteCountSig); void __DefineModuleRef(); void __SetParent(); void __GetTokenFromTypeSpec(); void __SaveToMemory(); void __DefineUserString(); void __DeleteToken(); void __SetMethodProps(); void __SetTypeDefProps(); void __SetEventProps(); void __SetPermissionSetProps(); void __DefinePinvokeMap(); void __SetPinvokeMap(); void __DeletePinvokeMap(); void __DefineCustomAttribute(); void __SetCustomAttributeValue(); void __DefineField(); void __DefineProperty(); void __DefineParam(); void __SetFieldProps(); void __SetPropertyProps(); void __SetParamProps(); void __DefineSecurityAttributeSet(); void __ApplyEditAndContinue(); void __TranslateSigWithScope(); void __SetMethodImplFlags(); void __SetFieldRVA(); void __Merge(); void __MergeEnd(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #pragma warning disable 436 // SuppressUnmanagedCodeSecurityAttribute defined in source and mscorlib using System; using System.Runtime.InteropServices; using System.Security; namespace Microsoft.DiaSymReader { [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("BA3FEE4C-ECB9-4e41-83B7-183FA41CD859")] [SuppressUnmanagedCodeSecurity] internal unsafe interface IMetadataEmit { // SymWriter doesn't use any methods from this interface except for GetTokenFromSig, which is only called when // DefineLocalVariable(2) and DefineConstant(2) don't specify signature token, or the token is nil. void __SetModuleProps(); void __Save(); void __SaveToStream(); void __GetSaveSize(); void __DefineTypeDef(); void __DefineNestedType(); void __SetHandler(); void __DefineMethod(); void __DefineMethodImpl(); void __DefineTypeRefByName(); void __DefineImportType(); void __DefineMemberRef(); void __DefineImportMember(); void __DefineEvent(); void __SetClassLayout(); void __DeleteClassLayout(); void __SetFieldMarshal(); void __DeleteFieldMarshal(); void __DefinePermissionSet(); void __SetRVA(); int GetTokenFromSig(byte* voidPointerSig, int byteCountSig); void __DefineModuleRef(); void __SetParent(); void __GetTokenFromTypeSpec(); void __SaveToMemory(); void __DefineUserString(); void __DeleteToken(); void __SetMethodProps(); void __SetTypeDefProps(); void __SetEventProps(); void __SetPermissionSetProps(); void __DefinePinvokeMap(); void __SetPinvokeMap(); void __DeletePinvokeMap(); void __DefineCustomAttribute(); void __SetCustomAttributeValue(); void __DefineField(); void __DefineProperty(); void __DefineParam(); void __SetFieldProps(); void __SetPropertyProps(); void __SetParamProps(); void __DefineSecurityAttributeSet(); void __ApplyEditAndContinue(); void __TranslateSigWithScope(); void __SetMethodImplFlags(); void __SetFieldRVA(); void __Merge(); void __MergeEnd(); } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Workspaces/Core/Portable/Storage/AbstractPersistentStorageService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Storage { /// <summary> /// A service that enables storing and retrieving of information associated with solutions, /// projects or documents across runtime sessions. /// </summary> internal abstract partial class AbstractPersistentStorageService : IChecksummedPersistentStorageService { private readonly IPersistentStorageLocationService _locationService; /// <summary> /// This lock guards all mutable fields in this type. /// </summary> private readonly SemaphoreSlim _lock = new(initialCount: 1); private ReferenceCountedDisposable<IChecksummedPersistentStorage>? _currentPersistentStorage; private SolutionId? _currentPersistentStorageSolutionId; protected AbstractPersistentStorageService(IPersistentStorageLocationService locationService) => _locationService = locationService; protected abstract string GetDatabaseFilePath(string workingFolderPath); /// <summary> /// Can throw. If it does, the caller (<see cref="CreatePersistentStorageAsync"/>) will attempt /// to delete the database and retry opening one more time. If that fails again, the <see /// cref="NoOpPersistentStorage"/> instance will be used. /// </summary> protected abstract ValueTask<IChecksummedPersistentStorage?> TryOpenDatabaseAsync(SolutionKey solutionKey, string workingFolderPath, string databaseFilePath, CancellationToken cancellationToken); protected abstract bool ShouldDeleteDatabase(Exception exception); [Obsolete("Use GetStorageAsync instead")] IPersistentStorage IPersistentStorageService.GetStorage(Solution solution) => GetStorageAsync(solution.Workspace, SolutionKey.ToSolutionKey(solution), solution, checkBranchId: true, CancellationToken.None).AsTask().GetAwaiter().GetResult(); async ValueTask<IPersistentStorage> IPersistentStorageService.GetStorageAsync(Solution solution, CancellationToken cancellationToken) => await GetStorageAsync(solution.Workspace, SolutionKey.ToSolutionKey(solution), solution, checkBranchId: true, cancellationToken).ConfigureAwait(false); public ValueTask<IChecksummedPersistentStorage> GetStorageAsync(Solution solution, CancellationToken cancellationToken) => GetStorageAsync(solution.Workspace, SolutionKey.ToSolutionKey(solution), solution, checkBranchId: true, cancellationToken); public ValueTask<IChecksummedPersistentStorage> GetStorageAsync(Solution solution, bool checkBranchId, CancellationToken cancellationToken) => GetStorageAsync(solution.Workspace, SolutionKey.ToSolutionKey(solution), solution, checkBranchId, cancellationToken); public ValueTask<IChecksummedPersistentStorage> GetStorageAsync(Workspace workspace, SolutionKey solutionKey, bool checkBranchId, CancellationToken cancellationToken) => GetStorageAsync(workspace, solutionKey, bulkLoadSnapshot: null, checkBranchId, cancellationToken); public ValueTask<IChecksummedPersistentStorage> GetStorageAsync( Workspace workspace, SolutionKey solutionKey, Solution? bulkLoadSnapshot, bool checkBranchId, CancellationToken cancellationToken) { if (!DatabaseSupported(solutionKey, checkBranchId)) return new(NoOpPersistentStorage.GetOrThrow(workspace.Options)); return GetStorageWorkerAsync(workspace, solutionKey, bulkLoadSnapshot, cancellationToken); } internal async ValueTask<IChecksummedPersistentStorage> GetStorageWorkerAsync( Workspace workspace, SolutionKey solutionKey, Solution? bulkLoadSnapshot, CancellationToken cancellationToken) { using (await _lock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { // Do we already have storage for this? if (solutionKey.Id == _currentPersistentStorageSolutionId) { // We do, great. Increment our ref count for our caller. They'll decrement it // when done with it. return PersistentStorageReferenceCountedDisposableWrapper.AddReferenceCountToAndCreateWrapper(_currentPersistentStorage!); } var workingFolder = TryGetWorkingFolder(workspace, solutionKey, bulkLoadSnapshot); if (workingFolder == null) return NoOpPersistentStorage.GetOrThrow(workspace.Options); // If we already had some previous cached service, let's let it start cleaning up if (_currentPersistentStorage != null) { var storageToDispose = _currentPersistentStorage; // Kick off a task to actually go dispose the previous cached storage instance. // This will remove the single ref count we ourselves added when we cached the // instance. Then once all other existing clients who are holding onto this // instance let go, it will finally get truly disposed. // This operation is not safe to cancel (as dispose must happen). _ = Task.Run(() => storageToDispose.Dispose(), CancellationToken.None); _currentPersistentStorage = null; _currentPersistentStorageSolutionId = null; } var storage = await CreatePersistentStorageAsync(workspace, solutionKey, workingFolder, cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(storage); // Create and cache a new storage instance associated with this particular solution. // It will initially have a ref-count of 1 due to our reference to it. _currentPersistentStorage = new ReferenceCountedDisposable<IChecksummedPersistentStorage>(storage); _currentPersistentStorageSolutionId = solutionKey.Id; // Now increment the reference count and return to our caller. The current ref // count for this instance will be 2. Until all the callers *and* us decrement // the refcounts, this instance will not be actually disposed. return PersistentStorageReferenceCountedDisposableWrapper.AddReferenceCountToAndCreateWrapper(_currentPersistentStorage); } } private string? TryGetWorkingFolder(Workspace workspace, SolutionKey solutionKey, Solution? bulkLoadSnapshot) { // First, see if we have the new API that just operates on a Workspace/Key. If so, use that. if (_locationService is IPersistentStorageLocationService2 locationService2) return locationService2.TryGetStorageLocation(workspace, solutionKey); // Otherwise, use the existing API. However, that API only works if we have a full Solution to pass it. if (bulkLoadSnapshot == null) return null; return _locationService.TryGetStorageLocation(bulkLoadSnapshot); } private static bool DatabaseSupported(SolutionKey solution, bool checkBranchId) { if (solution.FilePath == null) { return false; } if (checkBranchId && !solution.IsPrimaryBranch) { // we only use database for primary solution. (Ex, forked solution will not use database) return false; } return true; } private async ValueTask<IChecksummedPersistentStorage> CreatePersistentStorageAsync( Workspace workspace, SolutionKey solutionKey, string workingFolderPath, CancellationToken cancellationToken) { // Attempt to create the database up to two times. The first time we may encounter // some sort of issue (like DB corruption). We'll then try to delete the DB and can // try to create it again. If we can't create it the second time, then there's nothing // we can do and we have to store things in memory. var result = await TryCreatePersistentStorageAsync(workspace, solutionKey, workingFolderPath, cancellationToken).ConfigureAwait(false) ?? await TryCreatePersistentStorageAsync(workspace, solutionKey, workingFolderPath, cancellationToken).ConfigureAwait(false); if (result != null) return result; return NoOpPersistentStorage.GetOrThrow(workspace.Options); } private async ValueTask<IChecksummedPersistentStorage?> TryCreatePersistentStorageAsync( Workspace workspace, SolutionKey solutionKey, string workingFolderPath, CancellationToken cancellationToken) { var databaseFilePath = GetDatabaseFilePath(workingFolderPath); try { return await TryOpenDatabaseAsync(solutionKey, workingFolderPath, databaseFilePath, cancellationToken).ConfigureAwait(false); } catch (Exception ex) { StorageDatabaseLogger.LogException(ex); if (ShouldDeleteDatabase(ex)) { // this was not a normal exception that we expected during DB open. // Report this so we can try to address whatever is causing this. FatalError.ReportAndCatch(ex); IOUtilities.PerformIO(() => Directory.Delete(Path.GetDirectoryName(databaseFilePath)!, recursive: true)); } if (workspace.Options.GetOption(StorageOptions.DatabaseMustSucceed)) throw; return null; } } private void Shutdown() { ReferenceCountedDisposable<IChecksummedPersistentStorage>? storage = null; lock (_lock) { // We will transfer ownership in a thread-safe way out so we can dispose outside the lock storage = _currentPersistentStorage; _currentPersistentStorage = null; _currentPersistentStorageSolutionId = null; } if (storage != null) { // Dispose storage outside of the lock. Note this only removes our reference count; clients who are still // using this will still be holding a reference count. storage.Dispose(); } } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly AbstractPersistentStorageService _service; public TestAccessor(AbstractPersistentStorageService service) => _service = service; public void Shutdown() => _service.Shutdown(); } /// <summary> /// A trivial wrapper that we can hand out for instances from the <see cref="AbstractPersistentStorageService"/> /// that wraps the underlying <see cref="IPersistentStorage"/> singleton. /// </summary> private sealed class PersistentStorageReferenceCountedDisposableWrapper : IChecksummedPersistentStorage { private readonly ReferenceCountedDisposable<IChecksummedPersistentStorage> _storage; private PersistentStorageReferenceCountedDisposableWrapper(ReferenceCountedDisposable<IChecksummedPersistentStorage> storage) => _storage = storage; public static IChecksummedPersistentStorage AddReferenceCountToAndCreateWrapper(ReferenceCountedDisposable<IChecksummedPersistentStorage> storage) { // This should only be called from a caller that has a non-null storage that it // already has a reference on. So .TryAddReference cannot fail. return new PersistentStorageReferenceCountedDisposableWrapper(storage.TryAddReference() ?? throw ExceptionUtilities.Unreachable); } public void Dispose() => _storage.Dispose(); public ValueTask DisposeAsync() => _storage.DisposeAsync(); public Task<bool> ChecksumMatchesAsync(string name, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.ChecksumMatchesAsync(name, checksum, cancellationToken); public Task<bool> ChecksumMatchesAsync(Project project, string name, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.ChecksumMatchesAsync(project, name, checksum, cancellationToken); public Task<bool> ChecksumMatchesAsync(Document document, string name, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.ChecksumMatchesAsync(document, name, checksum, cancellationToken); public Task<bool> ChecksumMatchesAsync(ProjectKey project, string name, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.ChecksumMatchesAsync(project, name, checksum, cancellationToken); public Task<bool> ChecksumMatchesAsync(DocumentKey document, string name, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.ChecksumMatchesAsync(document, name, checksum, cancellationToken); public Task<Stream?> ReadStreamAsync(string name, CancellationToken cancellationToken) => _storage.Target.ReadStreamAsync(name, cancellationToken); public Task<Stream?> ReadStreamAsync(Project project, string name, CancellationToken cancellationToken) => _storage.Target.ReadStreamAsync(project, name, cancellationToken); public Task<Stream?> ReadStreamAsync(Document document, string name, CancellationToken cancellationToken) => _storage.Target.ReadStreamAsync(document, name, cancellationToken); public Task<Stream> ReadStreamAsync(string name, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.ReadStreamAsync(name, checksum, cancellationToken); public Task<Stream> ReadStreamAsync(Project project, string name, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.ReadStreamAsync(project, name, checksum, cancellationToken); public Task<Stream> ReadStreamAsync(Document document, string name, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.ReadStreamAsync(document, name, checksum, cancellationToken); public Task<Stream> ReadStreamAsync(ProjectKey project, string name, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.ReadStreamAsync(project, name, checksum, cancellationToken); public Task<Stream> ReadStreamAsync(DocumentKey document, string name, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.ReadStreamAsync(document, name, checksum, cancellationToken); public Task<bool> WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken) => _storage.Target.WriteStreamAsync(name, stream, cancellationToken); public Task<bool> WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken) => _storage.Target.WriteStreamAsync(project, name, stream, cancellationToken); public Task<bool> WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken) => _storage.Target.WriteStreamAsync(document, name, stream, cancellationToken); public Task<bool> WriteStreamAsync(string name, Stream stream, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.WriteStreamAsync(name, stream, checksum, cancellationToken); public Task<bool> WriteStreamAsync(Project project, string name, Stream stream, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.WriteStreamAsync(project, name, stream, checksum, cancellationToken); public Task<bool> WriteStreamAsync(Document document, string name, Stream stream, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.WriteStreamAsync(document, name, stream, checksum, cancellationToken); public Task<bool> WriteStreamAsync(ProjectKey projectKey, string name, Stream stream, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.WriteStreamAsync(projectKey, name, stream, checksum, cancellationToken); public Task<bool> WriteStreamAsync(DocumentKey documentKey, string name, Stream stream, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.WriteStreamAsync(documentKey, name, stream, checksum, 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.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Storage { /// <summary> /// A service that enables storing and retrieving of information associated with solutions, /// projects or documents across runtime sessions. /// </summary> internal abstract partial class AbstractPersistentStorageService : IChecksummedPersistentStorageService { private readonly IPersistentStorageLocationService _locationService; /// <summary> /// This lock guards all mutable fields in this type. /// </summary> private readonly SemaphoreSlim _lock = new(initialCount: 1); private ReferenceCountedDisposable<IChecksummedPersistentStorage>? _currentPersistentStorage; private SolutionId? _currentPersistentStorageSolutionId; protected AbstractPersistentStorageService(IPersistentStorageLocationService locationService) => _locationService = locationService; protected abstract string GetDatabaseFilePath(string workingFolderPath); /// <summary> /// Can throw. If it does, the caller (<see cref="CreatePersistentStorageAsync"/>) will attempt /// to delete the database and retry opening one more time. If that fails again, the <see /// cref="NoOpPersistentStorage"/> instance will be used. /// </summary> protected abstract ValueTask<IChecksummedPersistentStorage?> TryOpenDatabaseAsync(SolutionKey solutionKey, string workingFolderPath, string databaseFilePath, CancellationToken cancellationToken); protected abstract bool ShouldDeleteDatabase(Exception exception); [Obsolete("Use GetStorageAsync instead")] IPersistentStorage IPersistentStorageService.GetStorage(Solution solution) => GetStorageAsync(solution.Workspace, SolutionKey.ToSolutionKey(solution), solution, checkBranchId: true, CancellationToken.None).AsTask().GetAwaiter().GetResult(); async ValueTask<IPersistentStorage> IPersistentStorageService.GetStorageAsync(Solution solution, CancellationToken cancellationToken) => await GetStorageAsync(solution.Workspace, SolutionKey.ToSolutionKey(solution), solution, checkBranchId: true, cancellationToken).ConfigureAwait(false); public ValueTask<IChecksummedPersistentStorage> GetStorageAsync(Solution solution, CancellationToken cancellationToken) => GetStorageAsync(solution.Workspace, SolutionKey.ToSolutionKey(solution), solution, checkBranchId: true, cancellationToken); public ValueTask<IChecksummedPersistentStorage> GetStorageAsync(Solution solution, bool checkBranchId, CancellationToken cancellationToken) => GetStorageAsync(solution.Workspace, SolutionKey.ToSolutionKey(solution), solution, checkBranchId, cancellationToken); public ValueTask<IChecksummedPersistentStorage> GetStorageAsync(Workspace workspace, SolutionKey solutionKey, bool checkBranchId, CancellationToken cancellationToken) => GetStorageAsync(workspace, solutionKey, bulkLoadSnapshot: null, checkBranchId, cancellationToken); public ValueTask<IChecksummedPersistentStorage> GetStorageAsync( Workspace workspace, SolutionKey solutionKey, Solution? bulkLoadSnapshot, bool checkBranchId, CancellationToken cancellationToken) { if (!DatabaseSupported(solutionKey, checkBranchId)) return new(NoOpPersistentStorage.GetOrThrow(workspace.Options)); return GetStorageWorkerAsync(workspace, solutionKey, bulkLoadSnapshot, cancellationToken); } internal async ValueTask<IChecksummedPersistentStorage> GetStorageWorkerAsync( Workspace workspace, SolutionKey solutionKey, Solution? bulkLoadSnapshot, CancellationToken cancellationToken) { using (await _lock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { // Do we already have storage for this? if (solutionKey.Id == _currentPersistentStorageSolutionId) { // We do, great. Increment our ref count for our caller. They'll decrement it // when done with it. return PersistentStorageReferenceCountedDisposableWrapper.AddReferenceCountToAndCreateWrapper(_currentPersistentStorage!); } var workingFolder = TryGetWorkingFolder(workspace, solutionKey, bulkLoadSnapshot); if (workingFolder == null) return NoOpPersistentStorage.GetOrThrow(workspace.Options); // If we already had some previous cached service, let's let it start cleaning up if (_currentPersistentStorage != null) { var storageToDispose = _currentPersistentStorage; // Kick off a task to actually go dispose the previous cached storage instance. // This will remove the single ref count we ourselves added when we cached the // instance. Then once all other existing clients who are holding onto this // instance let go, it will finally get truly disposed. // This operation is not safe to cancel (as dispose must happen). _ = Task.Run(() => storageToDispose.Dispose(), CancellationToken.None); _currentPersistentStorage = null; _currentPersistentStorageSolutionId = null; } var storage = await CreatePersistentStorageAsync(workspace, solutionKey, workingFolder, cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(storage); // Create and cache a new storage instance associated with this particular solution. // It will initially have a ref-count of 1 due to our reference to it. _currentPersistentStorage = new ReferenceCountedDisposable<IChecksummedPersistentStorage>(storage); _currentPersistentStorageSolutionId = solutionKey.Id; // Now increment the reference count and return to our caller. The current ref // count for this instance will be 2. Until all the callers *and* us decrement // the refcounts, this instance will not be actually disposed. return PersistentStorageReferenceCountedDisposableWrapper.AddReferenceCountToAndCreateWrapper(_currentPersistentStorage); } } private string? TryGetWorkingFolder(Workspace workspace, SolutionKey solutionKey, Solution? bulkLoadSnapshot) { // First, see if we have the new API that just operates on a Workspace/Key. If so, use that. if (_locationService is IPersistentStorageLocationService2 locationService2) return locationService2.TryGetStorageLocation(workspace, solutionKey); // Otherwise, use the existing API. However, that API only works if we have a full Solution to pass it. if (bulkLoadSnapshot == null) return null; return _locationService.TryGetStorageLocation(bulkLoadSnapshot); } private static bool DatabaseSupported(SolutionKey solution, bool checkBranchId) { if (solution.FilePath == null) { return false; } if (checkBranchId && !solution.IsPrimaryBranch) { // we only use database for primary solution. (Ex, forked solution will not use database) return false; } return true; } private async ValueTask<IChecksummedPersistentStorage> CreatePersistentStorageAsync( Workspace workspace, SolutionKey solutionKey, string workingFolderPath, CancellationToken cancellationToken) { // Attempt to create the database up to two times. The first time we may encounter // some sort of issue (like DB corruption). We'll then try to delete the DB and can // try to create it again. If we can't create it the second time, then there's nothing // we can do and we have to store things in memory. var result = await TryCreatePersistentStorageAsync(workspace, solutionKey, workingFolderPath, cancellationToken).ConfigureAwait(false) ?? await TryCreatePersistentStorageAsync(workspace, solutionKey, workingFolderPath, cancellationToken).ConfigureAwait(false); if (result != null) return result; return NoOpPersistentStorage.GetOrThrow(workspace.Options); } private async ValueTask<IChecksummedPersistentStorage?> TryCreatePersistentStorageAsync( Workspace workspace, SolutionKey solutionKey, string workingFolderPath, CancellationToken cancellationToken) { var databaseFilePath = GetDatabaseFilePath(workingFolderPath); try { return await TryOpenDatabaseAsync(solutionKey, workingFolderPath, databaseFilePath, cancellationToken).ConfigureAwait(false); } catch (Exception ex) { StorageDatabaseLogger.LogException(ex); if (ShouldDeleteDatabase(ex)) { // this was not a normal exception that we expected during DB open. // Report this so we can try to address whatever is causing this. FatalError.ReportAndCatch(ex); IOUtilities.PerformIO(() => Directory.Delete(Path.GetDirectoryName(databaseFilePath)!, recursive: true)); } if (workspace.Options.GetOption(StorageOptions.DatabaseMustSucceed)) throw; return null; } } private void Shutdown() { ReferenceCountedDisposable<IChecksummedPersistentStorage>? storage = null; lock (_lock) { // We will transfer ownership in a thread-safe way out so we can dispose outside the lock storage = _currentPersistentStorage; _currentPersistentStorage = null; _currentPersistentStorageSolutionId = null; } if (storage != null) { // Dispose storage outside of the lock. Note this only removes our reference count; clients who are still // using this will still be holding a reference count. storage.Dispose(); } } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly AbstractPersistentStorageService _service; public TestAccessor(AbstractPersistentStorageService service) => _service = service; public void Shutdown() => _service.Shutdown(); } /// <summary> /// A trivial wrapper that we can hand out for instances from the <see cref="AbstractPersistentStorageService"/> /// that wraps the underlying <see cref="IPersistentStorage"/> singleton. /// </summary> private sealed class PersistentStorageReferenceCountedDisposableWrapper : IChecksummedPersistentStorage { private readonly ReferenceCountedDisposable<IChecksummedPersistentStorage> _storage; private PersistentStorageReferenceCountedDisposableWrapper(ReferenceCountedDisposable<IChecksummedPersistentStorage> storage) => _storage = storage; public static IChecksummedPersistentStorage AddReferenceCountToAndCreateWrapper(ReferenceCountedDisposable<IChecksummedPersistentStorage> storage) { // This should only be called from a caller that has a non-null storage that it // already has a reference on. So .TryAddReference cannot fail. return new PersistentStorageReferenceCountedDisposableWrapper(storage.TryAddReference() ?? throw ExceptionUtilities.Unreachable); } public void Dispose() => _storage.Dispose(); public ValueTask DisposeAsync() => _storage.DisposeAsync(); public Task<bool> ChecksumMatchesAsync(string name, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.ChecksumMatchesAsync(name, checksum, cancellationToken); public Task<bool> ChecksumMatchesAsync(Project project, string name, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.ChecksumMatchesAsync(project, name, checksum, cancellationToken); public Task<bool> ChecksumMatchesAsync(Document document, string name, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.ChecksumMatchesAsync(document, name, checksum, cancellationToken); public Task<bool> ChecksumMatchesAsync(ProjectKey project, string name, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.ChecksumMatchesAsync(project, name, checksum, cancellationToken); public Task<bool> ChecksumMatchesAsync(DocumentKey document, string name, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.ChecksumMatchesAsync(document, name, checksum, cancellationToken); public Task<Stream?> ReadStreamAsync(string name, CancellationToken cancellationToken) => _storage.Target.ReadStreamAsync(name, cancellationToken); public Task<Stream?> ReadStreamAsync(Project project, string name, CancellationToken cancellationToken) => _storage.Target.ReadStreamAsync(project, name, cancellationToken); public Task<Stream?> ReadStreamAsync(Document document, string name, CancellationToken cancellationToken) => _storage.Target.ReadStreamAsync(document, name, cancellationToken); public Task<Stream> ReadStreamAsync(string name, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.ReadStreamAsync(name, checksum, cancellationToken); public Task<Stream> ReadStreamAsync(Project project, string name, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.ReadStreamAsync(project, name, checksum, cancellationToken); public Task<Stream> ReadStreamAsync(Document document, string name, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.ReadStreamAsync(document, name, checksum, cancellationToken); public Task<Stream> ReadStreamAsync(ProjectKey project, string name, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.ReadStreamAsync(project, name, checksum, cancellationToken); public Task<Stream> ReadStreamAsync(DocumentKey document, string name, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.ReadStreamAsync(document, name, checksum, cancellationToken); public Task<bool> WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken) => _storage.Target.WriteStreamAsync(name, stream, cancellationToken); public Task<bool> WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken) => _storage.Target.WriteStreamAsync(project, name, stream, cancellationToken); public Task<bool> WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken) => _storage.Target.WriteStreamAsync(document, name, stream, cancellationToken); public Task<bool> WriteStreamAsync(string name, Stream stream, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.WriteStreamAsync(name, stream, checksum, cancellationToken); public Task<bool> WriteStreamAsync(Project project, string name, Stream stream, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.WriteStreamAsync(project, name, stream, checksum, cancellationToken); public Task<bool> WriteStreamAsync(Document document, string name, Stream stream, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.WriteStreamAsync(document, name, stream, checksum, cancellationToken); public Task<bool> WriteStreamAsync(ProjectKey projectKey, string name, Stream stream, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.WriteStreamAsync(projectKey, name, stream, checksum, cancellationToken); public Task<bool> WriteStreamAsync(DocumentKey documentKey, string name, Stream stream, Checksum checksum, CancellationToken cancellationToken) => _storage.Target.WriteStreamAsync(documentKey, name, stream, checksum, cancellationToken); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/Core/Rebuild/xlf/RebuildResources.ja.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="ja" original="../RebuildResources.resx"> <body> <trans-unit id="0_exists_1_times_in_compilation_options"> <source>'{0}' exists '{1}' times in compilation options.</source> <target state="new">'{0}' exists '{1}' times in compilation options.</target> <note /> </trans-unit> <trans-unit id="A_non_null_PDB_stream_must_be_provided_because_the_compilation_does_not_have_an_embedded_PDB"> <source>A non-null PDB stream must be provided because the compilation does not have an embedded PDB.</source> <target state="new">A non-null PDB stream must be provided because the compilation does not have an embedded PDB.</target> <note /> </trans-unit> <trans-unit id="Cannot_create_compilation_options_0"> <source>Cannot create compilation options: {0}</source> <target state="new">Cannot create compilation options: {0}</target> <note /> </trans-unit> <trans-unit id="Could_not_get_PDB_file_path"> <source>Could not get PDB file path.</source> <target state="new">Could not get PDB file path.</target> <note /> </trans-unit> <trans-unit id="Does_not_contain_metadata_compilation_options"> <source>Does not contain metadata compilation options.</source> <target state="new">Does not contain metadata compilation options.</target> <note /> </trans-unit> <trans-unit id="Encountered_null_or_empty_key_for_compilation_options_pairs"> <source>Encountered null or empty key for compilation options pairs.</source> <target state="new">Encountered null or empty key for compilation options pairs.</target> <note /> </trans-unit> <trans-unit id="Encountered_unexpected_byte_0_when_expecting_a_null_terminator"> <source>Encountered unexpected byte '{0}' when expecting a null terminator.</source> <target state="new">Encountered unexpected byte '{0}' when expecting a null terminator.</target> <note /> </trans-unit> <trans-unit id="Invalid_language_name"> <source>Invalid language name.</source> <target state="new">Invalid language name.</target> <note /> </trans-unit> <trans-unit id="PDB_stream_must_be_null_because_the_compilation_has_an_embedded_PDB"> <source>PDB stream must be null because the compilation has an embedded PDB.</source> <target state="new">PDB stream must be null because the compilation has an embedded PDB.</target> <note /> </trans-unit> <trans-unit id="Unexpected_value_for_EmbedInteropTypes_MetadataImageKind_0"> <source>Unexpected value for EmbedInteropTypes/MetadataImageKind '{0}'.</source> <target state="new">Unexpected value for EmbedInteropTypes/MetadataImageKind '{0}'.</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ja" original="../RebuildResources.resx"> <body> <trans-unit id="0_exists_1_times_in_compilation_options"> <source>'{0}' exists '{1}' times in compilation options.</source> <target state="new">'{0}' exists '{1}' times in compilation options.</target> <note /> </trans-unit> <trans-unit id="A_non_null_PDB_stream_must_be_provided_because_the_compilation_does_not_have_an_embedded_PDB"> <source>A non-null PDB stream must be provided because the compilation does not have an embedded PDB.</source> <target state="new">A non-null PDB stream must be provided because the compilation does not have an embedded PDB.</target> <note /> </trans-unit> <trans-unit id="Cannot_create_compilation_options_0"> <source>Cannot create compilation options: {0}</source> <target state="new">Cannot create compilation options: {0}</target> <note /> </trans-unit> <trans-unit id="Could_not_get_PDB_file_path"> <source>Could not get PDB file path.</source> <target state="new">Could not get PDB file path.</target> <note /> </trans-unit> <trans-unit id="Does_not_contain_metadata_compilation_options"> <source>Does not contain metadata compilation options.</source> <target state="new">Does not contain metadata compilation options.</target> <note /> </trans-unit> <trans-unit id="Encountered_null_or_empty_key_for_compilation_options_pairs"> <source>Encountered null or empty key for compilation options pairs.</source> <target state="new">Encountered null or empty key for compilation options pairs.</target> <note /> </trans-unit> <trans-unit id="Encountered_unexpected_byte_0_when_expecting_a_null_terminator"> <source>Encountered unexpected byte '{0}' when expecting a null terminator.</source> <target state="new">Encountered unexpected byte '{0}' when expecting a null terminator.</target> <note /> </trans-unit> <trans-unit id="Invalid_language_name"> <source>Invalid language name.</source> <target state="new">Invalid language name.</target> <note /> </trans-unit> <trans-unit id="PDB_stream_must_be_null_because_the_compilation_has_an_embedded_PDB"> <source>PDB stream must be null because the compilation has an embedded PDB.</source> <target state="new">PDB stream must be null because the compilation has an embedded PDB.</target> <note /> </trans-unit> <trans-unit id="Unexpected_value_for_EmbedInteropTypes_MetadataImageKind_0"> <source>Unexpected value for EmbedInteropTypes/MetadataImageKind '{0}'.</source> <target state="new">Unexpected value for EmbedInteropTypes/MetadataImageKind '{0}'.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Workspaces/CSharp/Portable/Indentation/CSharpIndentationService.Indenter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Indentation; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Indentation { internal partial class CSharpIndentationService { protected override bool ShouldUseTokenIndenter(Indenter indenter, out SyntaxToken syntaxToken) => ShouldUseSmartTokenFormatterInsteadOfIndenter( indenter.Rules, indenter.Root, indenter.LineToBeIndented, indenter.OptionService, indenter.OptionSet, out syntaxToken); protected override ISmartTokenFormatter CreateSmartTokenFormatter(Indenter indenter) { var workspace = indenter.Document.Project.Solution.Workspace; var formattingRuleFactory = workspace.Services.GetRequiredService<IHostDependentFormattingRuleFactoryService>(); var rules = formattingRuleFactory.CreateRule(indenter.Document.Document, indenter.LineToBeIndented.Start).Concat(Formatter.GetDefaultFormattingRules(indenter.Document.Document)); return new CSharpSmartTokenFormatter(indenter.OptionSet, rules, indenter.Root); } protected override IndentationResult? GetDesiredIndentationWorker(Indenter indenter, SyntaxToken? tokenOpt, SyntaxTrivia? triviaOpt) => TryGetDesiredIndentation(indenter, triviaOpt) ?? TryGetDesiredIndentation(indenter, tokenOpt); private static IndentationResult? TryGetDesiredIndentation(Indenter indenter, SyntaxTrivia? triviaOpt) { // If we have a // comment, and it's the only thing on the line, then if we hit enter, we should align to // that. This helps for cases like: // // int goo; // this comment // // continues // // onwards // // The user will have to manually indent `// continues`, but we'll respect that indentation from that point on. if (triviaOpt == null) return null; var trivia = triviaOpt.Value; if (!trivia.IsSingleOrMultiLineComment() && !trivia.IsDocComment()) return null; var line = indenter.Text.Lines.GetLineFromPosition(trivia.FullSpan.Start); if (line.GetFirstNonWhitespacePosition() != trivia.FullSpan.Start) return null; // Previous line just contained this single line comment. Align us with it. return new IndentationResult(trivia.FullSpan.Start, 0); } private static IndentationResult? TryGetDesiredIndentation(Indenter indenter, SyntaxToken? tokenOpt) { if (tokenOpt == null) return null; return GetIndentationBasedOnToken(indenter, tokenOpt.Value); } private static IndentationResult GetIndentationBasedOnToken(Indenter indenter, SyntaxToken token) { Contract.ThrowIfNull(indenter.Tree); Contract.ThrowIfTrue(token.Kind() == SyntaxKind.None); // special cases // case 1: token belongs to verbatim token literal // case 2: $@"$${0}" // case 3: $@"Comment$$ in-between{0}" // case 4: $@"{0}$$" if (token.IsVerbatimStringLiteral() || token.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken) || token.IsKind(SyntaxKind.InterpolatedStringTextToken) || (token.IsKind(SyntaxKind.CloseBraceToken) && token.Parent.IsKind(SyntaxKind.Interpolation))) { return indenter.IndentFromStartOfLine(0); } // if previous statement belong to labeled statement, don't follow label's indentation // but its previous one. if (token.Parent is LabeledStatementSyntax || token.IsLastTokenInLabelStatement()) { token = token.GetAncestor<LabeledStatementSyntax>()!.GetFirstToken(includeZeroWidth: true).GetPreviousToken(includeZeroWidth: true); } var position = indenter.GetCurrentPositionNotBelongToEndOfFileToken(indenter.LineToBeIndented.Start); // first check operation service to see whether we can determine indentation from it var indentation = indenter.Finder.FromIndentBlockOperations(indenter.Tree, token, position, indenter.CancellationToken); if (indentation.HasValue) { return indenter.IndentFromStartOfLine(indentation.Value); } var alignmentTokenIndentation = indenter.Finder.FromAlignTokensOperations(indenter.Tree, token); if (alignmentTokenIndentation.HasValue) { return indenter.IndentFromStartOfLine(alignmentTokenIndentation.Value); } // if we couldn't determine indentation from the service, use heuristic to find indentation. var sourceText = indenter.LineToBeIndented.Text; RoslynDebug.AssertNotNull(sourceText); // If this is the last token of an embedded statement, walk up to the top-most parenting embedded // statement owner and use its indentation. // // cases: // if (true) // if (false) // Goo(); // // if (true) // { } if (token.IsSemicolonOfEmbeddedStatement() || token.IsCloseBraceOfEmbeddedBlock()) { Debug.Assert( token.Parent != null && (token.Parent.Parent is StatementSyntax || token.Parent.Parent is ElseClauseSyntax)); var embeddedStatementOwner = token.Parent.Parent; while (embeddedStatementOwner.IsEmbeddedStatement()) { RoslynDebug.AssertNotNull(embeddedStatementOwner.Parent); embeddedStatementOwner = embeddedStatementOwner.Parent; } return indenter.GetIndentationOfLine(sourceText.Lines.GetLineFromPosition(embeddedStatementOwner.GetFirstToken(includeZeroWidth: true).SpanStart)); } switch (token.Kind()) { case SyntaxKind.SemicolonToken: { // special cases if (token.IsSemicolonInForStatement()) { return GetDefaultIndentationFromToken(indenter, token); } return indenter.IndentFromStartOfLine(indenter.Finder.GetIndentationOfCurrentPosition(indenter.Tree, token, position, indenter.CancellationToken)); } case SyntaxKind.CloseBraceToken: { if (token.Parent.IsKind(SyntaxKind.AccessorList) && token.Parent.Parent.IsKind(SyntaxKind.PropertyDeclaration)) { if (token.GetNextToken().IsEqualsTokenInAutoPropertyInitializers()) { return GetDefaultIndentationFromToken(indenter, token); } } return indenter.IndentFromStartOfLine(indenter.Finder.GetIndentationOfCurrentPosition(indenter.Tree, token, position, indenter.CancellationToken)); } case SyntaxKind.OpenBraceToken: { return indenter.IndentFromStartOfLine(indenter.Finder.GetIndentationOfCurrentPosition(indenter.Tree, token, position, indenter.CancellationToken)); } case SyntaxKind.ColonToken: { var nonTerminalNode = token.Parent; Contract.ThrowIfNull(nonTerminalNode, @"Malformed code or bug in parser???"); if (nonTerminalNode is SwitchLabelSyntax) { return indenter.GetIndentationOfLine(sourceText.Lines.GetLineFromPosition(nonTerminalNode.GetFirstToken(includeZeroWidth: true).SpanStart), indenter.OptionSet.GetOption(FormattingOptions.IndentationSize, token.Language)); } goto default; } case SyntaxKind.CloseBracketToken: { var nonTerminalNode = token.Parent; Contract.ThrowIfNull(nonTerminalNode, @"Malformed code or bug in parser???"); // if this is closing an attribute, we shouldn't indent. if (nonTerminalNode is AttributeListSyntax) { return indenter.GetIndentationOfLine(sourceText.Lines.GetLineFromPosition(nonTerminalNode.GetFirstToken(includeZeroWidth: true).SpanStart)); } goto default; } case SyntaxKind.XmlTextLiteralToken: { return indenter.GetIndentationOfLine(sourceText.Lines.GetLineFromPosition(token.SpanStart)); } case SyntaxKind.CommaToken: { return GetIndentationFromCommaSeparatedList(indenter, token); } case SyntaxKind.CloseParenToken: { if (token.Parent.IsKind(SyntaxKind.ArgumentList)) { return GetDefaultIndentationFromToken(indenter, token.Parent.GetFirstToken(includeZeroWidth: true)); } goto default; } default: { return GetDefaultIndentationFromToken(indenter, token); } } } private static IndentationResult GetIndentationFromCommaSeparatedList(Indenter indenter, SyntaxToken token) => token.Parent switch { BaseArgumentListSyntax argument => GetIndentationFromCommaSeparatedList(indenter, argument.Arguments, token), BaseParameterListSyntax parameter => GetIndentationFromCommaSeparatedList(indenter, parameter.Parameters, token), TypeArgumentListSyntax typeArgument => GetIndentationFromCommaSeparatedList(indenter, typeArgument.Arguments, token), TypeParameterListSyntax typeParameter => GetIndentationFromCommaSeparatedList(indenter, typeParameter.Parameters, token), EnumDeclarationSyntax enumDeclaration => GetIndentationFromCommaSeparatedList(indenter, enumDeclaration.Members, token), InitializerExpressionSyntax initializerSyntax => GetIndentationFromCommaSeparatedList(indenter, initializerSyntax.Expressions, token), _ => GetDefaultIndentationFromToken(indenter, token), }; private static IndentationResult GetIndentationFromCommaSeparatedList<T>( Indenter indenter, SeparatedSyntaxList<T> list, SyntaxToken token) where T : SyntaxNode { var index = list.GetWithSeparators().IndexOf(token); if (index < 0) { return GetDefaultIndentationFromToken(indenter, token); } // find node that starts at the beginning of a line var sourceText = indenter.LineToBeIndented.Text; RoslynDebug.AssertNotNull(sourceText); for (var i = (index - 1) / 2; i >= 0; i--) { var node = list[i]; var firstToken = node.GetFirstToken(includeZeroWidth: true); if (firstToken.IsFirstTokenOnLine(sourceText)) { return indenter.GetIndentationOfLine(sourceText.Lines.GetLineFromPosition(firstToken.SpanStart)); } } // smart indenter has a special indent block rule for comma separated list, so don't // need to add default additional space for multiline expressions return GetDefaultIndentationFromTokenLine(indenter, token, additionalSpace: 0); } private static IndentationResult GetDefaultIndentationFromToken(Indenter indenter, SyntaxToken token) { if (IsPartOfQueryExpression(token)) { return GetIndentationForQueryExpression(indenter, token); } return GetDefaultIndentationFromTokenLine(indenter, token); } private static IndentationResult GetIndentationForQueryExpression(Indenter indenter, SyntaxToken token) { // find containing non terminal node var queryExpressionClause = GetQueryExpressionClause(token); if (queryExpressionClause == null) { return GetDefaultIndentationFromTokenLine(indenter, token); } // find line where first token of the node is var sourceText = indenter.LineToBeIndented.Text; RoslynDebug.AssertNotNull(sourceText); var firstToken = queryExpressionClause.GetFirstToken(includeZeroWidth: true); var firstTokenLine = sourceText.Lines.GetLineFromPosition(firstToken.SpanStart); // find line where given token is var givenTokenLine = sourceText.Lines.GetLineFromPosition(token.SpanStart); if (firstTokenLine.LineNumber != givenTokenLine.LineNumber) { // do default behavior return GetDefaultIndentationFromTokenLine(indenter, token); } // okay, we are right under the query expression. // align caret to query expression if (firstToken.IsFirstTokenOnLine(sourceText)) { return indenter.GetIndentationOfToken(firstToken); } // find query body that has a token that is a first token on the line if (!(queryExpressionClause.Parent is QueryBodySyntax queryBody)) { return indenter.GetIndentationOfToken(firstToken); } // find preceding clause that starts on its own. var clauses = queryBody.Clauses; for (var i = clauses.Count - 1; i >= 0; i--) { var clause = clauses[i]; if (firstToken.SpanStart <= clause.SpanStart) { continue; } var clauseToken = clause.GetFirstToken(includeZeroWidth: true); if (clauseToken.IsFirstTokenOnLine(sourceText)) { return indenter.GetIndentationOfToken(clauseToken); } } // no query clause start a line. use the first token of the query expression RoslynDebug.AssertNotNull(queryBody.Parent); return indenter.GetIndentationOfToken(queryBody.Parent.GetFirstToken(includeZeroWidth: true)); } private static SyntaxNode? GetQueryExpressionClause(SyntaxToken token) { var clause = token.GetAncestors<SyntaxNode>().FirstOrDefault(n => n is QueryClauseSyntax || n is SelectOrGroupClauseSyntax); if (clause != null) { return clause; } // If this is a query continuation, use the last clause of its parenting query. var body = token.GetAncestor<QueryBodySyntax>(); if (body != null) { if (body.SelectOrGroup.IsMissing) { return body.Clauses.LastOrDefault(); } else { return body.SelectOrGroup; } } return null; } private static bool IsPartOfQueryExpression(SyntaxToken token) { var queryExpression = token.GetAncestor<QueryExpressionSyntax>(); return queryExpression != null; } private static IndentationResult GetDefaultIndentationFromTokenLine( Indenter indenter, SyntaxToken token, int? additionalSpace = null) { var spaceToAdd = additionalSpace ?? indenter.OptionSet.GetOption(FormattingOptions.IndentationSize, token.Language); var sourceText = indenter.LineToBeIndented.Text; RoslynDebug.AssertNotNull(sourceText); // find line where given token is var givenTokenLine = sourceText.Lines.GetLineFromPosition(token.SpanStart); // find right position var position = indenter.GetCurrentPositionNotBelongToEndOfFileToken(indenter.LineToBeIndented.Start); // find containing non expression node var nonExpressionNode = token.GetAncestors<SyntaxNode>().FirstOrDefault(n => n is StatementSyntax); if (nonExpressionNode == null) { // well, I can't find any non expression node. use default behavior return indenter.IndentFromStartOfLine(indenter.Finder.GetIndentationOfCurrentPosition(indenter.Tree, token, position, spaceToAdd, indenter.CancellationToken)); } // find line where first token of the node is var firstTokenLine = sourceText.Lines.GetLineFromPosition(nonExpressionNode.GetFirstToken(includeZeroWidth: true).SpanStart); // single line expression if (firstTokenLine.LineNumber == givenTokenLine.LineNumber) { return indenter.IndentFromStartOfLine(indenter.Finder.GetIndentationOfCurrentPosition(indenter.Tree, token, position, spaceToAdd, indenter.CancellationToken)); } // okay, looks like containing node is written over multiple lines, in that case, give same indentation as given token return indenter.GetIndentationOfLine(givenTokenLine); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Indentation; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Indentation { internal partial class CSharpIndentationService { protected override bool ShouldUseTokenIndenter(Indenter indenter, out SyntaxToken syntaxToken) => ShouldUseSmartTokenFormatterInsteadOfIndenter( indenter.Rules, indenter.Root, indenter.LineToBeIndented, indenter.OptionService, indenter.OptionSet, out syntaxToken); protected override ISmartTokenFormatter CreateSmartTokenFormatter(Indenter indenter) { var workspace = indenter.Document.Project.Solution.Workspace; var formattingRuleFactory = workspace.Services.GetRequiredService<IHostDependentFormattingRuleFactoryService>(); var rules = formattingRuleFactory.CreateRule(indenter.Document.Document, indenter.LineToBeIndented.Start).Concat(Formatter.GetDefaultFormattingRules(indenter.Document.Document)); return new CSharpSmartTokenFormatter(indenter.OptionSet, rules, indenter.Root); } protected override IndentationResult? GetDesiredIndentationWorker(Indenter indenter, SyntaxToken? tokenOpt, SyntaxTrivia? triviaOpt) => TryGetDesiredIndentation(indenter, triviaOpt) ?? TryGetDesiredIndentation(indenter, tokenOpt); private static IndentationResult? TryGetDesiredIndentation(Indenter indenter, SyntaxTrivia? triviaOpt) { // If we have a // comment, and it's the only thing on the line, then if we hit enter, we should align to // that. This helps for cases like: // // int goo; // this comment // // continues // // onwards // // The user will have to manually indent `// continues`, but we'll respect that indentation from that point on. if (triviaOpt == null) return null; var trivia = triviaOpt.Value; if (!trivia.IsSingleOrMultiLineComment() && !trivia.IsDocComment()) return null; var line = indenter.Text.Lines.GetLineFromPosition(trivia.FullSpan.Start); if (line.GetFirstNonWhitespacePosition() != trivia.FullSpan.Start) return null; // Previous line just contained this single line comment. Align us with it. return new IndentationResult(trivia.FullSpan.Start, 0); } private static IndentationResult? TryGetDesiredIndentation(Indenter indenter, SyntaxToken? tokenOpt) { if (tokenOpt == null) return null; return GetIndentationBasedOnToken(indenter, tokenOpt.Value); } private static IndentationResult GetIndentationBasedOnToken(Indenter indenter, SyntaxToken token) { Contract.ThrowIfNull(indenter.Tree); Contract.ThrowIfTrue(token.Kind() == SyntaxKind.None); // special cases // case 1: token belongs to verbatim token literal // case 2: $@"$${0}" // case 3: $@"Comment$$ in-between{0}" // case 4: $@"{0}$$" if (token.IsVerbatimStringLiteral() || token.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken) || token.IsKind(SyntaxKind.InterpolatedStringTextToken) || (token.IsKind(SyntaxKind.CloseBraceToken) && token.Parent.IsKind(SyntaxKind.Interpolation))) { return indenter.IndentFromStartOfLine(0); } // if previous statement belong to labeled statement, don't follow label's indentation // but its previous one. if (token.Parent is LabeledStatementSyntax || token.IsLastTokenInLabelStatement()) { token = token.GetAncestor<LabeledStatementSyntax>()!.GetFirstToken(includeZeroWidth: true).GetPreviousToken(includeZeroWidth: true); } var position = indenter.GetCurrentPositionNotBelongToEndOfFileToken(indenter.LineToBeIndented.Start); // first check operation service to see whether we can determine indentation from it var indentation = indenter.Finder.FromIndentBlockOperations(indenter.Tree, token, position, indenter.CancellationToken); if (indentation.HasValue) { return indenter.IndentFromStartOfLine(indentation.Value); } var alignmentTokenIndentation = indenter.Finder.FromAlignTokensOperations(indenter.Tree, token); if (alignmentTokenIndentation.HasValue) { return indenter.IndentFromStartOfLine(alignmentTokenIndentation.Value); } // if we couldn't determine indentation from the service, use heuristic to find indentation. var sourceText = indenter.LineToBeIndented.Text; RoslynDebug.AssertNotNull(sourceText); // If this is the last token of an embedded statement, walk up to the top-most parenting embedded // statement owner and use its indentation. // // cases: // if (true) // if (false) // Goo(); // // if (true) // { } if (token.IsSemicolonOfEmbeddedStatement() || token.IsCloseBraceOfEmbeddedBlock()) { Debug.Assert( token.Parent != null && (token.Parent.Parent is StatementSyntax || token.Parent.Parent is ElseClauseSyntax)); var embeddedStatementOwner = token.Parent.Parent; while (embeddedStatementOwner.IsEmbeddedStatement()) { RoslynDebug.AssertNotNull(embeddedStatementOwner.Parent); embeddedStatementOwner = embeddedStatementOwner.Parent; } return indenter.GetIndentationOfLine(sourceText.Lines.GetLineFromPosition(embeddedStatementOwner.GetFirstToken(includeZeroWidth: true).SpanStart)); } switch (token.Kind()) { case SyntaxKind.SemicolonToken: { // special cases if (token.IsSemicolonInForStatement()) { return GetDefaultIndentationFromToken(indenter, token); } return indenter.IndentFromStartOfLine(indenter.Finder.GetIndentationOfCurrentPosition(indenter.Tree, token, position, indenter.CancellationToken)); } case SyntaxKind.CloseBraceToken: { if (token.Parent.IsKind(SyntaxKind.AccessorList) && token.Parent.Parent.IsKind(SyntaxKind.PropertyDeclaration)) { if (token.GetNextToken().IsEqualsTokenInAutoPropertyInitializers()) { return GetDefaultIndentationFromToken(indenter, token); } } return indenter.IndentFromStartOfLine(indenter.Finder.GetIndentationOfCurrentPosition(indenter.Tree, token, position, indenter.CancellationToken)); } case SyntaxKind.OpenBraceToken: { return indenter.IndentFromStartOfLine(indenter.Finder.GetIndentationOfCurrentPosition(indenter.Tree, token, position, indenter.CancellationToken)); } case SyntaxKind.ColonToken: { var nonTerminalNode = token.Parent; Contract.ThrowIfNull(nonTerminalNode, @"Malformed code or bug in parser???"); if (nonTerminalNode is SwitchLabelSyntax) { return indenter.GetIndentationOfLine(sourceText.Lines.GetLineFromPosition(nonTerminalNode.GetFirstToken(includeZeroWidth: true).SpanStart), indenter.OptionSet.GetOption(FormattingOptions.IndentationSize, token.Language)); } goto default; } case SyntaxKind.CloseBracketToken: { var nonTerminalNode = token.Parent; Contract.ThrowIfNull(nonTerminalNode, @"Malformed code or bug in parser???"); // if this is closing an attribute, we shouldn't indent. if (nonTerminalNode is AttributeListSyntax) { return indenter.GetIndentationOfLine(sourceText.Lines.GetLineFromPosition(nonTerminalNode.GetFirstToken(includeZeroWidth: true).SpanStart)); } goto default; } case SyntaxKind.XmlTextLiteralToken: { return indenter.GetIndentationOfLine(sourceText.Lines.GetLineFromPosition(token.SpanStart)); } case SyntaxKind.CommaToken: { return GetIndentationFromCommaSeparatedList(indenter, token); } case SyntaxKind.CloseParenToken: { if (token.Parent.IsKind(SyntaxKind.ArgumentList)) { return GetDefaultIndentationFromToken(indenter, token.Parent.GetFirstToken(includeZeroWidth: true)); } goto default; } default: { return GetDefaultIndentationFromToken(indenter, token); } } } private static IndentationResult GetIndentationFromCommaSeparatedList(Indenter indenter, SyntaxToken token) => token.Parent switch { BaseArgumentListSyntax argument => GetIndentationFromCommaSeparatedList(indenter, argument.Arguments, token), BaseParameterListSyntax parameter => GetIndentationFromCommaSeparatedList(indenter, parameter.Parameters, token), TypeArgumentListSyntax typeArgument => GetIndentationFromCommaSeparatedList(indenter, typeArgument.Arguments, token), TypeParameterListSyntax typeParameter => GetIndentationFromCommaSeparatedList(indenter, typeParameter.Parameters, token), EnumDeclarationSyntax enumDeclaration => GetIndentationFromCommaSeparatedList(indenter, enumDeclaration.Members, token), InitializerExpressionSyntax initializerSyntax => GetIndentationFromCommaSeparatedList(indenter, initializerSyntax.Expressions, token), _ => GetDefaultIndentationFromToken(indenter, token), }; private static IndentationResult GetIndentationFromCommaSeparatedList<T>( Indenter indenter, SeparatedSyntaxList<T> list, SyntaxToken token) where T : SyntaxNode { var index = list.GetWithSeparators().IndexOf(token); if (index < 0) { return GetDefaultIndentationFromToken(indenter, token); } // find node that starts at the beginning of a line var sourceText = indenter.LineToBeIndented.Text; RoslynDebug.AssertNotNull(sourceText); for (var i = (index - 1) / 2; i >= 0; i--) { var node = list[i]; var firstToken = node.GetFirstToken(includeZeroWidth: true); if (firstToken.IsFirstTokenOnLine(sourceText)) { return indenter.GetIndentationOfLine(sourceText.Lines.GetLineFromPosition(firstToken.SpanStart)); } } // smart indenter has a special indent block rule for comma separated list, so don't // need to add default additional space for multiline expressions return GetDefaultIndentationFromTokenLine(indenter, token, additionalSpace: 0); } private static IndentationResult GetDefaultIndentationFromToken(Indenter indenter, SyntaxToken token) { if (IsPartOfQueryExpression(token)) { return GetIndentationForQueryExpression(indenter, token); } return GetDefaultIndentationFromTokenLine(indenter, token); } private static IndentationResult GetIndentationForQueryExpression(Indenter indenter, SyntaxToken token) { // find containing non terminal node var queryExpressionClause = GetQueryExpressionClause(token); if (queryExpressionClause == null) { return GetDefaultIndentationFromTokenLine(indenter, token); } // find line where first token of the node is var sourceText = indenter.LineToBeIndented.Text; RoslynDebug.AssertNotNull(sourceText); var firstToken = queryExpressionClause.GetFirstToken(includeZeroWidth: true); var firstTokenLine = sourceText.Lines.GetLineFromPosition(firstToken.SpanStart); // find line where given token is var givenTokenLine = sourceText.Lines.GetLineFromPosition(token.SpanStart); if (firstTokenLine.LineNumber != givenTokenLine.LineNumber) { // do default behavior return GetDefaultIndentationFromTokenLine(indenter, token); } // okay, we are right under the query expression. // align caret to query expression if (firstToken.IsFirstTokenOnLine(sourceText)) { return indenter.GetIndentationOfToken(firstToken); } // find query body that has a token that is a first token on the line if (!(queryExpressionClause.Parent is QueryBodySyntax queryBody)) { return indenter.GetIndentationOfToken(firstToken); } // find preceding clause that starts on its own. var clauses = queryBody.Clauses; for (var i = clauses.Count - 1; i >= 0; i--) { var clause = clauses[i]; if (firstToken.SpanStart <= clause.SpanStart) { continue; } var clauseToken = clause.GetFirstToken(includeZeroWidth: true); if (clauseToken.IsFirstTokenOnLine(sourceText)) { return indenter.GetIndentationOfToken(clauseToken); } } // no query clause start a line. use the first token of the query expression RoslynDebug.AssertNotNull(queryBody.Parent); return indenter.GetIndentationOfToken(queryBody.Parent.GetFirstToken(includeZeroWidth: true)); } private static SyntaxNode? GetQueryExpressionClause(SyntaxToken token) { var clause = token.GetAncestors<SyntaxNode>().FirstOrDefault(n => n is QueryClauseSyntax || n is SelectOrGroupClauseSyntax); if (clause != null) { return clause; } // If this is a query continuation, use the last clause of its parenting query. var body = token.GetAncestor<QueryBodySyntax>(); if (body != null) { if (body.SelectOrGroup.IsMissing) { return body.Clauses.LastOrDefault(); } else { return body.SelectOrGroup; } } return null; } private static bool IsPartOfQueryExpression(SyntaxToken token) { var queryExpression = token.GetAncestor<QueryExpressionSyntax>(); return queryExpression != null; } private static IndentationResult GetDefaultIndentationFromTokenLine( Indenter indenter, SyntaxToken token, int? additionalSpace = null) { var spaceToAdd = additionalSpace ?? indenter.OptionSet.GetOption(FormattingOptions.IndentationSize, token.Language); var sourceText = indenter.LineToBeIndented.Text; RoslynDebug.AssertNotNull(sourceText); // find line where given token is var givenTokenLine = sourceText.Lines.GetLineFromPosition(token.SpanStart); // find right position var position = indenter.GetCurrentPositionNotBelongToEndOfFileToken(indenter.LineToBeIndented.Start); // find containing non expression node var nonExpressionNode = token.GetAncestors<SyntaxNode>().FirstOrDefault(n => n is StatementSyntax); if (nonExpressionNode == null) { // well, I can't find any non expression node. use default behavior return indenter.IndentFromStartOfLine(indenter.Finder.GetIndentationOfCurrentPosition(indenter.Tree, token, position, spaceToAdd, indenter.CancellationToken)); } // find line where first token of the node is var firstTokenLine = sourceText.Lines.GetLineFromPosition(nonExpressionNode.GetFirstToken(includeZeroWidth: true).SpanStart); // single line expression if (firstTokenLine.LineNumber == givenTokenLine.LineNumber) { return indenter.IndentFromStartOfLine(indenter.Finder.GetIndentationOfCurrentPosition(indenter.Tree, token, position, spaceToAdd, indenter.CancellationToken)); } // okay, looks like containing node is written over multiple lines, in that case, give same indentation as given token return indenter.GetIndentationOfLine(givenTokenLine); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/VisualBasic/Test/Syntax/Syntax/SerializationTests.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 System.IO Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SerializationTests Private Sub RoundTrip(text As String, Optional expectRecursive As Boolean = True) Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim root = tree.GetRoot() Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Dim dtext = droot.ToFullString() Assert.Equal(text, dtext) Assert.True(droot.IsEquivalentTo(tree.GetRoot())) End Sub <Fact> Public Sub TestRoundTripSyntaxNode() RoundTrip(<Goo> Public Class C End Class </Goo>.Value) End Sub <Fact> Public Sub TestRoundTripSyntaxNodeWithDiagnostics() Dim text = <Goo> Public Class C End </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim root = tree.GetVisualBasicRoot() Assert.True(root.HasErrors) Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Dim dtext = droot.ToFullString() Assert.Equal(text, dtext) Assert.True(DirectCast(droot, VisualBasicSyntaxNode).HasErrors) Assert.True(droot.IsEquivalentTo(tree.GetRoot())) End Sub <Fact> Public Sub TestRoundTripSyntaxNodeWithAnnotation() Dim text = <Goo> Public Class C End Class </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim annotation = New SyntaxAnnotation() Dim root = tree.GetRoot().WithAdditionalAnnotations(annotation) Assert.True(root.ContainsAnnotations) Assert.True(root.HasAnnotation(annotation)) Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Dim dtext = droot.ToFullString() Assert.Equal(text, dtext) Assert.True(droot.ContainsAnnotations) Assert.True(droot.HasAnnotation(annotation)) Assert.True(droot.IsEquivalentTo(tree.GetRoot())) End Sub <Fact> Public Sub TestRoundTripSyntaxNodeWithMultipleInstancesOfTheSameAnnotation() Dim text = <Goo> Public Class C End Class </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim annotation = New SyntaxAnnotation() Dim root = tree.GetRoot().WithAdditionalAnnotations(annotation, annotation) Assert.True(root.ContainsAnnotations) Assert.True(root.HasAnnotation(annotation)) Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Dim dtext = droot.ToFullString() Assert.Equal(text, dtext) Assert.True(droot.ContainsAnnotations) Assert.True(droot.HasAnnotation(annotation)) Assert.True(droot.IsEquivalentTo(tree.GetRoot())) End Sub <Fact> Public Sub RoundTripSyntaxNodeWithAnnotationsRemoved() Dim text = <Goo> Public Class C End Class </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim annotation1 = New SyntaxAnnotation("annotation1") Dim root = tree.GetRoot().WithAdditionalAnnotations(annotation1) Assert.Equal(True, root.ContainsAnnotations) Assert.Equal(True, root.HasAnnotation(annotation1)) Dim removedRoot = root.WithoutAnnotations(annotation1) Assert.Equal(False, removedRoot.ContainsAnnotations) Assert.Equal(False, removedRoot.HasAnnotation(annotation1)) Dim stream = New MemoryStream() removedRoot.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Assert.Equal(False, droot.ContainsAnnotations) Assert.Equal(False, droot.HasAnnotation(annotation1)) Dim annotation2 = New SyntaxAnnotation("annotation2") Dim doubleAnnoRoot = droot.WithAdditionalAnnotations(annotation1, annotation2) Assert.Equal(True, doubleAnnoRoot.ContainsAnnotations) Assert.Equal(True, doubleAnnoRoot.HasAnnotation(annotation1)) Assert.Equal(True, doubleAnnoRoot.HasAnnotation(annotation2)) Dim removedDoubleAnnoRoot = doubleAnnoRoot.WithoutAnnotations(annotation1, annotation2) Assert.Equal(False, removedDoubleAnnoRoot.ContainsAnnotations) Assert.Equal(False, removedDoubleAnnoRoot.HasAnnotation(annotation1)) Assert.Equal(False, removedDoubleAnnoRoot.HasAnnotation(annotation2)) stream = New MemoryStream() removedRoot.SerializeTo(stream) stream.Position = 0 droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Assert.Equal(False, droot.ContainsAnnotations) Assert.Equal(False, droot.HasAnnotation(annotation1)) Assert.Equal(False, droot.HasAnnotation(annotation2)) End Sub <Fact> Public Sub RoundTripSyntaxNodeWithAnnotationRemovedWithMultipleReference() Dim text = <Goo> Public Class C End Class </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim annotation1 = New SyntaxAnnotation("annotation1") Dim root = tree.GetRoot().WithAdditionalAnnotations(annotation1, annotation1) Assert.Equal(True, root.ContainsAnnotations) Assert.Equal(True, root.HasAnnotation(annotation1)) Dim removedRoot = root.WithoutAnnotations(annotation1) Assert.Equal(False, removedRoot.ContainsAnnotations) Assert.Equal(False, removedRoot.HasAnnotation(annotation1)) Dim stream = New MemoryStream() removedRoot.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Assert.Equal(False, droot.ContainsAnnotations) Assert.Equal(False, droot.HasAnnotation(annotation1)) End Sub <Fact()> Public Sub TestRoundTripSyntaxNodeWithSpecialAnnotation() Dim text = <Goo> Public Class C End Class </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim annotation = New SyntaxAnnotation("TestAnnotation", "this is a test") Dim root = tree.GetRoot().WithAdditionalAnnotations(annotation) Assert.True(root.ContainsAnnotations) Assert.True(root.HasAnnotation(annotation)) Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Dim dtext = droot.ToFullString() Assert.Equal(text, dtext) Assert.True(droot.ContainsAnnotations) Assert.True(droot.HasAnnotation(annotation)) Assert.True(droot.IsEquivalentTo(tree.GetRoot())) Dim dannotation = droot.GetAnnotations("TestAnnotation").SingleOrDefault() Assert.NotNull(dannotation) Assert.NotSame(annotation, dannotation) ' not same instance Assert.Equal(annotation, dannotation) ' but are equivalent End Sub <Fact> <WorkItem(530374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530374")> Public Sub RoundtripSerializeDeepExpression() Dim text = <Goo><![CDATA[ Module Module15 Declare Function GetDesktopWindow Lib "User32" () As Integer Declare Function EnumChildWindows Lib "User32" (ByVal hw As Integer, ByVal lpWndProc As mydel, ByVal lp As Integer) As Integer Public intCounter As Integer Delegate Function mydel(ByVal hw As Integer, ByVal lp As Integer) As Integer Public d As mydel = New mydel(AddressOf EnumChildProc) Sub Main() Dim x As Object intCounter = 0 Dim hw As Integer hw = GetDesktopWindow() 'Call API passing ptr to callback x = EnumChildWindows(hw, d, 5) 'This should always be true, I would think If intCounter < 10 Then intcounter = 10 End If End Sub 'Callback function for EnumWindows Function EnumChildProc(ByVal hw As Integer, ByVal lp As Integer) As Integer intCounter = intCounter + 1 EnumChildProc = 1 End Function Sub Regression41614() Dim abc = "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" End Sub End Module ]]> </Goo>.Value RoundTrip(text, expectRecursive:=False) End Sub <Fact> <WorkItem(530374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530374")> Public Sub RoundtripSerializeDeepExpression2() Dim text = <Goo><![CDATA[ Module GroupJoin2 Sub Test1() q = From a In aa Group Join b As $ In bb On a Equals b End Sub End Module ]]> </Goo>.Value RoundTrip(text) End Sub <Fact> <WorkItem(1038237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1038237")> Public Sub RoundTripPragmaDirective() Dim text = <Goo><![CDATA[ #Disable Warning BC40000 ]]> </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim root = tree.GetRoot() Assert.True(root.ContainsDirectives) Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim newRoot = VisualBasicSyntaxNode.DeserializeFrom(stream) Assert.True(newRoot.ContainsDirectives) 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 Imports System.IO Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SerializationTests Private Sub RoundTrip(text As String, Optional expectRecursive As Boolean = True) Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim root = tree.GetRoot() Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Dim dtext = droot.ToFullString() Assert.Equal(text, dtext) Assert.True(droot.IsEquivalentTo(tree.GetRoot())) End Sub <Fact> Public Sub TestRoundTripSyntaxNode() RoundTrip(<Goo> Public Class C End Class </Goo>.Value) End Sub <Fact> Public Sub TestRoundTripSyntaxNodeWithDiagnostics() Dim text = <Goo> Public Class C End </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim root = tree.GetVisualBasicRoot() Assert.True(root.HasErrors) Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Dim dtext = droot.ToFullString() Assert.Equal(text, dtext) Assert.True(DirectCast(droot, VisualBasicSyntaxNode).HasErrors) Assert.True(droot.IsEquivalentTo(tree.GetRoot())) End Sub <Fact> Public Sub TestRoundTripSyntaxNodeWithAnnotation() Dim text = <Goo> Public Class C End Class </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim annotation = New SyntaxAnnotation() Dim root = tree.GetRoot().WithAdditionalAnnotations(annotation) Assert.True(root.ContainsAnnotations) Assert.True(root.HasAnnotation(annotation)) Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Dim dtext = droot.ToFullString() Assert.Equal(text, dtext) Assert.True(droot.ContainsAnnotations) Assert.True(droot.HasAnnotation(annotation)) Assert.True(droot.IsEquivalentTo(tree.GetRoot())) End Sub <Fact> Public Sub TestRoundTripSyntaxNodeWithMultipleInstancesOfTheSameAnnotation() Dim text = <Goo> Public Class C End Class </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim annotation = New SyntaxAnnotation() Dim root = tree.GetRoot().WithAdditionalAnnotations(annotation, annotation) Assert.True(root.ContainsAnnotations) Assert.True(root.HasAnnotation(annotation)) Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Dim dtext = droot.ToFullString() Assert.Equal(text, dtext) Assert.True(droot.ContainsAnnotations) Assert.True(droot.HasAnnotation(annotation)) Assert.True(droot.IsEquivalentTo(tree.GetRoot())) End Sub <Fact> Public Sub RoundTripSyntaxNodeWithAnnotationsRemoved() Dim text = <Goo> Public Class C End Class </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim annotation1 = New SyntaxAnnotation("annotation1") Dim root = tree.GetRoot().WithAdditionalAnnotations(annotation1) Assert.Equal(True, root.ContainsAnnotations) Assert.Equal(True, root.HasAnnotation(annotation1)) Dim removedRoot = root.WithoutAnnotations(annotation1) Assert.Equal(False, removedRoot.ContainsAnnotations) Assert.Equal(False, removedRoot.HasAnnotation(annotation1)) Dim stream = New MemoryStream() removedRoot.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Assert.Equal(False, droot.ContainsAnnotations) Assert.Equal(False, droot.HasAnnotation(annotation1)) Dim annotation2 = New SyntaxAnnotation("annotation2") Dim doubleAnnoRoot = droot.WithAdditionalAnnotations(annotation1, annotation2) Assert.Equal(True, doubleAnnoRoot.ContainsAnnotations) Assert.Equal(True, doubleAnnoRoot.HasAnnotation(annotation1)) Assert.Equal(True, doubleAnnoRoot.HasAnnotation(annotation2)) Dim removedDoubleAnnoRoot = doubleAnnoRoot.WithoutAnnotations(annotation1, annotation2) Assert.Equal(False, removedDoubleAnnoRoot.ContainsAnnotations) Assert.Equal(False, removedDoubleAnnoRoot.HasAnnotation(annotation1)) Assert.Equal(False, removedDoubleAnnoRoot.HasAnnotation(annotation2)) stream = New MemoryStream() removedRoot.SerializeTo(stream) stream.Position = 0 droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Assert.Equal(False, droot.ContainsAnnotations) Assert.Equal(False, droot.HasAnnotation(annotation1)) Assert.Equal(False, droot.HasAnnotation(annotation2)) End Sub <Fact> Public Sub RoundTripSyntaxNodeWithAnnotationRemovedWithMultipleReference() Dim text = <Goo> Public Class C End Class </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim annotation1 = New SyntaxAnnotation("annotation1") Dim root = tree.GetRoot().WithAdditionalAnnotations(annotation1, annotation1) Assert.Equal(True, root.ContainsAnnotations) Assert.Equal(True, root.HasAnnotation(annotation1)) Dim removedRoot = root.WithoutAnnotations(annotation1) Assert.Equal(False, removedRoot.ContainsAnnotations) Assert.Equal(False, removedRoot.HasAnnotation(annotation1)) Dim stream = New MemoryStream() removedRoot.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Assert.Equal(False, droot.ContainsAnnotations) Assert.Equal(False, droot.HasAnnotation(annotation1)) End Sub <Fact()> Public Sub TestRoundTripSyntaxNodeWithSpecialAnnotation() Dim text = <Goo> Public Class C End Class </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim annotation = New SyntaxAnnotation("TestAnnotation", "this is a test") Dim root = tree.GetRoot().WithAdditionalAnnotations(annotation) Assert.True(root.ContainsAnnotations) Assert.True(root.HasAnnotation(annotation)) Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim droot = VisualBasicSyntaxNode.DeserializeFrom(stream) Dim dtext = droot.ToFullString() Assert.Equal(text, dtext) Assert.True(droot.ContainsAnnotations) Assert.True(droot.HasAnnotation(annotation)) Assert.True(droot.IsEquivalentTo(tree.GetRoot())) Dim dannotation = droot.GetAnnotations("TestAnnotation").SingleOrDefault() Assert.NotNull(dannotation) Assert.NotSame(annotation, dannotation) ' not same instance Assert.Equal(annotation, dannotation) ' but are equivalent End Sub <Fact> <WorkItem(530374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530374")> Public Sub RoundtripSerializeDeepExpression() Dim text = <Goo><![CDATA[ Module Module15 Declare Function GetDesktopWindow Lib "User32" () As Integer Declare Function EnumChildWindows Lib "User32" (ByVal hw As Integer, ByVal lpWndProc As mydel, ByVal lp As Integer) As Integer Public intCounter As Integer Delegate Function mydel(ByVal hw As Integer, ByVal lp As Integer) As Integer Public d As mydel = New mydel(AddressOf EnumChildProc) Sub Main() Dim x As Object intCounter = 0 Dim hw As Integer hw = GetDesktopWindow() 'Call API passing ptr to callback x = EnumChildWindows(hw, d, 5) 'This should always be true, I would think If intCounter < 10 Then intcounter = 10 End If End Sub 'Callback function for EnumWindows Function EnumChildProc(ByVal hw As Integer, ByVal lp As Integer) As Integer intCounter = intCounter + 1 EnumChildProc = 1 End Function Sub Regression41614() Dim abc = "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & _ "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" & "abc" End Sub End Module ]]> </Goo>.Value RoundTrip(text, expectRecursive:=False) End Sub <Fact> <WorkItem(530374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530374")> Public Sub RoundtripSerializeDeepExpression2() Dim text = <Goo><![CDATA[ Module GroupJoin2 Sub Test1() q = From a In aa Group Join b As $ In bb On a Equals b End Sub End Module ]]> </Goo>.Value RoundTrip(text) End Sub <Fact> <WorkItem(1038237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1038237")> Public Sub RoundTripPragmaDirective() Dim text = <Goo><![CDATA[ #Disable Warning BC40000 ]]> </Goo>.Value Dim tree = VisualBasicSyntaxTree.ParseText(text) Dim root = tree.GetRoot() Assert.True(root.ContainsDirectives) Dim stream = New MemoryStream() root.SerializeTo(stream) stream.Position = 0 Dim newRoot = VisualBasicSyntaxNode.DeserializeFrom(stream) Assert.True(newRoot.ContainsDirectives) End Sub End Class End Namespace
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/CodeStyle/VisualBasic/CodeFixes/xlf/VBCodeStyleFixesResources.es.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="es" original="../VBCodeStyleFixesResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Quite este valor cuando se agregue otro.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</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="es" original="../VBCodeStyleFixesResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Quite este valor cuando se agregue otro.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/VisualStudio/Core/Impl/CodeModel/MethodXml/BinaryOperatorKind.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml { internal enum BinaryOperatorKind { None, AddDelegate, BitwiseAnd, BitwiseOr, Concatenate, Plus } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml { internal enum BinaryOperatorKind { None, AddDelegate, BitwiseAnd, BitwiseOr, Concatenate, Plus } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Analyzers/CSharp/Tests/UpdateLegacySuppressions/UpdateLegacySuppressionsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.CSharp.RemoveUnnecessarySuppressions.CSharpRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer, Microsoft.CodeAnalysis.UpdateLegacySuppressions.UpdateLegacySuppressionsCodeFixProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UpdateLegacySuppressions { [Trait(Traits.Feature, Traits.Features.CodeActionsUpdateLegacySuppressions)] [WorkItem(44362, "https://github.com/dotnet/roslyn/issues/44362")] public class UpdateLegacySuppressionsTests { [Theory, CombinatorialData] public void TestStandardProperty(AnalyzerProperty property) => VerifyCS.VerifyStandardProperty(property); // Namespace [InlineData("namespace", "N", "~N:N")] // Type [InlineData("type", "N.C+D", "~T:N.C.D")] // Field [InlineData("member", "N.C.#F", "~F:N.C.F")] // Property [InlineData("member", "N.C.#P", "~P:N.C.P")] // Method [InlineData("member", "N.C.#M", "~M:N.C.M")] // Generic method with parameters [InlineData("member", "N.C.#M2(!!0)", "~M:N.C.M2``1(``0)~System.Int32")] // Event [InlineData("member", "e:N.C.#E", "~E:N.C.E")] [Theory] public async Task LegacySuppressions(string scope, string target, string fixedTarget) { var input = $@" [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Scope = ""{scope}"", Target = {{|#0:""{target}""|}})] namespace N {{ class C {{ private int F; public int P {{ get; set; }} public void M() {{ }} public int M2<T>(T t) => 0; public event System.EventHandler<int> E; class D {{ }} }} }}"; var expectedDiagnostic = VerifyCS.Diagnostic(AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer.LegacyFormatTargetDescriptor) .WithLocation(0) .WithArguments(target); var fixedCode = $@" [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Scope = ""{scope}"", Target = ""{fixedTarget}"")] namespace N {{ class C {{ private int F; public int P {{ get; set; }} public void M() {{ }} public int M2<T>(T t) => 0; public event System.EventHandler<int> E; class D {{ }} }} }}"; await VerifyCS.VerifyCodeFixAsync(input, expectedDiagnostic, fixedCode); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.CSharp.RemoveUnnecessarySuppressions.CSharpRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer, Microsoft.CodeAnalysis.UpdateLegacySuppressions.UpdateLegacySuppressionsCodeFixProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UpdateLegacySuppressions { [Trait(Traits.Feature, Traits.Features.CodeActionsUpdateLegacySuppressions)] [WorkItem(44362, "https://github.com/dotnet/roslyn/issues/44362")] public class UpdateLegacySuppressionsTests { [Theory, CombinatorialData] public void TestStandardProperty(AnalyzerProperty property) => VerifyCS.VerifyStandardProperty(property); // Namespace [InlineData("namespace", "N", "~N:N")] // Type [InlineData("type", "N.C+D", "~T:N.C.D")] // Field [InlineData("member", "N.C.#F", "~F:N.C.F")] // Property [InlineData("member", "N.C.#P", "~P:N.C.P")] // Method [InlineData("member", "N.C.#M", "~M:N.C.M")] // Generic method with parameters [InlineData("member", "N.C.#M2(!!0)", "~M:N.C.M2``1(``0)~System.Int32")] // Event [InlineData("member", "e:N.C.#E", "~E:N.C.E")] [Theory] public async Task LegacySuppressions(string scope, string target, string fixedTarget) { var input = $@" [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Scope = ""{scope}"", Target = {{|#0:""{target}""|}})] namespace N {{ class C {{ private int F; public int P {{ get; set; }} public void M() {{ }} public int M2<T>(T t) => 0; public event System.EventHandler<int> E; class D {{ }} }} }}"; var expectedDiagnostic = VerifyCS.Diagnostic(AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer.LegacyFormatTargetDescriptor) .WithLocation(0) .WithArguments(target); var fixedCode = $@" [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Scope = ""{scope}"", Target = ""{fixedTarget}"")] namespace N {{ class C {{ private int F; public int P {{ get; set; }} public void M() {{ }} public int M2<T>(T t) => 0; public event System.EventHandler<int> E; class D {{ }} }} }}"; await VerifyCS.VerifyCodeFixAsync(input, expectedDiagnostic, fixedCode); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Analyzers/CSharp/Tests/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionFixAllTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertSwitchStatementToExpression { using VerifyCS = CSharpCodeFixVerifier< ConvertSwitchStatementToExpressionDiagnosticAnalyzer, ConvertSwitchStatementToExpressionCodeFixProvider>; public class ConvertSwitchStatementToExpressionFixAllTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)] public async Task TestNested_01() { await VerifyCS.VerifyCodeFixAsync( @"class Program { int M(int i, int j) { int r; [|switch|] (i) { case 1: r = 1; break; case 2: r = 2; break; case 3: r = 3; break; default: r = 4; break; } int x, y; switch (i) { case 1: x = 1; y = 1; break; case 2: x = 1; y = 1; break; case 3: x = 1; y = 1; break; default: x = 1; y = 1; break; } [|switch|] (i) { default: throw null; case 1: [|switch|] (j) { case 10: return 10; case 20: return 20; case 30: return 30; } return 0; case 2: [|switch|] (j) { case 10: return 10; case 20: return 20; case 30: return 30; case var _: return 0; } case 3: [|switch|] (j) { case 10: return 10; case 20: return 20; case 30: return 30; case var v: return 0; } } } }", @"class Program { int M(int i, int j) { var r = i switch { 1 => 1, 2 => 2, 3 => 3, _ => 4, }; int x, y; switch (i) { case 1: x = 1; y = 1; break; case 2: x = 1; y = 1; break; case 3: x = 1; y = 1; break; default: x = 1; y = 1; break; } return i switch { 1 => j switch { 10 => 10, 20 => 20, 30 => 30, _ => 0, }, 2 => j switch { 10 => 10, 20 => 20, 30 => 30, var _ => 0, }, 3 => j switch { 10 => 10, 20 => 20, 30 => 30, var v => 0, }, _ => throw null, }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)] public async Task TestNested_02() { var input = @"class Program { System.Func<int> M(int i, int j) { [|switch|] (i) { // 1 default: // 2 return () => { [|switch|] (j) { default: return 3; } }; } } }"; var expected = @"class Program { System.Func<int> M(int i, int j) { return i switch { // 1 // 2 _ => () => { return j switch { _ => 3, }; } , }; } }"; await new VerifyCS.Test { TestCode = input, FixedCode = expected, NumberOfFixAllIterations = 2, }.RunAsync(); } [WorkItem(37907, "https://github.com/dotnet/roslyn/issues/37907")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)] public async Task TestNested_03() { await VerifyCS.VerifyCodeFixAsync( @"using System; class Program { public static void Main() { } public DayOfWeek StatusValue() => DayOfWeek.Monday; public short Value => 0; public bool ValueBoolean() { bool value; [|switch|] (StatusValue()) { case DayOfWeek.Monday: [|switch|] (Value) { case 0: value = false; break; case 1: value = true; break; default: throw new Exception(); } break; default: throw new Exception(); } return value; } }", @"using System; class Program { public static void Main() { } public DayOfWeek StatusValue() => DayOfWeek.Monday; public short Value => 0; public bool ValueBoolean() { var value = StatusValue() switch { DayOfWeek.Monday => Value switch { 0 => false, 1 => true, _ => throw new Exception(), }, _ => throw new Exception(), }; return value; } }"); } [WorkItem(44572, "https://github.com/dotnet/roslyn/issues/44572")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)] public async Task TestImplicitConversion() { await VerifyCS.VerifyCodeFixAsync( @"using System; class C { public C(String s) => _s = s; private readonly String _s; public static implicit operator String(C value) => value._s; public static implicit operator C(String value) => new C(value); public bool method(C c) { [|switch|] (c) { case ""A"": return true; default: return false; } } }", @"using System; class C { public C(String s) => _s = s; private readonly String _s; public static implicit operator String(C value) => value._s; public static implicit operator C(String value) => new C(value); public bool method(C c) { return (string)c switch { ""A"" => true, _ => false, }; } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertSwitchStatementToExpression { using VerifyCS = CSharpCodeFixVerifier< ConvertSwitchStatementToExpressionDiagnosticAnalyzer, ConvertSwitchStatementToExpressionCodeFixProvider>; public class ConvertSwitchStatementToExpressionFixAllTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)] public async Task TestNested_01() { await VerifyCS.VerifyCodeFixAsync( @"class Program { int M(int i, int j) { int r; [|switch|] (i) { case 1: r = 1; break; case 2: r = 2; break; case 3: r = 3; break; default: r = 4; break; } int x, y; switch (i) { case 1: x = 1; y = 1; break; case 2: x = 1; y = 1; break; case 3: x = 1; y = 1; break; default: x = 1; y = 1; break; } [|switch|] (i) { default: throw null; case 1: [|switch|] (j) { case 10: return 10; case 20: return 20; case 30: return 30; } return 0; case 2: [|switch|] (j) { case 10: return 10; case 20: return 20; case 30: return 30; case var _: return 0; } case 3: [|switch|] (j) { case 10: return 10; case 20: return 20; case 30: return 30; case var v: return 0; } } } }", @"class Program { int M(int i, int j) { var r = i switch { 1 => 1, 2 => 2, 3 => 3, _ => 4, }; int x, y; switch (i) { case 1: x = 1; y = 1; break; case 2: x = 1; y = 1; break; case 3: x = 1; y = 1; break; default: x = 1; y = 1; break; } return i switch { 1 => j switch { 10 => 10, 20 => 20, 30 => 30, _ => 0, }, 2 => j switch { 10 => 10, 20 => 20, 30 => 30, var _ => 0, }, 3 => j switch { 10 => 10, 20 => 20, 30 => 30, var v => 0, }, _ => throw null, }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)] public async Task TestNested_02() { var input = @"class Program { System.Func<int> M(int i, int j) { [|switch|] (i) { // 1 default: // 2 return () => { [|switch|] (j) { default: return 3; } }; } } }"; var expected = @"class Program { System.Func<int> M(int i, int j) { return i switch { // 1 // 2 _ => () => { return j switch { _ => 3, }; } , }; } }"; await new VerifyCS.Test { TestCode = input, FixedCode = expected, NumberOfFixAllIterations = 2, }.RunAsync(); } [WorkItem(37907, "https://github.com/dotnet/roslyn/issues/37907")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)] public async Task TestNested_03() { await VerifyCS.VerifyCodeFixAsync( @"using System; class Program { public static void Main() { } public DayOfWeek StatusValue() => DayOfWeek.Monday; public short Value => 0; public bool ValueBoolean() { bool value; [|switch|] (StatusValue()) { case DayOfWeek.Monday: [|switch|] (Value) { case 0: value = false; break; case 1: value = true; break; default: throw new Exception(); } break; default: throw new Exception(); } return value; } }", @"using System; class Program { public static void Main() { } public DayOfWeek StatusValue() => DayOfWeek.Monday; public short Value => 0; public bool ValueBoolean() { var value = StatusValue() switch { DayOfWeek.Monday => Value switch { 0 => false, 1 => true, _ => throw new Exception(), }, _ => throw new Exception(), }; return value; } }"); } [WorkItem(44572, "https://github.com/dotnet/roslyn/issues/44572")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)] public async Task TestImplicitConversion() { await VerifyCS.VerifyCodeFixAsync( @"using System; class C { public C(String s) => _s = s; private readonly String _s; public static implicit operator String(C value) => value._s; public static implicit operator C(String value) => new C(value); public bool method(C c) { [|switch|] (c) { case ""A"": return true; default: return false; } } }", @"using System; class C { public C(String s) => _s = s; private readonly String _s; public static implicit operator String(C value) => value._s; public static implicit operator C(String value) => new C(value); public bool method(C c) { return (string)c switch { ""A"" => true, _ => false, }; } }"); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Workspaces/CoreTestUtilities/MEF/FeaturesTestCompositions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.UnitTests.Remote; namespace Microsoft.CodeAnalysis.Test.Utilities { public static class FeaturesTestCompositions { public static readonly TestComposition Features = TestComposition.Empty .AddAssemblies(MefHostServices.DefaultAssemblies) .AddParts( typeof(TestSerializerService.Factory), typeof(MockWorkspaceEventListenerProvider), // by default, avoid running Solution Crawler and other services that start in workspace event listeners typeof(TestErrorReportingService)); // mocks the info-bar error reporting public static readonly TestComposition RemoteHost = TestComposition.Empty .AddAssemblies(RemoteWorkspaceManager.RemoteHostAssemblies) .AddParts(typeof(TestSerializerService.Factory)); public static TestComposition WithTestHostParts(this TestComposition composition, TestHost host) => (host == TestHost.InProcess) ? composition : composition.AddAssemblies(typeof(RemoteWorkspacesResources).Assembly).AddParts(typeof(InProcRemoteHostClientProvider.Factory)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.UnitTests.Remote; namespace Microsoft.CodeAnalysis.Test.Utilities { public static class FeaturesTestCompositions { public static readonly TestComposition Features = TestComposition.Empty .AddAssemblies(MefHostServices.DefaultAssemblies) .AddParts( typeof(TestSerializerService.Factory), typeof(MockWorkspaceEventListenerProvider), // by default, avoid running Solution Crawler and other services that start in workspace event listeners typeof(TestErrorReportingService)); // mocks the info-bar error reporting public static readonly TestComposition RemoteHost = TestComposition.Empty .AddAssemblies(RemoteWorkspaceManager.RemoteHostAssemblies) .AddParts(typeof(TestSerializerService.Factory)); public static TestComposition WithTestHostParts(this TestComposition composition, TestHost host) => (host == TestHost.InProcess) ? composition : composition.AddAssemblies(typeof(RemoteWorkspacesResources).Assembly).AddParts(typeof(InProcRemoteHostClientProvider.Factory)); } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpUpgradeProject.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpUpgradeProject : AbstractUpdateProjectTest { public CSharpUpgradeProject(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } private void InvokeFix(string version = "latest") { VisualStudio.Editor.SetText(@$" #error version:{version} "); VisualStudio.Editor.Activate(); VisualStudio.Editor.PlaceCaret($"version:{version}"); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction($"Upgrade this project to C# language version '{version}'", applyFix: true); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/38301"), Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public void CPSProject_GeneralPropertyGroupUpdated() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.CreateSolution(SolutionName); VisualStudio.SolutionExplorer.AddProject(project, WellKnownProjectTemplates.CSharpNetStandardClassLibrary, LanguageNames.CSharp); VisualStudio.SolutionExplorer.RestoreNuGetPackages(project); InvokeFix(); VerifyPropertyOutsideConfiguration(GetProjectFileElement(project), "LangVersion", "latest"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public void LegacyProject_AllConfigurationsUpdated() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.CreateSolution(SolutionName); VisualStudio.SolutionExplorer.AddCustomProject(project, ".csproj", $@"<?xml version=""1.0"" encoding=""utf-8""?> <Project ToolsVersion=""15.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" Condition=""Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"" /> <PropertyGroup> <Configuration Condition=""'$(Configuration)' == ''"">Debug</Configuration> <Platform Condition=""'$(Platform)' == ''"">x64</Platform> <ProjectGuid>{{F4233BA4-A4CB-498B-BBC1-65A42206B1BA}}</ProjectGuid> <OutputType>Library</OutputType> <RootNamespace>{ProjectName}</RootNamespace> <AssemblyName>{ProjectName}</AssemblyName> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> <LangVersion>7.0</LangVersion> </PropertyGroup> <PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Debug|x86'""> <OutputPath>bin\x86\Debug\</OutputPath> <PlatformTarget>x86</PlatformTarget> </PropertyGroup> <PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Release|x86'""> <OutputPath>bin\x86\Release\</OutputPath> <PlatformTarget>x86</PlatformTarget> </PropertyGroup> <PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Debug|x64'""> <OutputPath>bin\x64\Debug\</OutputPath> <PlatformTarget>x64</PlatformTarget> </PropertyGroup> <PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Release|x64'""> <OutputPath>bin\x64\Release\</OutputPath> <PlatformTarget>x64</PlatformTarget> </PropertyGroup> <ItemGroup> </ItemGroup> <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" /> </Project>"); VisualStudio.SolutionExplorer.AddFile(project, "C.cs", open: true); InvokeFix(version: "7.3"); VerifyPropertyInEachConfiguration(GetProjectFileElement(project), "LangVersion", "7.3"); } [WorkItem(23342, "https://github.com/dotnet/roslyn/issues/23342")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public void LegacyProject_MultiplePlatforms_AllConfigurationsUpdated() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.CreateSolution(SolutionName); VisualStudio.SolutionExplorer.AddCustomProject(project, ".csproj", $@"<?xml version=""1.0"" encoding=""utf-8""?> <Project ToolsVersion=""15.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" Condition=""Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"" /> <PropertyGroup> <Configuration Condition=""'$(Configuration)' == ''"">Debug</Configuration> <Platform Condition=""'$(Platform)' == ''"">x64</Platform> <ProjectGuid>{{F4233BA4-A4CB-498B-BBC1-65A42206B1BA}}</ProjectGuid> <OutputType>Library</OutputType> <RootNamespace>{ProjectName}</RootNamespace> <AssemblyName>{ProjectName}</AssemblyName> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> </PropertyGroup> <PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Debug|x86'""> <OutputPath>bin\x86\Debug\</OutputPath> <PlatformTarget>x86</PlatformTarget> <LangVersion>7.2</LangVersion> </PropertyGroup> <PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Release|x86'""> <OutputPath>bin\x86\Release\</OutputPath> <PlatformTarget>x86</PlatformTarget> <LangVersion>7.1</LangVersion> </PropertyGroup> <PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Debug|x64'""> <OutputPath>bin\x64\Debug\</OutputPath> <PlatformTarget>x64</PlatformTarget> <LangVersion>7.0</LangVersion> </PropertyGroup> <PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Release|x64'""> <OutputPath>bin\x64\Release\</OutputPath> <PlatformTarget>x64</PlatformTarget> <LangVersion>7.1</LangVersion> </PropertyGroup> <ItemGroup> </ItemGroup> <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" /> </Project>"); VisualStudio.SolutionExplorer.AddFile(project, "C.cs", open: true); InvokeFix(version: "7.3"); VerifyPropertyInEachConfiguration(GetProjectFileElement(project), "LangVersion", "7.3"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpUpgradeProject : AbstractUpdateProjectTest { public CSharpUpgradeProject(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } private void InvokeFix(string version = "latest") { VisualStudio.Editor.SetText(@$" #error version:{version} "); VisualStudio.Editor.Activate(); VisualStudio.Editor.PlaceCaret($"version:{version}"); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction($"Upgrade this project to C# language version '{version}'", applyFix: true); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/38301"), Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public void CPSProject_GeneralPropertyGroupUpdated() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.CreateSolution(SolutionName); VisualStudio.SolutionExplorer.AddProject(project, WellKnownProjectTemplates.CSharpNetStandardClassLibrary, LanguageNames.CSharp); VisualStudio.SolutionExplorer.RestoreNuGetPackages(project); InvokeFix(); VerifyPropertyOutsideConfiguration(GetProjectFileElement(project), "LangVersion", "latest"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public void LegacyProject_AllConfigurationsUpdated() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.CreateSolution(SolutionName); VisualStudio.SolutionExplorer.AddCustomProject(project, ".csproj", $@"<?xml version=""1.0"" encoding=""utf-8""?> <Project ToolsVersion=""15.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" Condition=""Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"" /> <PropertyGroup> <Configuration Condition=""'$(Configuration)' == ''"">Debug</Configuration> <Platform Condition=""'$(Platform)' == ''"">x64</Platform> <ProjectGuid>{{F4233BA4-A4CB-498B-BBC1-65A42206B1BA}}</ProjectGuid> <OutputType>Library</OutputType> <RootNamespace>{ProjectName}</RootNamespace> <AssemblyName>{ProjectName}</AssemblyName> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> <LangVersion>7.0</LangVersion> </PropertyGroup> <PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Debug|x86'""> <OutputPath>bin\x86\Debug\</OutputPath> <PlatformTarget>x86</PlatformTarget> </PropertyGroup> <PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Release|x86'""> <OutputPath>bin\x86\Release\</OutputPath> <PlatformTarget>x86</PlatformTarget> </PropertyGroup> <PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Debug|x64'""> <OutputPath>bin\x64\Debug\</OutputPath> <PlatformTarget>x64</PlatformTarget> </PropertyGroup> <PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Release|x64'""> <OutputPath>bin\x64\Release\</OutputPath> <PlatformTarget>x64</PlatformTarget> </PropertyGroup> <ItemGroup> </ItemGroup> <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" /> </Project>"); VisualStudio.SolutionExplorer.AddFile(project, "C.cs", open: true); InvokeFix(version: "7.3"); VerifyPropertyInEachConfiguration(GetProjectFileElement(project), "LangVersion", "7.3"); } [WorkItem(23342, "https://github.com/dotnet/roslyn/issues/23342")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public void LegacyProject_MultiplePlatforms_AllConfigurationsUpdated() { var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.CreateSolution(SolutionName); VisualStudio.SolutionExplorer.AddCustomProject(project, ".csproj", $@"<?xml version=""1.0"" encoding=""utf-8""?> <Project ToolsVersion=""15.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" Condition=""Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"" /> <PropertyGroup> <Configuration Condition=""'$(Configuration)' == ''"">Debug</Configuration> <Platform Condition=""'$(Platform)' == ''"">x64</Platform> <ProjectGuid>{{F4233BA4-A4CB-498B-BBC1-65A42206B1BA}}</ProjectGuid> <OutputType>Library</OutputType> <RootNamespace>{ProjectName}</RootNamespace> <AssemblyName>{ProjectName}</AssemblyName> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> </PropertyGroup> <PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Debug|x86'""> <OutputPath>bin\x86\Debug\</OutputPath> <PlatformTarget>x86</PlatformTarget> <LangVersion>7.2</LangVersion> </PropertyGroup> <PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Release|x86'""> <OutputPath>bin\x86\Release\</OutputPath> <PlatformTarget>x86</PlatformTarget> <LangVersion>7.1</LangVersion> </PropertyGroup> <PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Debug|x64'""> <OutputPath>bin\x64\Debug\</OutputPath> <PlatformTarget>x64</PlatformTarget> <LangVersion>7.0</LangVersion> </PropertyGroup> <PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Release|x64'""> <OutputPath>bin\x64\Release\</OutputPath> <PlatformTarget>x64</PlatformTarget> <LangVersion>7.1</LangVersion> </PropertyGroup> <ItemGroup> </ItemGroup> <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" /> </Project>"); VisualStudio.SolutionExplorer.AddFile(project, "C.cs", open: true); InvokeFix(version: "7.3"); VerifyPropertyInEachConfiguration(GetProjectFileElement(project), "LangVersion", "7.3"); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/EditorFeatures/Core/xlf/EditorFeaturesResources.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="../EditorFeaturesResources.resx"> <body> <trans-unit id="All_methods"> <source>All methods</source> <target state="translated">Todos os métodos</target> <note /> </trans-unit> <trans-unit id="Always_for_clarity"> <source>Always for clarity</source> <target state="translated">Sempre para esclarecimento</target> <note /> </trans-unit> <trans-unit id="An_inline_rename_session_is_active_for_identifier_0"> <source>An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time.</source> <target state="translated">Uma sessão de renomeação embutida está ativa para o identificador '{0}'. Invoque a renomeação embutida novamente para acessar opções adicionais. Você pode continuar a editar o identificador que está sendo renomeado a qualquer momento.</target> <note>For screenreaders. {0} is the identifier being renamed.</note> </trans-unit> <trans-unit id="Applying_changes"> <source>Applying changes</source> <target state="translated">Aplicando mudanças</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_parameters"> <source>Avoid unused parameters</source> <target state="translated">Evitar parâmetros não utilizados</target> <note /> </trans-unit> <trans-unit id="Change_configuration"> <source>Change configuration</source> <target state="translated">Alterar configuração</target> <note /> </trans-unit> <trans-unit id="Code_cleanup_is_not_configured"> <source>Code cleanup is not configured</source> <target state="translated">A limpeza de código não está configurada</target> <note /> </trans-unit> <trans-unit id="Configure_it_now"> <source>Configure it now</source> <target state="translated">Configurar agora</target> <note /> </trans-unit> <trans-unit id="Do_not_prefer_this_or_Me"> <source>Do not prefer 'this.' or 'Me.'</source> <target state="translated">Não preferir 'this.' nem 'Me'.</target> <note /> </trans-unit> <trans-unit id="Do_not_show_this_message_again"> <source>Do not show this message again</source> <target state="translated">Não mostrar esta mensagem novamente</target> <note /> </trans-unit> <trans-unit id="Do_you_still_want_to_proceed_This_may_produce_broken_code"> <source>Do you still want to proceed? This may produce broken code.</source> <target state="translated">Ainda quer continuar? Isso pode produzir código desfeito.</target> <note /> </trans-unit> <trans-unit id="Expander_display_text"> <source>items from unimported namespaces</source> <target state="translated">itens de namespaces não importados</target> <note /> </trans-unit> <trans-unit id="Expander_image_element"> <source>Expander</source> <target state="translated">Expansor</target> <note /> </trans-unit> <trans-unit id="Extract_method_encountered_the_following_issues"> <source>Extract method encountered the following issues:</source> <target state="translated">O método de extração encontrou os seguintes problemas:</target> <note /> </trans-unit> <trans-unit id="Filter_image_element"> <source>Filter</source> <target state="translated">Filtrar</target> <note>Caption/tooltip for "Filter" image element displayed in completion popup.</note> </trans-unit> <trans-unit id="For_locals_parameters_and_members"> <source>For locals, parameters and members</source> <target state="translated">Para locais, parâmetros e membros</target> <note /> </trans-unit> <trans-unit id="For_member_access_expressions"> <source>For member access expressions</source> <target state="translated">Para expressões de acesso de membro</target> <note /> </trans-unit> <trans-unit id="Format_document_performed_additional_cleanup"> <source>Format Document performed additional cleanup</source> <target state="translated">A Formatação do Documento executou uma limpeza adicional</target> <note /> </trans-unit> <trans-unit id="Get_help_for_0"> <source>Get help for '{0}'</source> <target state="translated">Obter ajuda para '{0}'</target> <note /> </trans-unit> <trans-unit id="Get_help_for_0_from_Bing"> <source>Get help for '{0}' from Bing</source> <target state="translated">Obter ajuda para o '{0}' do Bing</target> <note /> </trans-unit> <trans-unit id="Gathering_Suggestions_0"> <source>Gathering Suggestions - '{0}'</source> <target state="translated">Obtendo Sugestões – '{0}'</target> <note /> </trans-unit> <trans-unit id="Gathering_Suggestions_Waiting_for_the_solution_to_fully_load"> <source>Gathering Suggestions - Waiting for the solution to fully load</source> <target state="translated">Obtendo Sugestões – aguardando a solução carregar totalmente</target> <note /> </trans-unit> <trans-unit id="Go_To_Base"> <source>Go To Base</source> <target state="translated">Ir Para a Base</target> <note /> </trans-unit> <trans-unit id="In_arithmetic_binary_operators"> <source>In arithmetic operators</source> <target state="translated">Em operadores aritméticos</target> <note /> </trans-unit> <trans-unit id="In_other_binary_operators"> <source>In other binary operators</source> <target state="translated">Em outros operadores binários</target> <note /> </trans-unit> <trans-unit id="In_other_operators"> <source>In other operators</source> <target state="translated">Em outros operadores</target> <note /> </trans-unit> <trans-unit id="In_relational_binary_operators"> <source>In relational operators</source> <target state="translated">Em operadores relacionais</target> <note /> </trans-unit> <trans-unit id="Indentation_Size"> <source>Indentation Size</source> <target state="translated">Tamanho do Recuo</target> <note /> </trans-unit> <trans-unit id="Inline_Hints"> <source>Inline Hints</source> <target state="translated">Dicas Embutidas</target> <note /> </trans-unit> <trans-unit id="Insert_Final_Newline"> <source>Insert Final Newline</source> <target state="translated">Inserir Nova Linha Final</target> <note /> </trans-unit> <trans-unit id="Invalid_assembly_name"> <source>Invalid assembly name</source> <target state="translated">Nome do assembly inválido</target> <note /> </trans-unit> <trans-unit id="Invalid_characters_in_assembly_name"> <source>Invalid characters in assembly name</source> <target state="translated">Caracteres inválidos no nome do assembly</target> <note /> </trans-unit> <trans-unit id="Keyword_Control"> <source>Keyword - Control</source> <target state="translated">Palavra-chave – Controle</target> <note /> </trans-unit> <trans-unit id="Locating_bases"> <source>Locating bases...</source> <target state="translated">Localizando as bases...</target> <note /> </trans-unit> <trans-unit id="Never_if_unnecessary"> <source>Never if unnecessary</source> <target state="translated">Nunca se desnecessário</target> <note /> </trans-unit> <trans-unit id="New_Line"> <source>New Line</source> <target state="translated">Nova Linha</target> <note /> </trans-unit> <trans-unit id="No"> <source>No</source> <target state="translated">Não</target> <note /> </trans-unit> <trans-unit id="Non_public_methods"> <source>Non-public methods</source> <target state="translated">Métodos não públicos</target> <note /> </trans-unit> <trans-unit id="Operator_Overloaded"> <source>Operator - Overloaded</source> <target state="translated">Operador – Sobrecarregado</target> <note /> </trans-unit> <trans-unit id="Paste_Tracking"> <source>Paste Tracking</source> <target state="translated">Colar Acompanhamento</target> <note /> </trans-unit> <trans-unit id="Prefer_System_HashCode_in_GetHashCode"> <source>Prefer 'System.HashCode' in 'GetHashCode'</source> <target state="translated">Prefira 'System.HashCode' em 'GetHashCode'</target> <note /> </trans-unit> <trans-unit id="Prefer_coalesce_expression"> <source>Prefer coalesce expression</source> <target state="translated">Preferir a expressão de união</target> <note /> </trans-unit> <trans-unit id="Prefer_collection_initializer"> <source>Prefer collection initializer</source> <target state="translated">Preferir o inicializador de coleção</target> <note /> </trans-unit> <trans-unit id="Prefer_compound_assignments"> <source>Prefer compound assignments</source> <target state="translated">Preferir atribuições de compostos</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_assignments"> <source>Prefer conditional expression over 'if' with assignments</source> <target state="translated">Preferir expressão condicional em vez de 'if' com atribuições</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_returns"> <source>Prefer conditional expression over 'if' with returns</source> <target state="translated">Preferir expressão condicional em vez de 'if' com retornos</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_tuple_name"> <source>Prefer explicit tuple name</source> <target state="translated">Preferir nome de tupla explícito</target> <note /> </trans-unit> <trans-unit id="Prefer_framework_type"> <source>Prefer framework type</source> <target state="translated">Preferir tipo de estrutura</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_anonymous_type_member_names"> <source>Prefer inferred anonymous type member names</source> <target state="translated">Prefira usar nomes de membro inferidos do tipo anônimo</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_tuple_names"> <source>Prefer inferred tuple element names</source> <target state="translated">Preferir usar nomes de elementos inferidos de tupla</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 /> </trans-unit> <trans-unit id="Prefer_null_propagation"> <source>Prefer null propagation</source> <target state="translated">Preferir tratamento simplificado de nulo</target> <note /> </trans-unit> <trans-unit id="Prefer_object_initializer"> <source>Prefer object initializer</source> <target state="translated">Preferir inicializador de objeto</target> <note /> </trans-unit> <trans-unit id="Prefer_predefined_type"> <source>Prefer predefined type</source> <target state="translated">Preferir tipo predefinido</target> <note /> </trans-unit> <trans-unit id="Prefer_readonly_fields"> <source>Prefer readonly fields</source> <target state="translated">Preferir campos readonly</target> <note /> </trans-unit> <trans-unit id="Prefer_simplified_boolean_expressions"> <source>Prefer simplified boolean expressions</source> <target state="translated">Preferir expressões boolianas simplificadas</target> <note /> </trans-unit> <trans-unit id="Prefer_this_or_Me"> <source>Prefer 'this.' or 'Me.'</source> <target state="translated">Preferir 'this.' ou 'Me.'</target> <note /> </trans-unit> <trans-unit id="Preprocessor_Text"> <source>Preprocessor Text</source> <target state="translated">Texto de Pré-Processador</target> <note /> </trans-unit> <trans-unit id="Punctuation"> <source>Punctuation</source> <target state="translated">Pontuação</target> <note /> </trans-unit> <trans-unit id="Qualify_event_access_with_this_or_Me"> <source>Qualify event access with 'this' or 'Me'</source> <target state="translated">Qualificar o acesso de evento com 'this' ou 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_field_access_with_this_or_Me"> <source>Qualify field access with 'this' or 'Me'</source> <target state="translated">Qualificar o acesso de campo com 'this' ou 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_method_access_with_this_or_Me"> <source>Qualify method access with 'this' or 'Me'</source> <target state="translated">Qualificar o acesso de método com 'this' ou 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_property_access_with_this_or_Me"> <source>Qualify property access with 'this' or 'Me'</source> <target state="translated">Qualificar o acesso de propriedade com 'this' ou 'Me'</target> <note /> </trans-unit> <trans-unit id="Reassigned_variable"> <source>Reassigned variable</source> <target state="new">Reassigned variable</target> <note /> </trans-unit> <trans-unit id="Rename_file_name_doesnt_match"> <source>Rename _file (type does not match file name)</source> <target state="translated">Renomear _arquivo (o tipo não corresponde ao nome do arquivo)</target> <note /> </trans-unit> <trans-unit id="Rename_file_partial_type"> <source>Rename _file (not allowed on partial types)</source> <target state="translated">Renomear _arquivo (não permitido em tipos parciais)</target> <note>Disabled text status for file rename</note> </trans-unit> <trans-unit id="Rename_symbols_file"> <source>Rename symbol's _file</source> <target state="translated">Renomear o _arquivo do símbolo</target> <note>Indicates that the file a symbol is defined in will also be renamed</note> </trans-unit> <trans-unit id="Split_comment"> <source>Split comment</source> <target state="translated">Dividir o comentário</target> <note /> </trans-unit> <trans-unit id="String_Escape_Character"> <source>String - Escape Character</source> <target state="translated">String - caractere de Escape</target> <note /> </trans-unit> <trans-unit id="Symbol_Static"> <source>Symbol - Static</source> <target state="translated">Símbolo – Estático</target> <note /> </trans-unit> <trans-unit id="Tab_Size"> <source>Tab Size</source> <target state="translated">Tamanho da Tabulação</target> <note /> </trans-unit> <trans-unit id="The_symbol_has_no_base"> <source>The symbol has no base.</source> <target state="translated">O símbolo não tem nenhuma base.</target> <note /> </trans-unit> <trans-unit id="Toggle_Block_Comment"> <source>Toggle Block Comment</source> <target state="translated">Ativar/Desativar Comentário de Bloco</target> <note /> </trans-unit> <trans-unit id="Toggle_Line_Comment"> <source>Toggle Line Comment</source> <target state="translated">Ativar/Desativar Comentário de Linha</target> <note /> </trans-unit> <trans-unit id="Toggling_block_comment"> <source>Toggling block comment...</source> <target state="translated">Ativando/desativando o comentário de bloco...</target> <note /> </trans-unit> <trans-unit id="Toggling_line_comment"> <source>Toggling line comment...</source> <target state="translated">Ativando/desativando o comentário de linha...</target> <note /> </trans-unit> <trans-unit id="Use_Tabs"> <source>Use Tabs</source> <target state="translated">Usar Tabulações</target> <note /> </trans-unit> <trans-unit id="User_Members_Constants"> <source>User Members - Constants</source> <target state="translated">Membros de Usuário – Constantes</target> <note /> </trans-unit> <trans-unit id="User_Members_Enum_Members"> <source>User Members - Enum Members</source> <target state="translated">Membros de Usuário – Membros Enum</target> <note /> </trans-unit> <trans-unit id="User_Members_Events"> <source>User Members - Events</source> <target state="translated">Membros de Usuário – Eventos</target> <note /> </trans-unit> <trans-unit id="User_Members_Extension_Methods"> <source>User Members - Extension Methods</source> <target state="translated">Membros de Usuário – Métodos de Extensão</target> <note /> </trans-unit> <trans-unit id="User_Members_Fields"> <source>User Members - Fields</source> <target state="translated">Membros de Usuário – Campos</target> <note /> </trans-unit> <trans-unit id="User_Members_Labels"> <source>User Members - Labels</source> <target state="translated">Membros de Usuário – Rótulos</target> <note /> </trans-unit> <trans-unit id="User_Members_Locals"> <source>User Members - Locals</source> <target state="translated">Membros de Usuário – Locais</target> <note /> </trans-unit> <trans-unit id="User_Members_Methods"> <source>User Members - Methods</source> <target state="translated">Membros de Usuário – Métodos</target> <note /> </trans-unit> <trans-unit id="User_Members_Namespaces"> <source>User Members - Namespaces</source> <target state="translated">Membros de Usuário – Namespaces</target> <note /> </trans-unit> <trans-unit id="User_Members_Parameters"> <source>User Members - Parameters</source> <target state="translated">Membros de Usuário – Parâmetros</target> <note /> </trans-unit> <trans-unit id="User_Members_Properties"> <source>User Members - Properties</source> <target state="translated">Membros de Usuário – Propriedades</target> <note /> </trans-unit> <trans-unit id="User_Types_Classes"> <source>User Types - Classes</source> <target state="translated">Tipos de Usuário - Classes</target> <note /> </trans-unit> <trans-unit id="User_Types_Delegates"> <source>User Types - Delegates</source> <target state="translated">Tipos de Usuário - Representantes</target> <note /> </trans-unit> <trans-unit id="User_Types_Enums"> <source>User Types - Enums</source> <target state="translated">Tipos de Usuário - Enums</target> <note /> </trans-unit> <trans-unit id="User_Types_Interfaces"> <source>User Types - Interfaces</source> <target state="translated">Tipos de Usuário - Interfaces</target> <note /> </trans-unit> <trans-unit id="User_Types_Record_Structs"> <source>User Types - Record Structs</source> <target state="translated">Tipos de usuário - Registro de structs</target> <note /> </trans-unit> <trans-unit id="User_Types_Records"> <source>User Types - Records</source> <target state="translated">Tipos de Usuário – Registros</target> <note /> </trans-unit> <trans-unit id="User_Types_Structures"> <source>User Types - Structures</source> <target state="translated">Tipos de Usuário - Estruturas</target> <note /> </trans-unit> <trans-unit id="User_Types_Type_Parameters"> <source>User Types - Type Parameters</source> <target state="translated">Tipos de Usuário - Parâmetros de Tipo</target> <note /> </trans-unit> <trans-unit id="String_Verbatim"> <source>String - Verbatim</source> <target state="translated">Cadeia de caracteres - Textual</target> <note /> </trans-unit> <trans-unit id="Waiting_for_background_work_to_finish"> <source>Waiting for background work to finish...</source> <target state="translated">Aguardando a conclusão do trabalho em segundo plano...</target> <note /> </trans-unit> <trans-unit id="Warning_image_element"> <source>Warning</source> <target state="translated">Aviso</target> <note>Caption/tooltip for "Warning" image element displayed in completion popup.</note> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Name"> <source>XML Doc Comments - Attribute Name</source> <target state="translated">Comentário da documentação XML - Nome de Atributo</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_CData_Section"> <source>XML Doc Comments - CData Section</source> <target state="translated">Comentário da documentação XML - Seção CData</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Text"> <source>XML Doc Comments - Text</source> <target state="translated">Comentário da documentação XML - Texto</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Delimiter"> <source>XML Doc Comments - Delimiter</source> <target state="translated">Comentário da documentação XML - Delimitador</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Comment"> <source>XML Doc Comments - Comment</source> <target state="translated">Comentário da documentação XML - Comentário</target> <note /> </trans-unit> <trans-unit id="User_Types_Modules"> <source>User Types - Modules</source> <target state="translated">Tipos de Usuário - Módulos</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Name"> <source>VB XML Literals - Attribute Name</source> <target state="translated">Literais XML do VB - Nome de Atributo</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Quotes"> <source>VB XML Literals - Attribute Quotes</source> <target state="translated">Literais XML do VB - Aspas de Atributo</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Value"> <source>VB XML Literals - Attribute Value</source> <target state="translated">Literais XML do VB - Valor de Atributo</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_CData_Section"> <source>VB XML Literals - CData Section</source> <target state="translated">Literais XML do VB - Seção CData</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Comment"> <source>VB XML Literals - Comment</source> <target state="translated">Literais XML do VB - Comentário</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Delimiter"> <source>VB XML Literals - Delimiter</source> <target state="translated">Literais XML do VB - Delimitador</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Embedded_Expression"> <source>VB XML Literals - Embedded Expression</source> <target state="translated">Literais XML do VB - Expressão Inserida</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Entity_Reference"> <source>VB XML Literals - Entity Reference</source> <target state="translated">Literais XML do VB - Referência de Entidade</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Name"> <source>VB XML Literals - Name</source> <target state="translated">Literais XML do VB - Nome</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Processing_Instruction"> <source>VB XML Literals - Processing Instruction</source> <target state="translated">Literais XML do VB - Instrução de Processamento</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Text"> <source>VB XML Literals - Text</source> <target state="translated">Literais XML do VB - Texto</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Quotes"> <source>XML Doc Comments - Attribute Quotes</source> <target state="translated">Comentário da documentação XML - Aspas de Atributo</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Value"> <source>XML Doc Comments - Attribute Value</source> <target state="translated">Comentário da documentação XML - Valor de Atributo</target> <note /> </trans-unit> <trans-unit id="Unnecessary_Code"> <source>Unnecessary Code</source> <target state="translated">Código Desnecessário</target> <note /> </trans-unit> <trans-unit id="Rude_Edit"> <source>Rude Edit</source> <target state="translated">Edição Rudimentar</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_1_reference_in_1_file"> <source>Rename will update 1 reference in 1 file.</source> <target state="translated">Renomear atualizará 1 referência em 1 arquivo.</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_0_references_in_1_file"> <source>Rename will update {0} references in 1 file.</source> <target state="translated">Renomear atualizará {0} referências em 1 arquivo.</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_0_references_in_1_files"> <source>Rename will update {0} references in {1} files.</source> <target state="translated">Renomear atualizará {0} referências em {1} arquivos.</target> <note /> </trans-unit> <trans-unit id="Yes"> <source>Yes</source> <target state="translated">Sim</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element_because_it_is_contained_in_a_read_only_file"> <source>You cannot rename this element because it is contained in a read-only file.</source> <target state="translated">Você não pode renomear este elemento porque ele está contido em um arquivo somente leitura.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element_because_it_is_in_a_location_that_cannot_be_navigated_to"> <source>You cannot rename this element because it is in a location that cannot be navigated to.</source> <target state="translated">Você não pode renomear este elemento porque ele está em um local para o qual não é possível navegar.</target> <note /> </trans-unit> <trans-unit id="_0_bases"> <source>'{0}' bases</source> <target state="translated">Bases '{0}'</target> <note /> </trans-unit> <trans-unit id="_0_conflict_s_will_be_resolved"> <source>{0} conflict(s) will be resolved</source> <target state="translated">{0} conflito(s) será(ão) resolvido(s)</target> <note /> </trans-unit> <trans-unit id="_0_implemented_members"> <source>'{0}' implemented members</source> <target state="translated">'{0}' membros implementados</target> <note /> </trans-unit> <trans-unit id="_0_unresolvable_conflict_s"> <source>{0} unresolvable conflict(s)</source> <target state="translated">{0} conflito(s) não solucionável(is)</target> <note /> </trans-unit> <trans-unit id="Applying_0"> <source>Applying "{0}"...</source> <target state="translated">Aplicando "{0}"...</target> <note /> </trans-unit> <trans-unit id="Adding_0_to_1_with_content_colon"> <source>Adding '{0}' to '{1}' with content:</source> <target state="translated">Adicionando "{0}" a "{1}" com conteúdo:</target> <note /> </trans-unit> <trans-unit id="Adding_project_0"> <source>Adding project '{0}'</source> <target state="translated">Adicionando projeto "{0}"</target> <note /> </trans-unit> <trans-unit id="Removing_project_0"> <source>Removing project '{0}'</source> <target state="translated">Removendo projeto "{0}"</target> <note /> </trans-unit> <trans-unit id="Changing_project_references_for_0"> <source>Changing project references for '{0}'</source> <target state="translated">Alterar referências de projeto para "{0}"</target> <note /> </trans-unit> <trans-unit id="Adding_reference_0_to_1"> <source>Adding reference '{0}' to '{1}'</source> <target state="translated">Adicionando referência "{0}" a "{1}"</target> <note /> </trans-unit> <trans-unit id="Removing_reference_0_from_1"> <source>Removing reference '{0}' from '{1}'</source> <target state="translated">Removendo referência "{0}" de "{1}"</target> <note /> </trans-unit> <trans-unit id="Adding_analyzer_reference_0_to_1"> <source>Adding analyzer reference '{0}' to '{1}'</source> <target state="translated">Adicionando referência de analisador "{0}" a "{1}"</target> <note /> </trans-unit> <trans-unit id="Removing_analyzer_reference_0_from_1"> <source>Removing analyzer reference '{0}' from '{1}'</source> <target state="translated">Removendo referência do analisador "{0}" de "{1}"</target> <note /> </trans-unit> <trans-unit id="XML_End_Tag_Completion"> <source>XML End Tag Completion</source> <target state="translated">Conclusão da Marca de Fim do XML</target> <note /> </trans-unit> <trans-unit id="Completing_Tag"> <source>Completing Tag</source> <target state="translated">Completando a Tag</target> <note /> </trans-unit> <trans-unit id="Encapsulate_Field"> <source>Encapsulate Field</source> <target state="translated">Encapsular Campo</target> <note /> </trans-unit> <trans-unit id="Applying_Encapsulate_Field_refactoring"> <source>Applying "Encapsulate Field" refactoring...</source> <target state="translated">Aplicando refatoração "Encapsular Campo"...</target> <note /> </trans-unit> <trans-unit id="Please_select_the_definition_of_the_field_to_encapsulate"> <source>Please select the definition of the field to encapsulate.</source> <target state="translated">Selecione a definição do campo a encapsular.</target> <note /> </trans-unit> <trans-unit id="Given_Workspace_doesn_t_support_Undo"> <source>Given Workspace doesn't support Undo</source> <target state="translated">Workspace fornecido não suporta Desfazer</target> <note /> </trans-unit> <trans-unit id="Searching"> <source>Searching...</source> <target state="translated">Pesquisando...</target> <note /> </trans-unit> <trans-unit id="Canceled"> <source>Canceled.</source> <target state="translated">Cancelado.</target> <note /> </trans-unit> <trans-unit id="No_information_found"> <source>No information found.</source> <target state="translated">Nenhuma informação encontrada.</target> <note /> </trans-unit> <trans-unit id="No_usages_found"> <source>No usages found.</source> <target state="translated">Nenhum uso encontrado.</target> <note /> </trans-unit> <trans-unit id="Implements_"> <source>Implements</source> <target state="translated">Implementos</target> <note /> </trans-unit> <trans-unit id="Implemented_By"> <source>Implemented By</source> <target state="translated">Implementado por</target> <note /> </trans-unit> <trans-unit id="Overrides_"> <source>Overrides</source> <target state="translated">Substitui</target> <note /> </trans-unit> <trans-unit id="Overridden_By"> <source>Overridden By</source> <target state="translated">Substituído por</target> <note /> </trans-unit> <trans-unit id="Directly_Called_In"> <source>Directly Called In</source> <target state="translated">Chamado Diretamente</target> <note /> </trans-unit> <trans-unit id="Indirectly_Called_In"> <source>Indirectly Called In</source> <target state="translated">Chamado Indiretamente </target> <note /> </trans-unit> <trans-unit id="Called_In"> <source>Called In</source> <target state="translated">Chamado Em</target> <note /> </trans-unit> <trans-unit id="Referenced_In"> <source>Referenced In</source> <target state="translated">Referenciado Em</target> <note /> </trans-unit> <trans-unit id="No_references_found"> <source>No references found.</source> <target state="translated">Nenhuma referência encontrada.</target> <note /> </trans-unit> <trans-unit id="No_derived_types_found"> <source>No derived types found.</source> <target state="translated">Nenhum tipo derivado encontrado.</target> <note /> </trans-unit> <trans-unit id="No_implementations_found"> <source>No implementations found.</source> <target state="translated">Nenhuma implementação encontrada.</target> <note /> </trans-unit> <trans-unit id="_0_Line_1"> <source>{0} - (Line {1})</source> <target state="translated">{0} - (Linha {1})</target> <note /> </trans-unit> <trans-unit id="Class_Parts"> <source>Class Parts</source> <target state="translated">Partes de Classe</target> <note /> </trans-unit> <trans-unit id="Struct_Parts"> <source>Struct Parts</source> <target state="translated">Partes de Struct</target> <note /> </trans-unit> <trans-unit id="Interface_Parts"> <source>Interface Parts</source> <target state="translated">Componentes da Interface</target> <note /> </trans-unit> <trans-unit id="Type_Parts"> <source>Type Parts</source> <target state="translated">Partes do Tipo</target> <note /> </trans-unit> <trans-unit id="Inherits_"> <source>Inherits</source> <target state="translated">Herda</target> <note /> </trans-unit> <trans-unit id="Inherited_By"> <source>Inherited By</source> <target state="translated">Herdado por</target> <note /> </trans-unit> <trans-unit id="Already_tracking_document_with_identical_key"> <source>Already tracking document with identical key</source> <target state="translated">Já está a rastrear o documento com chave idêntica</target> <note /> </trans-unit> <trans-unit id="analyzer_Prefer_auto_properties"> <source>Prefer auto properties</source> <target state="translated">Preferir propriedades automáticas</target> <note /> </trans-unit> <trans-unit id="document_is_not_currently_being_tracked"> <source>document is not currently being tracked</source> <target state="translated">documento não está sendo rastreado no momento</target> <note /> </trans-unit> <trans-unit id="Computing_Rename_information"> <source>Computing Rename information...</source> <target state="translated">Computando informações de Renomeação...</target> <note /> </trans-unit> <trans-unit id="Updating_files"> <source>Updating files...</source> <target state="translated">Atualizando arquivos...</target> <note /> </trans-unit> <trans-unit id="Rename_operation_was_cancelled_or_is_not_valid"> <source>Rename operation was cancelled or is not valid</source> <target state="translated">A operação de renomear foi cancelada ou não é válida</target> <note /> </trans-unit> <trans-unit id="Rename_Symbol"> <source>Rename Symbol</source> <target state="translated">Renomear Símbolo</target> <note /> </trans-unit> <trans-unit id="Text_Buffer_Change"> <source>Text Buffer Change</source> <target state="translated">Alteração no Buffer de Texto</target> <note /> </trans-unit> <trans-unit id="Rename_operation_was_not_properly_completed_Some_file_might_not_have_been_updated"> <source>Rename operation was not properly completed. Some file might not have been updated.</source> <target state="translated">A operação de renomear não foi corretamente concluída. Algum arquivo pode não ter sido atualizado.</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1"> <source>Rename '{0}' to '{1}'</source> <target state="translated">Renomear "{0}" para "{1}"</target> <note /> </trans-unit> <trans-unit id="Preview_Warning"> <source>Preview Warning</source> <target state="translated">Aviso de Visualização</target> <note /> </trans-unit> <trans-unit id="external"> <source>(external)</source> <target state="translated">(externo)</target> <note /> </trans-unit> <trans-unit id="Automatic_Line_Ender"> <source>Automatic Line Ender</source> <target state="translated">Finalizador de Linha Automático</target> <note /> </trans-unit> <trans-unit id="Automatically_completing"> <source>Automatically completing...</source> <target state="translated">Concluindo automaticamente...</target> <note /> </trans-unit> <trans-unit id="Automatic_Pair_Completion"> <source>Automatic Pair Completion</source> <target state="translated">Conclusão de Pares Automática</target> <note /> </trans-unit> <trans-unit id="An_active_inline_rename_session_is_still_active_Complete_it_before_starting_a_new_one"> <source>An active inline rename session is still active. Complete it before starting a new one.</source> <target state="translated">Uma sessão de renomeação embutida ativa ainda está ativa. Conclua-a antes de iniciar uma nova.</target> <note /> </trans-unit> <trans-unit id="The_buffer_is_not_part_of_a_workspace"> <source>The buffer is not part of a workspace.</source> <target state="translated">O buffer não é parte de um workspace.</target> <note /> </trans-unit> <trans-unit id="The_token_is_not_contained_in_the_workspace"> <source>The token is not contained in the workspace.</source> <target state="translated">O token não está contido no workspace.</target> <note /> </trans-unit> <trans-unit id="You_must_rename_an_identifier"> <source>You must rename an identifier.</source> <target state="translated">Você deve renomear um identificador.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element"> <source>You cannot rename this element.</source> <target state="translated">Você não pode renomear este elemento.</target> <note /> </trans-unit> <trans-unit id="Please_resolve_errors_in_your_code_before_renaming_this_element"> <source>Please resolve errors in your code before renaming this element.</source> <target state="translated">Resolva erros em seu código antes de renomear este elemento.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_operators"> <source>You cannot rename operators.</source> <target state="translated">Você não pode renomear operadores.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_elements_that_are_defined_in_metadata"> <source>You cannot rename elements that are defined in metadata.</source> <target state="translated">Você não pode renomear elementos que estão definidos nos metadados.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_elements_from_previous_submissions"> <source>You cannot rename elements from previous submissions.</source> <target state="translated">Você não pode renomear elementos de envios anteriores.</target> <note /> </trans-unit> <trans-unit id="Navigation_Bars"> <source>Navigation Bars</source> <target state="translated">Barras de Navegação</target> <note /> </trans-unit> <trans-unit id="Refreshing_navigation_bars"> <source>Refreshing navigation bars...</source> <target state="translated">Atualizando barras de navegação...</target> <note /> </trans-unit> <trans-unit id="Format_Token"> <source>Format Token</source> <target state="translated">Token de Formato</target> <note /> </trans-unit> <trans-unit id="Smart_Indenting"> <source>Smart Indenting</source> <target state="translated">Recuo Inteligente</target> <note /> </trans-unit> <trans-unit id="Find_References"> <source>Find References</source> <target state="translated">Localizar Referências</target> <note /> </trans-unit> <trans-unit id="Finding_references"> <source>Finding references...</source> <target state="translated">Localizando referências...</target> <note /> </trans-unit> <trans-unit id="Finding_references_of_0"> <source>Finding references of "{0}"...</source> <target state="translated">Localizando referências de "{0}"...</target> <note /> </trans-unit> <trans-unit id="Comment_Selection"> <source>Comment Selection</source> <target state="translated">Comentar Seleção</target> <note /> </trans-unit> <trans-unit id="Uncomment_Selection"> <source>Uncomment Selection</source> <target state="translated">Remover Comentários da Seleção</target> <note /> </trans-unit> <trans-unit id="Commenting_currently_selected_text"> <source>Commenting currently selected text...</source> <target state="translated">Comentando o texto selecionado no momento...</target> <note /> </trans-unit> <trans-unit id="Uncommenting_currently_selected_text"> <source>Uncommenting currently selected text...</source> <target state="translated">Removendo marca de comentário do texto selecionado no momento...</target> <note /> </trans-unit> <trans-unit id="Insert_new_line"> <source>Insert new line</source> <target state="translated">Inserir Nova Linha</target> <note /> </trans-unit> <trans-unit id="Documentation_Comment"> <source>Documentation Comment</source> <target state="translated">Comentário de Documentação</target> <note /> </trans-unit> <trans-unit id="Inserting_documentation_comment"> <source>Inserting documentation comment...</source> <target state="translated">Inserindo comentário da documentação...</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="Applying_Extract_Method_refactoring"> <source>Applying "Extract Method" refactoring...</source> <target state="translated">Aplicando refatoração "Extrair Método"...</target> <note /> </trans-unit> <trans-unit id="Format_Document"> <source>Format Document</source> <target state="translated">Formatar Documento</target> <note /> </trans-unit> <trans-unit id="Formatting_document"> <source>Formatting document...</source> <target state="translated">Formatando documento...</target> <note /> </trans-unit> <trans-unit id="Formatting"> <source>Formatting</source> <target state="translated">Formatação</target> <note /> </trans-unit> <trans-unit id="Format_Selection"> <source>Format Selection</source> <target state="translated">Formatar Seleção</target> <note /> </trans-unit> <trans-unit id="Formatting_currently_selected_text"> <source>Formatting currently selected text...</source> <target state="translated">Formatando texto selecionado no momento...</target> <note /> </trans-unit> <trans-unit id="Cannot_navigate_to_the_symbol_under_the_caret"> <source>Cannot navigate to the symbol under the caret.</source> <target state="translated">Não é possível navegar para o símbolo sob o cursor.</target> <note /> </trans-unit> <trans-unit id="Go_to_Definition"> <source>Go to Definition</source> <target state="translated">Ir para Definição</target> <note /> </trans-unit> <trans-unit id="Navigating_to_definition"> <source>Navigating to definition...</source> <target state="translated">Navegando para definição...</target> <note /> </trans-unit> <trans-unit id="Organize_Document"> <source>Organize Document</source> <target state="translated">Organizar Documento</target> <note /> </trans-unit> <trans-unit id="Organizing_document"> <source>Organizing document...</source> <target state="translated">Organizando documento...</target> <note /> </trans-unit> <trans-unit id="Highlighted_Definition"> <source>Highlighted Definition</source> <target state="translated">Definição Realçada</target> <note /> </trans-unit> <trans-unit id="The_new_name_is_not_a_valid_identifier"> <source>The new name is not a valid identifier.</source> <target state="translated">O novo nome não é um identificador válido.</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Fixup"> <source>Inline Rename Fixup</source> <target state="translated">Correção de Renomeação Embutida</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Resolved_Conflict"> <source>Inline Rename Resolved Conflict</source> <target state="translated">Conflito de Renomeação Embutida Resolvido </target> <note /> </trans-unit> <trans-unit id="Inline_Rename"> <source>Inline Rename</source> <target state="translated">Renomeação embutida</target> <note /> </trans-unit> <trans-unit id="Rename"> <source>Rename</source> <target state="translated">renomear</target> <note /> </trans-unit> <trans-unit id="Start_Rename"> <source>Start Rename</source> <target state="translated">Iniciar Renomeação</target> <note /> </trans-unit> <trans-unit id="Display_conflict_resolutions"> <source>Display conflict resolutions</source> <target state="translated">Exibir resoluções de conflitos</target> <note /> </trans-unit> <trans-unit id="Finding_token_to_rename"> <source>Finding token to rename...</source> <target state="translated">Localizando token para renomear...</target> <note /> </trans-unit> <trans-unit id="Conflict"> <source>Conflict</source> <target state="translated">Conflito</target> <note /> </trans-unit> <trans-unit id="Text_Navigation"> <source>Text Navigation</source> <target state="translated">Navegação de Texto</target> <note /> </trans-unit> <trans-unit id="Finding_word_extent"> <source>Finding word extent...</source> <target state="translated">Localizando de extensão de palavra...</target> <note /> </trans-unit> <trans-unit id="Finding_enclosing_span"> <source>Finding enclosing span...</source> <target state="translated">Localizando alcance de delimitação...</target> <note /> </trans-unit> <trans-unit id="Finding_span_of_next_sibling"> <source>Finding span of next sibling...</source> <target state="translated">Localizando a extensão do próximo irmão...</target> <note /> </trans-unit> <trans-unit id="Finding_span_of_previous_sibling"> <source>Finding span of previous sibling...</source> <target state="translated">Localizando a extensão do irmão anterior...</target> <note /> </trans-unit> <trans-unit id="Rename_colon_0"> <source>Rename: {0}</source> <target state="translated">Renomear: {0}</target> <note /> </trans-unit> <trans-unit id="Light_bulb_session_is_already_dismissed"> <source>Light bulb session is already dismissed.</source> <target state="translated">A sessão de lâmpada já foi descartada.</target> <note /> </trans-unit> <trans-unit id="Automatic_Pair_Completion_End_Point_Marker_Color"> <source>Automatic Pair Completion End Point Marker Color</source> <target state="translated">Cor do Marcador de Ponto Final da Conclusão de Pares Automática</target> <note /> </trans-unit> <trans-unit id="Renaming_anonymous_type_members_is_not_yet_supported"> <source>Renaming anonymous type members is not yet supported.</source> <target state="translated">Renomear membros de tipo anônimo ainda não é suportado.</target> <note /> </trans-unit> <trans-unit id="Engine_must_be_attached_to_an_Interactive_Window"> <source>Engine must be attached to an Interactive Window.</source> <target state="translated">O Mecanismo deve ser anexado a uma Janela Interativa.</target> <note /> </trans-unit> <trans-unit id="Changes_the_current_prompt_settings"> <source>Changes the current prompt settings.</source> <target state="translated">Altera as configurações de prompt atuais.</target> <note /> </trans-unit> <trans-unit id="Unexpected_text_colon_0"> <source>Unexpected text: '{0}'</source> <target state="translated">Texto inesperado: "{0}"</target> <note /> </trans-unit> <trans-unit id="The_triggerSpan_is_not_included_in_the_given_workspace"> <source>The triggerSpan is not included in the given workspace.</source> <target state="translated">O triggerSpan não está incluído no workspace fornecido.</target> <note /> </trans-unit> <trans-unit id="This_session_has_already_been_dismissed"> <source>This session has already been dismissed.</source> <target state="translated">Esta sessão já foi descartada.</target> <note /> </trans-unit> <trans-unit id="The_transaction_is_already_complete"> <source>The transaction is already complete.</source> <target state="translated">A transação já está concluída.</target> <note /> </trans-unit> <trans-unit id="Not_a_source_error_line_column_unavailable"> <source>Not a source error, line/column unavailable</source> <target state="translated">Não é um erro de origem, linha/coluna disponível</target> <note /> </trans-unit> <trans-unit id="Can_t_compare_positions_from_different_text_snapshots"> <source>Can't compare positions from different text snapshots</source> <target state="translated">Não é possível comparar as posições de instantâneos de textos diferentes</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Entity_Reference"> <source>XML Doc Comments - Entity Reference</source> <target state="translated">Comentário da documentação XML - Referência de Entidade</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Name"> <source>XML Doc Comments - Name</source> <target state="translated">Comentário da documentação XML - Nome</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Processing_Instruction"> <source>XML Doc Comments - Processing Instruction</source> <target state="translated">Comentário da documentação XML - Instrução de Processamento</target> <note /> </trans-unit> <trans-unit id="Active_Statement"> <source>Active Statement</source> <target state="translated">Instrução Ativa</target> <note /> </trans-unit> <trans-unit id="Loading_Peek_information"> <source>Loading Peek information...</source> <target state="translated">Carregando informações de Espiada...</target> <note /> </trans-unit> <trans-unit id="Peek"> <source>Peek</source> <target state="translated">Espiada</target> <note /> </trans-unit> <trans-unit id="Apply1"> <source>_Apply</source> <target state="translated">_Aplicar</target> <note /> </trans-unit> <trans-unit id="Include_overload_s"> <source>Include _overload(s)</source> <target state="translated">Incluir _overload(s)</target> <note /> </trans-unit> <trans-unit id="Include_comments"> <source>Include _comments</source> <target state="translated">Incluir _comments</target> <note /> </trans-unit> <trans-unit id="Include_strings"> <source>Include _strings</source> <target state="translated">Incluir _strings</target> <note /> </trans-unit> <trans-unit id="Apply2"> <source>Apply</source> <target state="translated">Aplicar</target> <note /> </trans-unit> <trans-unit id="Change_Signature"> <source>Change Signature</source> <target state="translated">Alterar Assinatura</target> <note /> </trans-unit> <trans-unit id="Preview_Changes_0"> <source>Preview Changes - {0}</source> <target state="translated">Visualizar Alterações - {0}</target> <note /> </trans-unit> <trans-unit id="Preview_Code_Changes_colon"> <source>Preview Code Changes:</source> <target state="translated">Visualizar Alterações de Código:</target> <note /> </trans-unit> <trans-unit id="Preview_Changes"> <source>Preview Changes</source> <target state="translated">Visualizar Alterações</target> <note /> </trans-unit> <trans-unit id="Format_Paste"> <source>Format Paste</source> <target state="translated">Colar Formato</target> <note /> </trans-unit> <trans-unit id="Formatting_pasted_text"> <source>Formatting pasted text...</source> <target state="translated">Formatando texto colado...</target> <note /> </trans-unit> <trans-unit id="The_definition_of_the_object_is_hidden"> <source>The definition of the object is hidden.</source> <target state="translated">A definição do objeto está oculta.</target> <note /> </trans-unit> <trans-unit id="Automatic_Formatting"> <source>Automatic Formatting</source> <target state="translated">Formatação Automática</target> <note /> </trans-unit> <trans-unit id="We_can_fix_the_error_by_not_making_struct_out_ref_parameter_s_Do_you_want_to_proceed"> <source>We can fix the error by not making struct "out/ref" parameter(s). Do you want to proceed?</source> <target state="translated">Podemos corrigir o erro ao não fazer struct de parâmetro(s) "out/ref". Deseja continuar?</target> <note /> </trans-unit> <trans-unit id="Change_Signature_colon"> <source>Change Signature:</source> <target state="translated">Alterar Assinatura:</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1_colon"> <source>Rename '{0}' to '{1}':</source> <target state="translated">Renomear '{0}' para '{1}':</target> <note /> </trans-unit> <trans-unit id="Encapsulate_Field_colon"> <source>Encapsulate Field:</source> <target state="translated">Encapsular Campo:</target> <note /> </trans-unit> <trans-unit id="Call_Hierarchy"> <source>Call Hierarchy</source> <target state="translated">Hierarquia de Chamada</target> <note /> </trans-unit> <trans-unit id="Calls_To_0"> <source>Calls To '{0}'</source> <target state="translated">Chamadas para '{0}'</target> <note /> </trans-unit> <trans-unit id="Calls_To_Base_Member_0"> <source>Calls To Base Member '{0}'</source> <target state="translated">Chamadas para Membro Base '{0}'</target> <note /> </trans-unit> <trans-unit id="Calls_To_Interface_Implementation_0"> <source>Calls To Interface Implementation '{0}'</source> <target state="translated">Chamadas para Implementação de Interface '{0}'</target> <note /> </trans-unit> <trans-unit id="Computing_Call_Hierarchy_Information"> <source>Computing Call Hierarchy Information</source> <target state="translated">Informações sobre Hierarquia de Chamada de Computação</target> <note /> </trans-unit> <trans-unit id="Implements_0"> <source>Implements '{0}'</source> <target state="translated">Implementa '{0}'</target> <note /> </trans-unit> <trans-unit id="Initializers"> <source>Initializers</source> <target state="translated">Inicializadores</target> <note /> </trans-unit> <trans-unit id="References_To_Field_0"> <source>References To Field '{0}'</source> <target state="translated">Referências ao Campo '{0}'</target> <note /> </trans-unit> <trans-unit id="Calls_To_Overrides"> <source>Calls To Overrides</source> <target state="translated">Chamadas para Substituições</target> <note /> </trans-unit> <trans-unit id="Preview_changes1"> <source>_Preview changes</source> <target state="translated">Alterações de _Preview</target> <note /> </trans-unit> <trans-unit id="Apply3"> <source>Apply</source> <target state="translated">Aplicar</target> <note /> </trans-unit> <trans-unit id="Cancel"> <source>Cancel</source> <target state="translated">Cancelar</target> <note /> </trans-unit> <trans-unit id="Changes"> <source>Changes</source> <target state="translated">Alterações</target> <note /> </trans-unit> <trans-unit id="Preview_changes2"> <source>Preview changes</source> <target state="translated">Visualizar alterações</target> <note /> </trans-unit> <trans-unit id="IntelliSense"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note /> </trans-unit> <trans-unit id="IntelliSense_Commit_Formatting"> <source>IntelliSense Commit Formatting</source> <target state="translated">Formatação de Confirmação IntelliSense</target> <note /> </trans-unit> <trans-unit id="Rename_Tracking"> <source>Rename Tracking</source> <target state="translated">Renomear Acompanhamento</target> <note /> </trans-unit> <trans-unit id="Removing_0_from_1_with_content_colon"> <source>Removing '{0}' from '{1}' with content:</source> <target state="translated">Removendo '{0}' de '{1}' com conteúdo:</target> <note /> </trans-unit> <trans-unit id="_0_does_not_support_the_1_operation_However_it_may_contain_nested_2_s_see_2_3_that_support_this_operation"> <source>'{0}' does not support the '{1}' operation. However, it may contain nested '{2}'s (see '{2}.{3}') that support this operation.</source> <target state="translated">'{0}' não dá suporte à operação '{1}'. No entanto, ele pode conter '{2}'s aninhados (consulte '{2}.{3}') que dá suporte a esta operação.</target> <note /> </trans-unit> <trans-unit id="Brace_Completion"> <source>Brace Completion</source> <target state="translated">Preenchimento de Chaves</target> <note /> </trans-unit> <trans-unit id="Cannot_apply_operation_while_a_rename_session_is_active"> <source>Cannot apply operation while a rename session is active.</source> <target state="translated">Não é possível aplicar a operação enquanto uma sessão de renomeação está ativa.</target> <note /> </trans-unit> <trans-unit id="The_rename_tracking_session_was_cancelled_and_is_no_longer_available"> <source>The rename tracking session was cancelled and is no longer available.</source> <target state="translated">A sessão de acompanhamento de renomeação foi cancelada e não está mais disponível.</target> <note /> </trans-unit> <trans-unit id="Highlighted_Written_Reference"> <source>Highlighted Written Reference</source> <target state="translated">Referência Escrita Realçada</target> <note /> </trans-unit> <trans-unit id="Cursor_must_be_on_a_member_name"> <source>Cursor must be on a member name.</source> <target state="translated">O cursor deve estar em um nome do membro.</target> <note /> </trans-unit> <trans-unit id="Brace_Matching"> <source>Brace Matching</source> <target state="translated">Correspondência de Chaves</target> <note /> </trans-unit> <trans-unit id="Locating_implementations"> <source>Locating implementations...</source> <target state="translated">Localizando implementações...</target> <note /> </trans-unit> <trans-unit id="Go_To_Implementation"> <source>Go To Implementation</source> <target state="translated">Ir Para Implementação</target> <note /> </trans-unit> <trans-unit id="The_symbol_has_no_implementations"> <source>The symbol has no implementations.</source> <target state="translated">O símbolo não tem implementações.</target> <note /> </trans-unit> <trans-unit id="New_name_colon_0"> <source>New name: {0}</source> <target state="translated">Novo nome: {0}</target> <note /> </trans-unit> <trans-unit id="Modify_any_highlighted_location_to_begin_renaming"> <source>Modify any highlighted location to begin renaming.</source> <target state="translated">Modifique qualquer local realçado para iniciar a renomeação.</target> <note /> </trans-unit> <trans-unit id="Paste"> <source>Paste</source> <target state="translated">Colar</target> <note /> </trans-unit> <trans-unit id="Navigating"> <source>Navigating...</source> <target state="translated">Navegando...</target> <note /> </trans-unit> <trans-unit id="Suggestion_ellipses"> <source>Suggestion ellipses (…)</source> <target state="translated">Reticências de sugestão (…)</target> <note /> </trans-unit> <trans-unit id="_0_references"> <source>'{0}' references</source> <target state="translated">'{0}' referências</target> <note /> </trans-unit> <trans-unit id="_0_implementations"> <source>'{0}' implementations</source> <target state="translated">'Implementações de '{0}'</target> <note /> </trans-unit> <trans-unit id="_0_declarations"> <source>'{0}' declarations</source> <target state="translated">'Declarações de '{0}'</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Conflict"> <source>Inline Rename Conflict</source> <target state="translated">Conflito de Renomeação Embutida</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Field_Background_and_Border"> <source>Inline Rename Field Background and Border</source> <target state="translated">Borda e Tela de Fundo do Campo de Renomeação Embutida</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Field_Text"> <source>Inline Rename Field Text</source> <target state="translated">Texto do Campo de Renomeação Embutida</target> <note /> </trans-unit> <trans-unit id="Block_Comment_Editing"> <source>Block Comment Editing</source> <target state="translated">Bloquear Edição de Comentário</target> <note /> </trans-unit> <trans-unit id="Comment_Uncomment_Selection"> <source>Comment/Uncomment Selection</source> <target state="translated">Comentar/Remover Marca de Comentário da Seleção</target> <note /> </trans-unit> <trans-unit id="Code_Completion"> <source>Code Completion</source> <target state="translated">Conclusão de Código</target> <note /> </trans-unit> <trans-unit id="Execute_In_Interactive"> <source>Execute In Interactive</source> <target state="translated">Executar em Interativo</target> <note /> </trans-unit> <trans-unit id="Extract_Interface"> <source>Extract Interface</source> <target state="translated">Extrair a Interface</target> <note /> </trans-unit> <trans-unit id="Go_To_Adjacent_Member"> <source>Go To Adjacent Member</source> <target state="translated">Ir para Membro Adjacente</target> <note /> </trans-unit> <trans-unit id="Interactive"> <source>Interactive</source> <target state="translated">Interativo</target> <note /> </trans-unit> <trans-unit id="Paste_in_Interactive"> <source>Paste in Interactive</source> <target state="translated">Colar em Interativo</target> <note /> </trans-unit> <trans-unit id="Navigate_To_Highlight_Reference"> <source>Navigate To Highlighted Reference</source> <target state="translated">Navegar para Referência Realçada</target> <note /> </trans-unit> <trans-unit id="Outlining"> <source>Outlining</source> <target state="translated">Estrutura de Tópicos</target> <note /> </trans-unit> <trans-unit id="Rename_Tracking_Cancellation"> <source>Rename Tracking Cancellation</source> <target state="translated">Renomear Cancelamento de Acompanhamento</target> <note /> </trans-unit> <trans-unit id="Signature_Help"> <source>Signature Help</source> <target state="translated">Ajuda da Assinatura</target> <note /> </trans-unit> <trans-unit id="Smart_Token_Formatter"> <source>Smart Token Formatter</source> <target state="translated">Formatador de Token Inteligente</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="pt-BR" original="../EditorFeaturesResources.resx"> <body> <trans-unit id="All_methods"> <source>All methods</source> <target state="translated">Todos os métodos</target> <note /> </trans-unit> <trans-unit id="Always_for_clarity"> <source>Always for clarity</source> <target state="translated">Sempre para esclarecimento</target> <note /> </trans-unit> <trans-unit id="An_inline_rename_session_is_active_for_identifier_0"> <source>An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time.</source> <target state="translated">Uma sessão de renomeação embutida está ativa para o identificador '{0}'. Invoque a renomeação embutida novamente para acessar opções adicionais. Você pode continuar a editar o identificador que está sendo renomeado a qualquer momento.</target> <note>For screenreaders. {0} is the identifier being renamed.</note> </trans-unit> <trans-unit id="Applying_changes"> <source>Applying changes</source> <target state="translated">Aplicando mudanças</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_parameters"> <source>Avoid unused parameters</source> <target state="translated">Evitar parâmetros não utilizados</target> <note /> </trans-unit> <trans-unit id="Change_configuration"> <source>Change configuration</source> <target state="translated">Alterar configuração</target> <note /> </trans-unit> <trans-unit id="Code_cleanup_is_not_configured"> <source>Code cleanup is not configured</source> <target state="translated">A limpeza de código não está configurada</target> <note /> </trans-unit> <trans-unit id="Configure_it_now"> <source>Configure it now</source> <target state="translated">Configurar agora</target> <note /> </trans-unit> <trans-unit id="Do_not_prefer_this_or_Me"> <source>Do not prefer 'this.' or 'Me.'</source> <target state="translated">Não preferir 'this.' nem 'Me'.</target> <note /> </trans-unit> <trans-unit id="Do_not_show_this_message_again"> <source>Do not show this message again</source> <target state="translated">Não mostrar esta mensagem novamente</target> <note /> </trans-unit> <trans-unit id="Do_you_still_want_to_proceed_This_may_produce_broken_code"> <source>Do you still want to proceed? This may produce broken code.</source> <target state="translated">Ainda quer continuar? Isso pode produzir código desfeito.</target> <note /> </trans-unit> <trans-unit id="Expander_display_text"> <source>items from unimported namespaces</source> <target state="translated">itens de namespaces não importados</target> <note /> </trans-unit> <trans-unit id="Expander_image_element"> <source>Expander</source> <target state="translated">Expansor</target> <note /> </trans-unit> <trans-unit id="Extract_method_encountered_the_following_issues"> <source>Extract method encountered the following issues:</source> <target state="translated">O método de extração encontrou os seguintes problemas:</target> <note /> </trans-unit> <trans-unit id="Filter_image_element"> <source>Filter</source> <target state="translated">Filtrar</target> <note>Caption/tooltip for "Filter" image element displayed in completion popup.</note> </trans-unit> <trans-unit id="For_locals_parameters_and_members"> <source>For locals, parameters and members</source> <target state="translated">Para locais, parâmetros e membros</target> <note /> </trans-unit> <trans-unit id="For_member_access_expressions"> <source>For member access expressions</source> <target state="translated">Para expressões de acesso de membro</target> <note /> </trans-unit> <trans-unit id="Format_document_performed_additional_cleanup"> <source>Format Document performed additional cleanup</source> <target state="translated">A Formatação do Documento executou uma limpeza adicional</target> <note /> </trans-unit> <trans-unit id="Get_help_for_0"> <source>Get help for '{0}'</source> <target state="translated">Obter ajuda para '{0}'</target> <note /> </trans-unit> <trans-unit id="Get_help_for_0_from_Bing"> <source>Get help for '{0}' from Bing</source> <target state="translated">Obter ajuda para o '{0}' do Bing</target> <note /> </trans-unit> <trans-unit id="Gathering_Suggestions_0"> <source>Gathering Suggestions - '{0}'</source> <target state="translated">Obtendo Sugestões – '{0}'</target> <note /> </trans-unit> <trans-unit id="Gathering_Suggestions_Waiting_for_the_solution_to_fully_load"> <source>Gathering Suggestions - Waiting for the solution to fully load</source> <target state="translated">Obtendo Sugestões – aguardando a solução carregar totalmente</target> <note /> </trans-unit> <trans-unit id="Go_To_Base"> <source>Go To Base</source> <target state="translated">Ir Para a Base</target> <note /> </trans-unit> <trans-unit id="In_arithmetic_binary_operators"> <source>In arithmetic operators</source> <target state="translated">Em operadores aritméticos</target> <note /> </trans-unit> <trans-unit id="In_other_binary_operators"> <source>In other binary operators</source> <target state="translated">Em outros operadores binários</target> <note /> </trans-unit> <trans-unit id="In_other_operators"> <source>In other operators</source> <target state="translated">Em outros operadores</target> <note /> </trans-unit> <trans-unit id="In_relational_binary_operators"> <source>In relational operators</source> <target state="translated">Em operadores relacionais</target> <note /> </trans-unit> <trans-unit id="Indentation_Size"> <source>Indentation Size</source> <target state="translated">Tamanho do Recuo</target> <note /> </trans-unit> <trans-unit id="Inline_Hints"> <source>Inline Hints</source> <target state="translated">Dicas Embutidas</target> <note /> </trans-unit> <trans-unit id="Insert_Final_Newline"> <source>Insert Final Newline</source> <target state="translated">Inserir Nova Linha Final</target> <note /> </trans-unit> <trans-unit id="Invalid_assembly_name"> <source>Invalid assembly name</source> <target state="translated">Nome do assembly inválido</target> <note /> </trans-unit> <trans-unit id="Invalid_characters_in_assembly_name"> <source>Invalid characters in assembly name</source> <target state="translated">Caracteres inválidos no nome do assembly</target> <note /> </trans-unit> <trans-unit id="Keyword_Control"> <source>Keyword - Control</source> <target state="translated">Palavra-chave – Controle</target> <note /> </trans-unit> <trans-unit id="Locating_bases"> <source>Locating bases...</source> <target state="translated">Localizando as bases...</target> <note /> </trans-unit> <trans-unit id="Never_if_unnecessary"> <source>Never if unnecessary</source> <target state="translated">Nunca se desnecessário</target> <note /> </trans-unit> <trans-unit id="New_Line"> <source>New Line</source> <target state="translated">Nova Linha</target> <note /> </trans-unit> <trans-unit id="No"> <source>No</source> <target state="translated">Não</target> <note /> </trans-unit> <trans-unit id="Non_public_methods"> <source>Non-public methods</source> <target state="translated">Métodos não públicos</target> <note /> </trans-unit> <trans-unit id="Operator_Overloaded"> <source>Operator - Overloaded</source> <target state="translated">Operador – Sobrecarregado</target> <note /> </trans-unit> <trans-unit id="Paste_Tracking"> <source>Paste Tracking</source> <target state="translated">Colar Acompanhamento</target> <note /> </trans-unit> <trans-unit id="Prefer_System_HashCode_in_GetHashCode"> <source>Prefer 'System.HashCode' in 'GetHashCode'</source> <target state="translated">Prefira 'System.HashCode' em 'GetHashCode'</target> <note /> </trans-unit> <trans-unit id="Prefer_coalesce_expression"> <source>Prefer coalesce expression</source> <target state="translated">Preferir a expressão de união</target> <note /> </trans-unit> <trans-unit id="Prefer_collection_initializer"> <source>Prefer collection initializer</source> <target state="translated">Preferir o inicializador de coleção</target> <note /> </trans-unit> <trans-unit id="Prefer_compound_assignments"> <source>Prefer compound assignments</source> <target state="translated">Preferir atribuições de compostos</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_assignments"> <source>Prefer conditional expression over 'if' with assignments</source> <target state="translated">Preferir expressão condicional em vez de 'if' com atribuições</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_returns"> <source>Prefer conditional expression over 'if' with returns</source> <target state="translated">Preferir expressão condicional em vez de 'if' com retornos</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_tuple_name"> <source>Prefer explicit tuple name</source> <target state="translated">Preferir nome de tupla explícito</target> <note /> </trans-unit> <trans-unit id="Prefer_framework_type"> <source>Prefer framework type</source> <target state="translated">Preferir tipo de estrutura</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_anonymous_type_member_names"> <source>Prefer inferred anonymous type member names</source> <target state="translated">Prefira usar nomes de membro inferidos do tipo anônimo</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_tuple_names"> <source>Prefer inferred tuple element names</source> <target state="translated">Preferir usar nomes de elementos inferidos de tupla</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 /> </trans-unit> <trans-unit id="Prefer_null_propagation"> <source>Prefer null propagation</source> <target state="translated">Preferir tratamento simplificado de nulo</target> <note /> </trans-unit> <trans-unit id="Prefer_object_initializer"> <source>Prefer object initializer</source> <target state="translated">Preferir inicializador de objeto</target> <note /> </trans-unit> <trans-unit id="Prefer_predefined_type"> <source>Prefer predefined type</source> <target state="translated">Preferir tipo predefinido</target> <note /> </trans-unit> <trans-unit id="Prefer_readonly_fields"> <source>Prefer readonly fields</source> <target state="translated">Preferir campos readonly</target> <note /> </trans-unit> <trans-unit id="Prefer_simplified_boolean_expressions"> <source>Prefer simplified boolean expressions</source> <target state="translated">Preferir expressões boolianas simplificadas</target> <note /> </trans-unit> <trans-unit id="Prefer_this_or_Me"> <source>Prefer 'this.' or 'Me.'</source> <target state="translated">Preferir 'this.' ou 'Me.'</target> <note /> </trans-unit> <trans-unit id="Preprocessor_Text"> <source>Preprocessor Text</source> <target state="translated">Texto de Pré-Processador</target> <note /> </trans-unit> <trans-unit id="Punctuation"> <source>Punctuation</source> <target state="translated">Pontuação</target> <note /> </trans-unit> <trans-unit id="Qualify_event_access_with_this_or_Me"> <source>Qualify event access with 'this' or 'Me'</source> <target state="translated">Qualificar o acesso de evento com 'this' ou 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_field_access_with_this_or_Me"> <source>Qualify field access with 'this' or 'Me'</source> <target state="translated">Qualificar o acesso de campo com 'this' ou 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_method_access_with_this_or_Me"> <source>Qualify method access with 'this' or 'Me'</source> <target state="translated">Qualificar o acesso de método com 'this' ou 'Me'</target> <note /> </trans-unit> <trans-unit id="Qualify_property_access_with_this_or_Me"> <source>Qualify property access with 'this' or 'Me'</source> <target state="translated">Qualificar o acesso de propriedade com 'this' ou 'Me'</target> <note /> </trans-unit> <trans-unit id="Reassigned_variable"> <source>Reassigned variable</source> <target state="new">Reassigned variable</target> <note /> </trans-unit> <trans-unit id="Rename_file_name_doesnt_match"> <source>Rename _file (type does not match file name)</source> <target state="translated">Renomear _arquivo (o tipo não corresponde ao nome do arquivo)</target> <note /> </trans-unit> <trans-unit id="Rename_file_partial_type"> <source>Rename _file (not allowed on partial types)</source> <target state="translated">Renomear _arquivo (não permitido em tipos parciais)</target> <note>Disabled text status for file rename</note> </trans-unit> <trans-unit id="Rename_symbols_file"> <source>Rename symbol's _file</source> <target state="translated">Renomear o _arquivo do símbolo</target> <note>Indicates that the file a symbol is defined in will also be renamed</note> </trans-unit> <trans-unit id="Split_comment"> <source>Split comment</source> <target state="translated">Dividir o comentário</target> <note /> </trans-unit> <trans-unit id="String_Escape_Character"> <source>String - Escape Character</source> <target state="translated">String - caractere de Escape</target> <note /> </trans-unit> <trans-unit id="Symbol_Static"> <source>Symbol - Static</source> <target state="translated">Símbolo – Estático</target> <note /> </trans-unit> <trans-unit id="Tab_Size"> <source>Tab Size</source> <target state="translated">Tamanho da Tabulação</target> <note /> </trans-unit> <trans-unit id="The_symbol_has_no_base"> <source>The symbol has no base.</source> <target state="translated">O símbolo não tem nenhuma base.</target> <note /> </trans-unit> <trans-unit id="Toggle_Block_Comment"> <source>Toggle Block Comment</source> <target state="translated">Ativar/Desativar Comentário de Bloco</target> <note /> </trans-unit> <trans-unit id="Toggle_Line_Comment"> <source>Toggle Line Comment</source> <target state="translated">Ativar/Desativar Comentário de Linha</target> <note /> </trans-unit> <trans-unit id="Toggling_block_comment"> <source>Toggling block comment...</source> <target state="translated">Ativando/desativando o comentário de bloco...</target> <note /> </trans-unit> <trans-unit id="Toggling_line_comment"> <source>Toggling line comment...</source> <target state="translated">Ativando/desativando o comentário de linha...</target> <note /> </trans-unit> <trans-unit id="Use_Tabs"> <source>Use Tabs</source> <target state="translated">Usar Tabulações</target> <note /> </trans-unit> <trans-unit id="User_Members_Constants"> <source>User Members - Constants</source> <target state="translated">Membros de Usuário – Constantes</target> <note /> </trans-unit> <trans-unit id="User_Members_Enum_Members"> <source>User Members - Enum Members</source> <target state="translated">Membros de Usuário – Membros Enum</target> <note /> </trans-unit> <trans-unit id="User_Members_Events"> <source>User Members - Events</source> <target state="translated">Membros de Usuário – Eventos</target> <note /> </trans-unit> <trans-unit id="User_Members_Extension_Methods"> <source>User Members - Extension Methods</source> <target state="translated">Membros de Usuário – Métodos de Extensão</target> <note /> </trans-unit> <trans-unit id="User_Members_Fields"> <source>User Members - Fields</source> <target state="translated">Membros de Usuário – Campos</target> <note /> </trans-unit> <trans-unit id="User_Members_Labels"> <source>User Members - Labels</source> <target state="translated">Membros de Usuário – Rótulos</target> <note /> </trans-unit> <trans-unit id="User_Members_Locals"> <source>User Members - Locals</source> <target state="translated">Membros de Usuário – Locais</target> <note /> </trans-unit> <trans-unit id="User_Members_Methods"> <source>User Members - Methods</source> <target state="translated">Membros de Usuário – Métodos</target> <note /> </trans-unit> <trans-unit id="User_Members_Namespaces"> <source>User Members - Namespaces</source> <target state="translated">Membros de Usuário – Namespaces</target> <note /> </trans-unit> <trans-unit id="User_Members_Parameters"> <source>User Members - Parameters</source> <target state="translated">Membros de Usuário – Parâmetros</target> <note /> </trans-unit> <trans-unit id="User_Members_Properties"> <source>User Members - Properties</source> <target state="translated">Membros de Usuário – Propriedades</target> <note /> </trans-unit> <trans-unit id="User_Types_Classes"> <source>User Types - Classes</source> <target state="translated">Tipos de Usuário - Classes</target> <note /> </trans-unit> <trans-unit id="User_Types_Delegates"> <source>User Types - Delegates</source> <target state="translated">Tipos de Usuário - Representantes</target> <note /> </trans-unit> <trans-unit id="User_Types_Enums"> <source>User Types - Enums</source> <target state="translated">Tipos de Usuário - Enums</target> <note /> </trans-unit> <trans-unit id="User_Types_Interfaces"> <source>User Types - Interfaces</source> <target state="translated">Tipos de Usuário - Interfaces</target> <note /> </trans-unit> <trans-unit id="User_Types_Record_Structs"> <source>User Types - Record Structs</source> <target state="translated">Tipos de usuário - Registro de structs</target> <note /> </trans-unit> <trans-unit id="User_Types_Records"> <source>User Types - Records</source> <target state="translated">Tipos de Usuário – Registros</target> <note /> </trans-unit> <trans-unit id="User_Types_Structures"> <source>User Types - Structures</source> <target state="translated">Tipos de Usuário - Estruturas</target> <note /> </trans-unit> <trans-unit id="User_Types_Type_Parameters"> <source>User Types - Type Parameters</source> <target state="translated">Tipos de Usuário - Parâmetros de Tipo</target> <note /> </trans-unit> <trans-unit id="String_Verbatim"> <source>String - Verbatim</source> <target state="translated">Cadeia de caracteres - Textual</target> <note /> </trans-unit> <trans-unit id="Waiting_for_background_work_to_finish"> <source>Waiting for background work to finish...</source> <target state="translated">Aguardando a conclusão do trabalho em segundo plano...</target> <note /> </trans-unit> <trans-unit id="Warning_image_element"> <source>Warning</source> <target state="translated">Aviso</target> <note>Caption/tooltip for "Warning" image element displayed in completion popup.</note> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Name"> <source>XML Doc Comments - Attribute Name</source> <target state="translated">Comentário da documentação XML - Nome de Atributo</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_CData_Section"> <source>XML Doc Comments - CData Section</source> <target state="translated">Comentário da documentação XML - Seção CData</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Text"> <source>XML Doc Comments - Text</source> <target state="translated">Comentário da documentação XML - Texto</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Delimiter"> <source>XML Doc Comments - Delimiter</source> <target state="translated">Comentário da documentação XML - Delimitador</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Comment"> <source>XML Doc Comments - Comment</source> <target state="translated">Comentário da documentação XML - Comentário</target> <note /> </trans-unit> <trans-unit id="User_Types_Modules"> <source>User Types - Modules</source> <target state="translated">Tipos de Usuário - Módulos</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Name"> <source>VB XML Literals - Attribute Name</source> <target state="translated">Literais XML do VB - Nome de Atributo</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Quotes"> <source>VB XML Literals - Attribute Quotes</source> <target state="translated">Literais XML do VB - Aspas de Atributo</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Value"> <source>VB XML Literals - Attribute Value</source> <target state="translated">Literais XML do VB - Valor de Atributo</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_CData_Section"> <source>VB XML Literals - CData Section</source> <target state="translated">Literais XML do VB - Seção CData</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Comment"> <source>VB XML Literals - Comment</source> <target state="translated">Literais XML do VB - Comentário</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Delimiter"> <source>VB XML Literals - Delimiter</source> <target state="translated">Literais XML do VB - Delimitador</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Embedded_Expression"> <source>VB XML Literals - Embedded Expression</source> <target state="translated">Literais XML do VB - Expressão Inserida</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Entity_Reference"> <source>VB XML Literals - Entity Reference</source> <target state="translated">Literais XML do VB - Referência de Entidade</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Name"> <source>VB XML Literals - Name</source> <target state="translated">Literais XML do VB - Nome</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Processing_Instruction"> <source>VB XML Literals - Processing Instruction</source> <target state="translated">Literais XML do VB - Instrução de Processamento</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Text"> <source>VB XML Literals - Text</source> <target state="translated">Literais XML do VB - Texto</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Quotes"> <source>XML Doc Comments - Attribute Quotes</source> <target state="translated">Comentário da documentação XML - Aspas de Atributo</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Value"> <source>XML Doc Comments - Attribute Value</source> <target state="translated">Comentário da documentação XML - Valor de Atributo</target> <note /> </trans-unit> <trans-unit id="Unnecessary_Code"> <source>Unnecessary Code</source> <target state="translated">Código Desnecessário</target> <note /> </trans-unit> <trans-unit id="Rude_Edit"> <source>Rude Edit</source> <target state="translated">Edição Rudimentar</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_1_reference_in_1_file"> <source>Rename will update 1 reference in 1 file.</source> <target state="translated">Renomear atualizará 1 referência em 1 arquivo.</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_0_references_in_1_file"> <source>Rename will update {0} references in 1 file.</source> <target state="translated">Renomear atualizará {0} referências em 1 arquivo.</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_0_references_in_1_files"> <source>Rename will update {0} references in {1} files.</source> <target state="translated">Renomear atualizará {0} referências em {1} arquivos.</target> <note /> </trans-unit> <trans-unit id="Yes"> <source>Yes</source> <target state="translated">Sim</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element_because_it_is_contained_in_a_read_only_file"> <source>You cannot rename this element because it is contained in a read-only file.</source> <target state="translated">Você não pode renomear este elemento porque ele está contido em um arquivo somente leitura.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element_because_it_is_in_a_location_that_cannot_be_navigated_to"> <source>You cannot rename this element because it is in a location that cannot be navigated to.</source> <target state="translated">Você não pode renomear este elemento porque ele está em um local para o qual não é possível navegar.</target> <note /> </trans-unit> <trans-unit id="_0_bases"> <source>'{0}' bases</source> <target state="translated">Bases '{0}'</target> <note /> </trans-unit> <trans-unit id="_0_conflict_s_will_be_resolved"> <source>{0} conflict(s) will be resolved</source> <target state="translated">{0} conflito(s) será(ão) resolvido(s)</target> <note /> </trans-unit> <trans-unit id="_0_implemented_members"> <source>'{0}' implemented members</source> <target state="translated">'{0}' membros implementados</target> <note /> </trans-unit> <trans-unit id="_0_unresolvable_conflict_s"> <source>{0} unresolvable conflict(s)</source> <target state="translated">{0} conflito(s) não solucionável(is)</target> <note /> </trans-unit> <trans-unit id="Applying_0"> <source>Applying "{0}"...</source> <target state="translated">Aplicando "{0}"...</target> <note /> </trans-unit> <trans-unit id="Adding_0_to_1_with_content_colon"> <source>Adding '{0}' to '{1}' with content:</source> <target state="translated">Adicionando "{0}" a "{1}" com conteúdo:</target> <note /> </trans-unit> <trans-unit id="Adding_project_0"> <source>Adding project '{0}'</source> <target state="translated">Adicionando projeto "{0}"</target> <note /> </trans-unit> <trans-unit id="Removing_project_0"> <source>Removing project '{0}'</source> <target state="translated">Removendo projeto "{0}"</target> <note /> </trans-unit> <trans-unit id="Changing_project_references_for_0"> <source>Changing project references for '{0}'</source> <target state="translated">Alterar referências de projeto para "{0}"</target> <note /> </trans-unit> <trans-unit id="Adding_reference_0_to_1"> <source>Adding reference '{0}' to '{1}'</source> <target state="translated">Adicionando referência "{0}" a "{1}"</target> <note /> </trans-unit> <trans-unit id="Removing_reference_0_from_1"> <source>Removing reference '{0}' from '{1}'</source> <target state="translated">Removendo referência "{0}" de "{1}"</target> <note /> </trans-unit> <trans-unit id="Adding_analyzer_reference_0_to_1"> <source>Adding analyzer reference '{0}' to '{1}'</source> <target state="translated">Adicionando referência de analisador "{0}" a "{1}"</target> <note /> </trans-unit> <trans-unit id="Removing_analyzer_reference_0_from_1"> <source>Removing analyzer reference '{0}' from '{1}'</source> <target state="translated">Removendo referência do analisador "{0}" de "{1}"</target> <note /> </trans-unit> <trans-unit id="XML_End_Tag_Completion"> <source>XML End Tag Completion</source> <target state="translated">Conclusão da Marca de Fim do XML</target> <note /> </trans-unit> <trans-unit id="Completing_Tag"> <source>Completing Tag</source> <target state="translated">Completando a Tag</target> <note /> </trans-unit> <trans-unit id="Encapsulate_Field"> <source>Encapsulate Field</source> <target state="translated">Encapsular Campo</target> <note /> </trans-unit> <trans-unit id="Applying_Encapsulate_Field_refactoring"> <source>Applying "Encapsulate Field" refactoring...</source> <target state="translated">Aplicando refatoração "Encapsular Campo"...</target> <note /> </trans-unit> <trans-unit id="Please_select_the_definition_of_the_field_to_encapsulate"> <source>Please select the definition of the field to encapsulate.</source> <target state="translated">Selecione a definição do campo a encapsular.</target> <note /> </trans-unit> <trans-unit id="Given_Workspace_doesn_t_support_Undo"> <source>Given Workspace doesn't support Undo</source> <target state="translated">Workspace fornecido não suporta Desfazer</target> <note /> </trans-unit> <trans-unit id="Searching"> <source>Searching...</source> <target state="translated">Pesquisando...</target> <note /> </trans-unit> <trans-unit id="Canceled"> <source>Canceled.</source> <target state="translated">Cancelado.</target> <note /> </trans-unit> <trans-unit id="No_information_found"> <source>No information found.</source> <target state="translated">Nenhuma informação encontrada.</target> <note /> </trans-unit> <trans-unit id="No_usages_found"> <source>No usages found.</source> <target state="translated">Nenhum uso encontrado.</target> <note /> </trans-unit> <trans-unit id="Implements_"> <source>Implements</source> <target state="translated">Implementos</target> <note /> </trans-unit> <trans-unit id="Implemented_By"> <source>Implemented By</source> <target state="translated">Implementado por</target> <note /> </trans-unit> <trans-unit id="Overrides_"> <source>Overrides</source> <target state="translated">Substitui</target> <note /> </trans-unit> <trans-unit id="Overridden_By"> <source>Overridden By</source> <target state="translated">Substituído por</target> <note /> </trans-unit> <trans-unit id="Directly_Called_In"> <source>Directly Called In</source> <target state="translated">Chamado Diretamente</target> <note /> </trans-unit> <trans-unit id="Indirectly_Called_In"> <source>Indirectly Called In</source> <target state="translated">Chamado Indiretamente </target> <note /> </trans-unit> <trans-unit id="Called_In"> <source>Called In</source> <target state="translated">Chamado Em</target> <note /> </trans-unit> <trans-unit id="Referenced_In"> <source>Referenced In</source> <target state="translated">Referenciado Em</target> <note /> </trans-unit> <trans-unit id="No_references_found"> <source>No references found.</source> <target state="translated">Nenhuma referência encontrada.</target> <note /> </trans-unit> <trans-unit id="No_derived_types_found"> <source>No derived types found.</source> <target state="translated">Nenhum tipo derivado encontrado.</target> <note /> </trans-unit> <trans-unit id="No_implementations_found"> <source>No implementations found.</source> <target state="translated">Nenhuma implementação encontrada.</target> <note /> </trans-unit> <trans-unit id="_0_Line_1"> <source>{0} - (Line {1})</source> <target state="translated">{0} - (Linha {1})</target> <note /> </trans-unit> <trans-unit id="Class_Parts"> <source>Class Parts</source> <target state="translated">Partes de Classe</target> <note /> </trans-unit> <trans-unit id="Struct_Parts"> <source>Struct Parts</source> <target state="translated">Partes de Struct</target> <note /> </trans-unit> <trans-unit id="Interface_Parts"> <source>Interface Parts</source> <target state="translated">Componentes da Interface</target> <note /> </trans-unit> <trans-unit id="Type_Parts"> <source>Type Parts</source> <target state="translated">Partes do Tipo</target> <note /> </trans-unit> <trans-unit id="Inherits_"> <source>Inherits</source> <target state="translated">Herda</target> <note /> </trans-unit> <trans-unit id="Inherited_By"> <source>Inherited By</source> <target state="translated">Herdado por</target> <note /> </trans-unit> <trans-unit id="Already_tracking_document_with_identical_key"> <source>Already tracking document with identical key</source> <target state="translated">Já está a rastrear o documento com chave idêntica</target> <note /> </trans-unit> <trans-unit id="analyzer_Prefer_auto_properties"> <source>Prefer auto properties</source> <target state="translated">Preferir propriedades automáticas</target> <note /> </trans-unit> <trans-unit id="document_is_not_currently_being_tracked"> <source>document is not currently being tracked</source> <target state="translated">documento não está sendo rastreado no momento</target> <note /> </trans-unit> <trans-unit id="Computing_Rename_information"> <source>Computing Rename information...</source> <target state="translated">Computando informações de Renomeação...</target> <note /> </trans-unit> <trans-unit id="Updating_files"> <source>Updating files...</source> <target state="translated">Atualizando arquivos...</target> <note /> </trans-unit> <trans-unit id="Rename_operation_was_cancelled_or_is_not_valid"> <source>Rename operation was cancelled or is not valid</source> <target state="translated">A operação de renomear foi cancelada ou não é válida</target> <note /> </trans-unit> <trans-unit id="Rename_Symbol"> <source>Rename Symbol</source> <target state="translated">Renomear Símbolo</target> <note /> </trans-unit> <trans-unit id="Text_Buffer_Change"> <source>Text Buffer Change</source> <target state="translated">Alteração no Buffer de Texto</target> <note /> </trans-unit> <trans-unit id="Rename_operation_was_not_properly_completed_Some_file_might_not_have_been_updated"> <source>Rename operation was not properly completed. Some file might not have been updated.</source> <target state="translated">A operação de renomear não foi corretamente concluída. Algum arquivo pode não ter sido atualizado.</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1"> <source>Rename '{0}' to '{1}'</source> <target state="translated">Renomear "{0}" para "{1}"</target> <note /> </trans-unit> <trans-unit id="Preview_Warning"> <source>Preview Warning</source> <target state="translated">Aviso de Visualização</target> <note /> </trans-unit> <trans-unit id="external"> <source>(external)</source> <target state="translated">(externo)</target> <note /> </trans-unit> <trans-unit id="Automatic_Line_Ender"> <source>Automatic Line Ender</source> <target state="translated">Finalizador de Linha Automático</target> <note /> </trans-unit> <trans-unit id="Automatically_completing"> <source>Automatically completing...</source> <target state="translated">Concluindo automaticamente...</target> <note /> </trans-unit> <trans-unit id="Automatic_Pair_Completion"> <source>Automatic Pair Completion</source> <target state="translated">Conclusão de Pares Automática</target> <note /> </trans-unit> <trans-unit id="An_active_inline_rename_session_is_still_active_Complete_it_before_starting_a_new_one"> <source>An active inline rename session is still active. Complete it before starting a new one.</source> <target state="translated">Uma sessão de renomeação embutida ativa ainda está ativa. Conclua-a antes de iniciar uma nova.</target> <note /> </trans-unit> <trans-unit id="The_buffer_is_not_part_of_a_workspace"> <source>The buffer is not part of a workspace.</source> <target state="translated">O buffer não é parte de um workspace.</target> <note /> </trans-unit> <trans-unit id="The_token_is_not_contained_in_the_workspace"> <source>The token is not contained in the workspace.</source> <target state="translated">O token não está contido no workspace.</target> <note /> </trans-unit> <trans-unit id="You_must_rename_an_identifier"> <source>You must rename an identifier.</source> <target state="translated">Você deve renomear um identificador.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element"> <source>You cannot rename this element.</source> <target state="translated">Você não pode renomear este elemento.</target> <note /> </trans-unit> <trans-unit id="Please_resolve_errors_in_your_code_before_renaming_this_element"> <source>Please resolve errors in your code before renaming this element.</source> <target state="translated">Resolva erros em seu código antes de renomear este elemento.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_operators"> <source>You cannot rename operators.</source> <target state="translated">Você não pode renomear operadores.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_elements_that_are_defined_in_metadata"> <source>You cannot rename elements that are defined in metadata.</source> <target state="translated">Você não pode renomear elementos que estão definidos nos metadados.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_elements_from_previous_submissions"> <source>You cannot rename elements from previous submissions.</source> <target state="translated">Você não pode renomear elementos de envios anteriores.</target> <note /> </trans-unit> <trans-unit id="Navigation_Bars"> <source>Navigation Bars</source> <target state="translated">Barras de Navegação</target> <note /> </trans-unit> <trans-unit id="Refreshing_navigation_bars"> <source>Refreshing navigation bars...</source> <target state="translated">Atualizando barras de navegação...</target> <note /> </trans-unit> <trans-unit id="Format_Token"> <source>Format Token</source> <target state="translated">Token de Formato</target> <note /> </trans-unit> <trans-unit id="Smart_Indenting"> <source>Smart Indenting</source> <target state="translated">Recuo Inteligente</target> <note /> </trans-unit> <trans-unit id="Find_References"> <source>Find References</source> <target state="translated">Localizar Referências</target> <note /> </trans-unit> <trans-unit id="Finding_references"> <source>Finding references...</source> <target state="translated">Localizando referências...</target> <note /> </trans-unit> <trans-unit id="Finding_references_of_0"> <source>Finding references of "{0}"...</source> <target state="translated">Localizando referências de "{0}"...</target> <note /> </trans-unit> <trans-unit id="Comment_Selection"> <source>Comment Selection</source> <target state="translated">Comentar Seleção</target> <note /> </trans-unit> <trans-unit id="Uncomment_Selection"> <source>Uncomment Selection</source> <target state="translated">Remover Comentários da Seleção</target> <note /> </trans-unit> <trans-unit id="Commenting_currently_selected_text"> <source>Commenting currently selected text...</source> <target state="translated">Comentando o texto selecionado no momento...</target> <note /> </trans-unit> <trans-unit id="Uncommenting_currently_selected_text"> <source>Uncommenting currently selected text...</source> <target state="translated">Removendo marca de comentário do texto selecionado no momento...</target> <note /> </trans-unit> <trans-unit id="Insert_new_line"> <source>Insert new line</source> <target state="translated">Inserir Nova Linha</target> <note /> </trans-unit> <trans-unit id="Documentation_Comment"> <source>Documentation Comment</source> <target state="translated">Comentário de Documentação</target> <note /> </trans-unit> <trans-unit id="Inserting_documentation_comment"> <source>Inserting documentation comment...</source> <target state="translated">Inserindo comentário da documentação...</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="Applying_Extract_Method_refactoring"> <source>Applying "Extract Method" refactoring...</source> <target state="translated">Aplicando refatoração "Extrair Método"...</target> <note /> </trans-unit> <trans-unit id="Format_Document"> <source>Format Document</source> <target state="translated">Formatar Documento</target> <note /> </trans-unit> <trans-unit id="Formatting_document"> <source>Formatting document...</source> <target state="translated">Formatando documento...</target> <note /> </trans-unit> <trans-unit id="Formatting"> <source>Formatting</source> <target state="translated">Formatação</target> <note /> </trans-unit> <trans-unit id="Format_Selection"> <source>Format Selection</source> <target state="translated">Formatar Seleção</target> <note /> </trans-unit> <trans-unit id="Formatting_currently_selected_text"> <source>Formatting currently selected text...</source> <target state="translated">Formatando texto selecionado no momento...</target> <note /> </trans-unit> <trans-unit id="Cannot_navigate_to_the_symbol_under_the_caret"> <source>Cannot navigate to the symbol under the caret.</source> <target state="translated">Não é possível navegar para o símbolo sob o cursor.</target> <note /> </trans-unit> <trans-unit id="Go_to_Definition"> <source>Go to Definition</source> <target state="translated">Ir para Definição</target> <note /> </trans-unit> <trans-unit id="Navigating_to_definition"> <source>Navigating to definition...</source> <target state="translated">Navegando para definição...</target> <note /> </trans-unit> <trans-unit id="Organize_Document"> <source>Organize Document</source> <target state="translated">Organizar Documento</target> <note /> </trans-unit> <trans-unit id="Organizing_document"> <source>Organizing document...</source> <target state="translated">Organizando documento...</target> <note /> </trans-unit> <trans-unit id="Highlighted_Definition"> <source>Highlighted Definition</source> <target state="translated">Definição Realçada</target> <note /> </trans-unit> <trans-unit id="The_new_name_is_not_a_valid_identifier"> <source>The new name is not a valid identifier.</source> <target state="translated">O novo nome não é um identificador válido.</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Fixup"> <source>Inline Rename Fixup</source> <target state="translated">Correção de Renomeação Embutida</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Resolved_Conflict"> <source>Inline Rename Resolved Conflict</source> <target state="translated">Conflito de Renomeação Embutida Resolvido </target> <note /> </trans-unit> <trans-unit id="Inline_Rename"> <source>Inline Rename</source> <target state="translated">Renomeação embutida</target> <note /> </trans-unit> <trans-unit id="Rename"> <source>Rename</source> <target state="translated">renomear</target> <note /> </trans-unit> <trans-unit id="Start_Rename"> <source>Start Rename</source> <target state="translated">Iniciar Renomeação</target> <note /> </trans-unit> <trans-unit id="Display_conflict_resolutions"> <source>Display conflict resolutions</source> <target state="translated">Exibir resoluções de conflitos</target> <note /> </trans-unit> <trans-unit id="Finding_token_to_rename"> <source>Finding token to rename...</source> <target state="translated">Localizando token para renomear...</target> <note /> </trans-unit> <trans-unit id="Conflict"> <source>Conflict</source> <target state="translated">Conflito</target> <note /> </trans-unit> <trans-unit id="Text_Navigation"> <source>Text Navigation</source> <target state="translated">Navegação de Texto</target> <note /> </trans-unit> <trans-unit id="Finding_word_extent"> <source>Finding word extent...</source> <target state="translated">Localizando de extensão de palavra...</target> <note /> </trans-unit> <trans-unit id="Finding_enclosing_span"> <source>Finding enclosing span...</source> <target state="translated">Localizando alcance de delimitação...</target> <note /> </trans-unit> <trans-unit id="Finding_span_of_next_sibling"> <source>Finding span of next sibling...</source> <target state="translated">Localizando a extensão do próximo irmão...</target> <note /> </trans-unit> <trans-unit id="Finding_span_of_previous_sibling"> <source>Finding span of previous sibling...</source> <target state="translated">Localizando a extensão do irmão anterior...</target> <note /> </trans-unit> <trans-unit id="Rename_colon_0"> <source>Rename: {0}</source> <target state="translated">Renomear: {0}</target> <note /> </trans-unit> <trans-unit id="Light_bulb_session_is_already_dismissed"> <source>Light bulb session is already dismissed.</source> <target state="translated">A sessão de lâmpada já foi descartada.</target> <note /> </trans-unit> <trans-unit id="Automatic_Pair_Completion_End_Point_Marker_Color"> <source>Automatic Pair Completion End Point Marker Color</source> <target state="translated">Cor do Marcador de Ponto Final da Conclusão de Pares Automática</target> <note /> </trans-unit> <trans-unit id="Renaming_anonymous_type_members_is_not_yet_supported"> <source>Renaming anonymous type members is not yet supported.</source> <target state="translated">Renomear membros de tipo anônimo ainda não é suportado.</target> <note /> </trans-unit> <trans-unit id="Engine_must_be_attached_to_an_Interactive_Window"> <source>Engine must be attached to an Interactive Window.</source> <target state="translated">O Mecanismo deve ser anexado a uma Janela Interativa.</target> <note /> </trans-unit> <trans-unit id="Changes_the_current_prompt_settings"> <source>Changes the current prompt settings.</source> <target state="translated">Altera as configurações de prompt atuais.</target> <note /> </trans-unit> <trans-unit id="Unexpected_text_colon_0"> <source>Unexpected text: '{0}'</source> <target state="translated">Texto inesperado: "{0}"</target> <note /> </trans-unit> <trans-unit id="The_triggerSpan_is_not_included_in_the_given_workspace"> <source>The triggerSpan is not included in the given workspace.</source> <target state="translated">O triggerSpan não está incluído no workspace fornecido.</target> <note /> </trans-unit> <trans-unit id="This_session_has_already_been_dismissed"> <source>This session has already been dismissed.</source> <target state="translated">Esta sessão já foi descartada.</target> <note /> </trans-unit> <trans-unit id="The_transaction_is_already_complete"> <source>The transaction is already complete.</source> <target state="translated">A transação já está concluída.</target> <note /> </trans-unit> <trans-unit id="Not_a_source_error_line_column_unavailable"> <source>Not a source error, line/column unavailable</source> <target state="translated">Não é um erro de origem, linha/coluna disponível</target> <note /> </trans-unit> <trans-unit id="Can_t_compare_positions_from_different_text_snapshots"> <source>Can't compare positions from different text snapshots</source> <target state="translated">Não é possível comparar as posições de instantâneos de textos diferentes</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Entity_Reference"> <source>XML Doc Comments - Entity Reference</source> <target state="translated">Comentário da documentação XML - Referência de Entidade</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Name"> <source>XML Doc Comments - Name</source> <target state="translated">Comentário da documentação XML - Nome</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Processing_Instruction"> <source>XML Doc Comments - Processing Instruction</source> <target state="translated">Comentário da documentação XML - Instrução de Processamento</target> <note /> </trans-unit> <trans-unit id="Active_Statement"> <source>Active Statement</source> <target state="translated">Instrução Ativa</target> <note /> </trans-unit> <trans-unit id="Loading_Peek_information"> <source>Loading Peek information...</source> <target state="translated">Carregando informações de Espiada...</target> <note /> </trans-unit> <trans-unit id="Peek"> <source>Peek</source> <target state="translated">Espiada</target> <note /> </trans-unit> <trans-unit id="Apply1"> <source>_Apply</source> <target state="translated">_Aplicar</target> <note /> </trans-unit> <trans-unit id="Include_overload_s"> <source>Include _overload(s)</source> <target state="translated">Incluir _overload(s)</target> <note /> </trans-unit> <trans-unit id="Include_comments"> <source>Include _comments</source> <target state="translated">Incluir _comments</target> <note /> </trans-unit> <trans-unit id="Include_strings"> <source>Include _strings</source> <target state="translated">Incluir _strings</target> <note /> </trans-unit> <trans-unit id="Apply2"> <source>Apply</source> <target state="translated">Aplicar</target> <note /> </trans-unit> <trans-unit id="Change_Signature"> <source>Change Signature</source> <target state="translated">Alterar Assinatura</target> <note /> </trans-unit> <trans-unit id="Preview_Changes_0"> <source>Preview Changes - {0}</source> <target state="translated">Visualizar Alterações - {0}</target> <note /> </trans-unit> <trans-unit id="Preview_Code_Changes_colon"> <source>Preview Code Changes:</source> <target state="translated">Visualizar Alterações de Código:</target> <note /> </trans-unit> <trans-unit id="Preview_Changes"> <source>Preview Changes</source> <target state="translated">Visualizar Alterações</target> <note /> </trans-unit> <trans-unit id="Format_Paste"> <source>Format Paste</source> <target state="translated">Colar Formato</target> <note /> </trans-unit> <trans-unit id="Formatting_pasted_text"> <source>Formatting pasted text...</source> <target state="translated">Formatando texto colado...</target> <note /> </trans-unit> <trans-unit id="The_definition_of_the_object_is_hidden"> <source>The definition of the object is hidden.</source> <target state="translated">A definição do objeto está oculta.</target> <note /> </trans-unit> <trans-unit id="Automatic_Formatting"> <source>Automatic Formatting</source> <target state="translated">Formatação Automática</target> <note /> </trans-unit> <trans-unit id="We_can_fix_the_error_by_not_making_struct_out_ref_parameter_s_Do_you_want_to_proceed"> <source>We can fix the error by not making struct "out/ref" parameter(s). Do you want to proceed?</source> <target state="translated">Podemos corrigir o erro ao não fazer struct de parâmetro(s) "out/ref". Deseja continuar?</target> <note /> </trans-unit> <trans-unit id="Change_Signature_colon"> <source>Change Signature:</source> <target state="translated">Alterar Assinatura:</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1_colon"> <source>Rename '{0}' to '{1}':</source> <target state="translated">Renomear '{0}' para '{1}':</target> <note /> </trans-unit> <trans-unit id="Encapsulate_Field_colon"> <source>Encapsulate Field:</source> <target state="translated">Encapsular Campo:</target> <note /> </trans-unit> <trans-unit id="Call_Hierarchy"> <source>Call Hierarchy</source> <target state="translated">Hierarquia de Chamada</target> <note /> </trans-unit> <trans-unit id="Calls_To_0"> <source>Calls To '{0}'</source> <target state="translated">Chamadas para '{0}'</target> <note /> </trans-unit> <trans-unit id="Calls_To_Base_Member_0"> <source>Calls To Base Member '{0}'</source> <target state="translated">Chamadas para Membro Base '{0}'</target> <note /> </trans-unit> <trans-unit id="Calls_To_Interface_Implementation_0"> <source>Calls To Interface Implementation '{0}'</source> <target state="translated">Chamadas para Implementação de Interface '{0}'</target> <note /> </trans-unit> <trans-unit id="Computing_Call_Hierarchy_Information"> <source>Computing Call Hierarchy Information</source> <target state="translated">Informações sobre Hierarquia de Chamada de Computação</target> <note /> </trans-unit> <trans-unit id="Implements_0"> <source>Implements '{0}'</source> <target state="translated">Implementa '{0}'</target> <note /> </trans-unit> <trans-unit id="Initializers"> <source>Initializers</source> <target state="translated">Inicializadores</target> <note /> </trans-unit> <trans-unit id="References_To_Field_0"> <source>References To Field '{0}'</source> <target state="translated">Referências ao Campo '{0}'</target> <note /> </trans-unit> <trans-unit id="Calls_To_Overrides"> <source>Calls To Overrides</source> <target state="translated">Chamadas para Substituições</target> <note /> </trans-unit> <trans-unit id="Preview_changes1"> <source>_Preview changes</source> <target state="translated">Alterações de _Preview</target> <note /> </trans-unit> <trans-unit id="Apply3"> <source>Apply</source> <target state="translated">Aplicar</target> <note /> </trans-unit> <trans-unit id="Cancel"> <source>Cancel</source> <target state="translated">Cancelar</target> <note /> </trans-unit> <trans-unit id="Changes"> <source>Changes</source> <target state="translated">Alterações</target> <note /> </trans-unit> <trans-unit id="Preview_changes2"> <source>Preview changes</source> <target state="translated">Visualizar alterações</target> <note /> </trans-unit> <trans-unit id="IntelliSense"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note /> </trans-unit> <trans-unit id="IntelliSense_Commit_Formatting"> <source>IntelliSense Commit Formatting</source> <target state="translated">Formatação de Confirmação IntelliSense</target> <note /> </trans-unit> <trans-unit id="Rename_Tracking"> <source>Rename Tracking</source> <target state="translated">Renomear Acompanhamento</target> <note /> </trans-unit> <trans-unit id="Removing_0_from_1_with_content_colon"> <source>Removing '{0}' from '{1}' with content:</source> <target state="translated">Removendo '{0}' de '{1}' com conteúdo:</target> <note /> </trans-unit> <trans-unit id="_0_does_not_support_the_1_operation_However_it_may_contain_nested_2_s_see_2_3_that_support_this_operation"> <source>'{0}' does not support the '{1}' operation. However, it may contain nested '{2}'s (see '{2}.{3}') that support this operation.</source> <target state="translated">'{0}' não dá suporte à operação '{1}'. No entanto, ele pode conter '{2}'s aninhados (consulte '{2}.{3}') que dá suporte a esta operação.</target> <note /> </trans-unit> <trans-unit id="Brace_Completion"> <source>Brace Completion</source> <target state="translated">Preenchimento de Chaves</target> <note /> </trans-unit> <trans-unit id="Cannot_apply_operation_while_a_rename_session_is_active"> <source>Cannot apply operation while a rename session is active.</source> <target state="translated">Não é possível aplicar a operação enquanto uma sessão de renomeação está ativa.</target> <note /> </trans-unit> <trans-unit id="The_rename_tracking_session_was_cancelled_and_is_no_longer_available"> <source>The rename tracking session was cancelled and is no longer available.</source> <target state="translated">A sessão de acompanhamento de renomeação foi cancelada e não está mais disponível.</target> <note /> </trans-unit> <trans-unit id="Highlighted_Written_Reference"> <source>Highlighted Written Reference</source> <target state="translated">Referência Escrita Realçada</target> <note /> </trans-unit> <trans-unit id="Cursor_must_be_on_a_member_name"> <source>Cursor must be on a member name.</source> <target state="translated">O cursor deve estar em um nome do membro.</target> <note /> </trans-unit> <trans-unit id="Brace_Matching"> <source>Brace Matching</source> <target state="translated">Correspondência de Chaves</target> <note /> </trans-unit> <trans-unit id="Locating_implementations"> <source>Locating implementations...</source> <target state="translated">Localizando implementações...</target> <note /> </trans-unit> <trans-unit id="Go_To_Implementation"> <source>Go To Implementation</source> <target state="translated">Ir Para Implementação</target> <note /> </trans-unit> <trans-unit id="The_symbol_has_no_implementations"> <source>The symbol has no implementations.</source> <target state="translated">O símbolo não tem implementações.</target> <note /> </trans-unit> <trans-unit id="New_name_colon_0"> <source>New name: {0}</source> <target state="translated">Novo nome: {0}</target> <note /> </trans-unit> <trans-unit id="Modify_any_highlighted_location_to_begin_renaming"> <source>Modify any highlighted location to begin renaming.</source> <target state="translated">Modifique qualquer local realçado para iniciar a renomeação.</target> <note /> </trans-unit> <trans-unit id="Paste"> <source>Paste</source> <target state="translated">Colar</target> <note /> </trans-unit> <trans-unit id="Navigating"> <source>Navigating...</source> <target state="translated">Navegando...</target> <note /> </trans-unit> <trans-unit id="Suggestion_ellipses"> <source>Suggestion ellipses (…)</source> <target state="translated">Reticências de sugestão (…)</target> <note /> </trans-unit> <trans-unit id="_0_references"> <source>'{0}' references</source> <target state="translated">'{0}' referências</target> <note /> </trans-unit> <trans-unit id="_0_implementations"> <source>'{0}' implementations</source> <target state="translated">'Implementações de '{0}'</target> <note /> </trans-unit> <trans-unit id="_0_declarations"> <source>'{0}' declarations</source> <target state="translated">'Declarações de '{0}'</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Conflict"> <source>Inline Rename Conflict</source> <target state="translated">Conflito de Renomeação Embutida</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Field_Background_and_Border"> <source>Inline Rename Field Background and Border</source> <target state="translated">Borda e Tela de Fundo do Campo de Renomeação Embutida</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Field_Text"> <source>Inline Rename Field Text</source> <target state="translated">Texto do Campo de Renomeação Embutida</target> <note /> </trans-unit> <trans-unit id="Block_Comment_Editing"> <source>Block Comment Editing</source> <target state="translated">Bloquear Edição de Comentário</target> <note /> </trans-unit> <trans-unit id="Comment_Uncomment_Selection"> <source>Comment/Uncomment Selection</source> <target state="translated">Comentar/Remover Marca de Comentário da Seleção</target> <note /> </trans-unit> <trans-unit id="Code_Completion"> <source>Code Completion</source> <target state="translated">Conclusão de Código</target> <note /> </trans-unit> <trans-unit id="Execute_In_Interactive"> <source>Execute In Interactive</source> <target state="translated">Executar em Interativo</target> <note /> </trans-unit> <trans-unit id="Extract_Interface"> <source>Extract Interface</source> <target state="translated">Extrair a Interface</target> <note /> </trans-unit> <trans-unit id="Go_To_Adjacent_Member"> <source>Go To Adjacent Member</source> <target state="translated">Ir para Membro Adjacente</target> <note /> </trans-unit> <trans-unit id="Interactive"> <source>Interactive</source> <target state="translated">Interativo</target> <note /> </trans-unit> <trans-unit id="Paste_in_Interactive"> <source>Paste in Interactive</source> <target state="translated">Colar em Interativo</target> <note /> </trans-unit> <trans-unit id="Navigate_To_Highlight_Reference"> <source>Navigate To Highlighted Reference</source> <target state="translated">Navegar para Referência Realçada</target> <note /> </trans-unit> <trans-unit id="Outlining"> <source>Outlining</source> <target state="translated">Estrutura de Tópicos</target> <note /> </trans-unit> <trans-unit id="Rename_Tracking_Cancellation"> <source>Rename Tracking Cancellation</source> <target state="translated">Renomear Cancelamento de Acompanhamento</target> <note /> </trans-unit> <trans-unit id="Signature_Help"> <source>Signature Help</source> <target state="translated">Ajuda da Assinatura</target> <note /> </trans-unit> <trans-unit id="Smart_Token_Formatter"> <source>Smart Token Formatter</source> <target state="translated">Formatador de Token Inteligente</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Workspaces/CoreTest/Editting/SyntaxEditorTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Editing { [UseExportProvider] public class SyntaxEditorTests { private Workspace _emptyWorkspace; private Workspace EmptyWorkspace => _emptyWorkspace ?? (_emptyWorkspace = new AdhocWorkspace()); private void VerifySyntax<TSyntax>(SyntaxNode node, string expectedText) where TSyntax : SyntaxNode { Assert.IsAssignableFrom<TSyntax>(node); var formatted = Formatter.Format(node, EmptyWorkspace); var actualText = formatted.ToFullString(); Assert.Equal(expectedText, actualText); } private SyntaxEditor GetEditor(SyntaxNode root) => new SyntaxEditor(root, EmptyWorkspace); [Fact] public void TestReplaceNode() { var code = @" public class C { public int X; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var editor = GetEditor(cu); var fieldX = editor.Generator.GetMembers(cls)[0]; editor.ReplaceNode(fieldX, editor.Generator.FieldDeclaration("Y", editor.Generator.TypeExpression(SpecialType.System_String), Accessibility.Public)); var newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public string Y; }"); } [Fact] public void TestRemoveNode() { var code = @" public class C { public int X; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var editor = GetEditor(cu); var fieldX = editor.Generator.GetMembers(cls)[0]; editor.RemoveNode(fieldX); var newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { }"); } [Fact] public void TestInsertAfter() { var code = @" public class C { public int X; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var editor = GetEditor(cu); var fieldX = editor.Generator.GetMembers(cls)[0]; editor.InsertAfter(fieldX, editor.Generator.FieldDeclaration("Y", editor.Generator.TypeExpression(SpecialType.System_String), Accessibility.Public)); var newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public int X; public string Y; }"); } [Fact] public void TestInsertBefore() { var code = @" public class C { public int X; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var editor = GetEditor(cu); var fieldX = editor.Generator.GetMembers(cls)[0]; editor.InsertBefore(fieldX, editor.Generator.FieldDeclaration("Y", editor.Generator.TypeExpression(SpecialType.System_String), Accessibility.Public)); var newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public string Y; public int X; }"); } [Fact] public void TestReplaceWithTracking() { // ReplaceNode overload #1 TestReplaceWithTrackingCore((SyntaxNode node, SyntaxNode newNode, SyntaxEditor editor) => { editor.ReplaceNode(node, newNode); }); // ReplaceNode overload #2 TestReplaceWithTrackingCore((SyntaxNode node, SyntaxNode newNode, SyntaxEditor editor) => { editor.ReplaceNode(node, computeReplacement: (originalNode, generator) => newNode); }); // ReplaceNode overload #3 TestReplaceWithTrackingCore((SyntaxNode node, SyntaxNode newNode, SyntaxEditor editor) => { editor.ReplaceNode(node, computeReplacement: (originalNode, generator, argument) => newNode, argument: (object)null); }); } private void TestReplaceWithTrackingCore(Action<SyntaxNode, SyntaxNode, SyntaxEditor> replaceNodeWithTracking) { var code = @" public class C { public int X; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var editor = GetEditor(cu); var fieldX = editor.Generator.GetMembers(cls)[0]; var newFieldY = editor.Generator.FieldDeclaration("Y", editor.Generator.TypeExpression(SpecialType.System_String), Accessibility.Public); replaceNodeWithTracking(fieldX, newFieldY, editor); var newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public string Y; }"); var newFieldYType = newFieldY.DescendantNodes().Single(n => n.ToString() == "string"); var newType = editor.Generator.TypeExpression(SpecialType.System_Char); replaceNodeWithTracking(newFieldYType, newType, editor); newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public char Y; }"); editor.RemoveNode(newFieldY); newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { }"); } [Fact] public void TestReplaceWithTracking_02() { var code = @" public class C { public int X; public string X2; public char X3; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var editor = GetEditor(cu); var cls = cu.Members[0]; var fieldX = editor.Generator.GetMembers(cls)[0]; var fieldX2 = editor.Generator.GetMembers(cls)[1]; var fieldX3 = editor.Generator.GetMembers(cls)[2]; var newFieldY = editor.Generator.FieldDeclaration("Y", editor.Generator.TypeExpression(SpecialType.System_String), Accessibility.Public); editor.ReplaceNode(fieldX, newFieldY); var newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public string Y; public string X2; public char X3; }"); var newFieldYType = newFieldY.DescendantNodes().Single(n => n.ToString() == "string"); var newType = editor.Generator.TypeExpression(SpecialType.System_Char); editor.ReplaceNode(newFieldYType, newType); newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public char Y; public string X2; public char X3; }"); var newFieldY2 = editor.Generator.FieldDeclaration("Y2", editor.Generator.TypeExpression(SpecialType.System_Boolean), Accessibility.Private); editor.ReplaceNode(fieldX2, newFieldY2); newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public char Y; private bool Y2; public char X3; }"); var newFieldZ = editor.Generator.FieldDeclaration("Z", editor.Generator.TypeExpression(SpecialType.System_Boolean), Accessibility.Public); editor.ReplaceNode(newFieldY, newFieldZ); newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public bool Z; private bool Y2; public char X3; }"); var originalFieldX3Type = fieldX3.DescendantNodes().Single(n => n.ToString() == "char"); newType = editor.Generator.TypeExpression(SpecialType.System_Boolean); editor.ReplaceNode(originalFieldX3Type, newType); newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public bool Z; private bool Y2; public bool X3; }"); editor.RemoveNode(newFieldY2); editor.RemoveNode(fieldX3); newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public bool Z; }"); } [Fact] public void TestInsertAfterWithTracking() { // InsertAfter overload #1 TestInsertAfterWithTrackingCore((SyntaxNode node, SyntaxNode newNode, SyntaxEditor editor) => { editor.InsertAfter(node, newNode); }); // InsertAfter overload #2 TestInsertAfterWithTrackingCore((SyntaxNode node, SyntaxNode newNode, SyntaxEditor editor) => { editor.InsertAfter(node, new[] { newNode }); }); } private void TestInsertAfterWithTrackingCore(Action<SyntaxNode, SyntaxNode, SyntaxEditor> insertAfterWithTracking) { var code = @" public class C { public int X; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var editor = GetEditor(cu); var fieldX = editor.Generator.GetMembers(cls)[0]; var newFieldY = editor.Generator.FieldDeclaration("Y", editor.Generator.TypeExpression(SpecialType.System_String), Accessibility.Public); insertAfterWithTracking(fieldX, newFieldY, editor); var newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public int X; public string Y; }"); var newFieldZ = editor.Generator.FieldDeclaration("Z", editor.Generator.TypeExpression(SpecialType.System_String), Accessibility.Public); editor.ReplaceNode(newFieldY, newFieldZ); newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public int X; public string Z; }"); } [Fact] public void TestInsertBeforeWithTracking() { // InsertBefore overload #1 TestInsertBeforeWithTrackingCore((SyntaxNode node, SyntaxNode newNode, SyntaxEditor editor) => { editor.InsertBefore(node, newNode); }); // InsertBefore overload #2 TestInsertBeforeWithTrackingCore((SyntaxNode node, SyntaxNode newNode, SyntaxEditor editor) => { editor.InsertBefore(node, new[] { newNode }); }); } private void TestInsertBeforeWithTrackingCore(Action<SyntaxNode, SyntaxNode, SyntaxEditor> insertBeforeWithTracking) { var code = @" public class C { public int X; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var editor = GetEditor(cu); var fieldX = editor.Generator.GetMembers(cls)[0]; var newFieldY = editor.Generator.FieldDeclaration("Y", editor.Generator.TypeExpression(SpecialType.System_String), Accessibility.Public); insertBeforeWithTracking(fieldX, newFieldY, editor); var newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public string Y; public int X; }"); var newFieldZ = editor.Generator.FieldDeclaration("Z", editor.Generator.TypeExpression(SpecialType.System_String), Accessibility.Public); editor.ReplaceNode(newFieldY, newFieldZ); newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public string Z; public int X; }"); } [Fact] public void TestTrackNode() { var code = @" public class C { public int X; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var editor = GetEditor(cu); var fieldX = editor.Generator.GetMembers(cls)[0]; editor.TrackNode(fieldX); var newRoot = editor.GetChangedRoot(); var currentFieldX = newRoot.GetCurrentNode(fieldX); Assert.NotNull(currentFieldX); } [Fact] public void TestMultipleEdits() { var code = @" public class C { public int X; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var editor = GetEditor(cu); var fieldX = editor.Generator.GetMembers(cls)[0]; editor.InsertAfter(fieldX, editor.Generator.FieldDeclaration("Y", editor.Generator.TypeExpression(SpecialType.System_String), Accessibility.Public)); editor.InsertBefore(fieldX, editor.Generator.FieldDeclaration("Z", editor.Generator.TypeExpression(SpecialType.System_Object), Accessibility.Public)); editor.RemoveNode(fieldX); var newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public object Z; public string Y; }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Editing { [UseExportProvider] public class SyntaxEditorTests { private Workspace _emptyWorkspace; private Workspace EmptyWorkspace => _emptyWorkspace ?? (_emptyWorkspace = new AdhocWorkspace()); private void VerifySyntax<TSyntax>(SyntaxNode node, string expectedText) where TSyntax : SyntaxNode { Assert.IsAssignableFrom<TSyntax>(node); var formatted = Formatter.Format(node, EmptyWorkspace); var actualText = formatted.ToFullString(); Assert.Equal(expectedText, actualText); } private SyntaxEditor GetEditor(SyntaxNode root) => new SyntaxEditor(root, EmptyWorkspace); [Fact] public void TestReplaceNode() { var code = @" public class C { public int X; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var editor = GetEditor(cu); var fieldX = editor.Generator.GetMembers(cls)[0]; editor.ReplaceNode(fieldX, editor.Generator.FieldDeclaration("Y", editor.Generator.TypeExpression(SpecialType.System_String), Accessibility.Public)); var newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public string Y; }"); } [Fact] public void TestRemoveNode() { var code = @" public class C { public int X; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var editor = GetEditor(cu); var fieldX = editor.Generator.GetMembers(cls)[0]; editor.RemoveNode(fieldX); var newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { }"); } [Fact] public void TestInsertAfter() { var code = @" public class C { public int X; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var editor = GetEditor(cu); var fieldX = editor.Generator.GetMembers(cls)[0]; editor.InsertAfter(fieldX, editor.Generator.FieldDeclaration("Y", editor.Generator.TypeExpression(SpecialType.System_String), Accessibility.Public)); var newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public int X; public string Y; }"); } [Fact] public void TestInsertBefore() { var code = @" public class C { public int X; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var editor = GetEditor(cu); var fieldX = editor.Generator.GetMembers(cls)[0]; editor.InsertBefore(fieldX, editor.Generator.FieldDeclaration("Y", editor.Generator.TypeExpression(SpecialType.System_String), Accessibility.Public)); var newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public string Y; public int X; }"); } [Fact] public void TestReplaceWithTracking() { // ReplaceNode overload #1 TestReplaceWithTrackingCore((SyntaxNode node, SyntaxNode newNode, SyntaxEditor editor) => { editor.ReplaceNode(node, newNode); }); // ReplaceNode overload #2 TestReplaceWithTrackingCore((SyntaxNode node, SyntaxNode newNode, SyntaxEditor editor) => { editor.ReplaceNode(node, computeReplacement: (originalNode, generator) => newNode); }); // ReplaceNode overload #3 TestReplaceWithTrackingCore((SyntaxNode node, SyntaxNode newNode, SyntaxEditor editor) => { editor.ReplaceNode(node, computeReplacement: (originalNode, generator, argument) => newNode, argument: (object)null); }); } private void TestReplaceWithTrackingCore(Action<SyntaxNode, SyntaxNode, SyntaxEditor> replaceNodeWithTracking) { var code = @" public class C { public int X; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var editor = GetEditor(cu); var fieldX = editor.Generator.GetMembers(cls)[0]; var newFieldY = editor.Generator.FieldDeclaration("Y", editor.Generator.TypeExpression(SpecialType.System_String), Accessibility.Public); replaceNodeWithTracking(fieldX, newFieldY, editor); var newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public string Y; }"); var newFieldYType = newFieldY.DescendantNodes().Single(n => n.ToString() == "string"); var newType = editor.Generator.TypeExpression(SpecialType.System_Char); replaceNodeWithTracking(newFieldYType, newType, editor); newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public char Y; }"); editor.RemoveNode(newFieldY); newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { }"); } [Fact] public void TestReplaceWithTracking_02() { var code = @" public class C { public int X; public string X2; public char X3; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var editor = GetEditor(cu); var cls = cu.Members[0]; var fieldX = editor.Generator.GetMembers(cls)[0]; var fieldX2 = editor.Generator.GetMembers(cls)[1]; var fieldX3 = editor.Generator.GetMembers(cls)[2]; var newFieldY = editor.Generator.FieldDeclaration("Y", editor.Generator.TypeExpression(SpecialType.System_String), Accessibility.Public); editor.ReplaceNode(fieldX, newFieldY); var newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public string Y; public string X2; public char X3; }"); var newFieldYType = newFieldY.DescendantNodes().Single(n => n.ToString() == "string"); var newType = editor.Generator.TypeExpression(SpecialType.System_Char); editor.ReplaceNode(newFieldYType, newType); newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public char Y; public string X2; public char X3; }"); var newFieldY2 = editor.Generator.FieldDeclaration("Y2", editor.Generator.TypeExpression(SpecialType.System_Boolean), Accessibility.Private); editor.ReplaceNode(fieldX2, newFieldY2); newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public char Y; private bool Y2; public char X3; }"); var newFieldZ = editor.Generator.FieldDeclaration("Z", editor.Generator.TypeExpression(SpecialType.System_Boolean), Accessibility.Public); editor.ReplaceNode(newFieldY, newFieldZ); newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public bool Z; private bool Y2; public char X3; }"); var originalFieldX3Type = fieldX3.DescendantNodes().Single(n => n.ToString() == "char"); newType = editor.Generator.TypeExpression(SpecialType.System_Boolean); editor.ReplaceNode(originalFieldX3Type, newType); newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public bool Z; private bool Y2; public bool X3; }"); editor.RemoveNode(newFieldY2); editor.RemoveNode(fieldX3); newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public bool Z; }"); } [Fact] public void TestInsertAfterWithTracking() { // InsertAfter overload #1 TestInsertAfterWithTrackingCore((SyntaxNode node, SyntaxNode newNode, SyntaxEditor editor) => { editor.InsertAfter(node, newNode); }); // InsertAfter overload #2 TestInsertAfterWithTrackingCore((SyntaxNode node, SyntaxNode newNode, SyntaxEditor editor) => { editor.InsertAfter(node, new[] { newNode }); }); } private void TestInsertAfterWithTrackingCore(Action<SyntaxNode, SyntaxNode, SyntaxEditor> insertAfterWithTracking) { var code = @" public class C { public int X; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var editor = GetEditor(cu); var fieldX = editor.Generator.GetMembers(cls)[0]; var newFieldY = editor.Generator.FieldDeclaration("Y", editor.Generator.TypeExpression(SpecialType.System_String), Accessibility.Public); insertAfterWithTracking(fieldX, newFieldY, editor); var newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public int X; public string Y; }"); var newFieldZ = editor.Generator.FieldDeclaration("Z", editor.Generator.TypeExpression(SpecialType.System_String), Accessibility.Public); editor.ReplaceNode(newFieldY, newFieldZ); newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public int X; public string Z; }"); } [Fact] public void TestInsertBeforeWithTracking() { // InsertBefore overload #1 TestInsertBeforeWithTrackingCore((SyntaxNode node, SyntaxNode newNode, SyntaxEditor editor) => { editor.InsertBefore(node, newNode); }); // InsertBefore overload #2 TestInsertBeforeWithTrackingCore((SyntaxNode node, SyntaxNode newNode, SyntaxEditor editor) => { editor.InsertBefore(node, new[] { newNode }); }); } private void TestInsertBeforeWithTrackingCore(Action<SyntaxNode, SyntaxNode, SyntaxEditor> insertBeforeWithTracking) { var code = @" public class C { public int X; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var editor = GetEditor(cu); var fieldX = editor.Generator.GetMembers(cls)[0]; var newFieldY = editor.Generator.FieldDeclaration("Y", editor.Generator.TypeExpression(SpecialType.System_String), Accessibility.Public); insertBeforeWithTracking(fieldX, newFieldY, editor); var newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public string Y; public int X; }"); var newFieldZ = editor.Generator.FieldDeclaration("Z", editor.Generator.TypeExpression(SpecialType.System_String), Accessibility.Public); editor.ReplaceNode(newFieldY, newFieldZ); newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public string Z; public int X; }"); } [Fact] public void TestTrackNode() { var code = @" public class C { public int X; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var editor = GetEditor(cu); var fieldX = editor.Generator.GetMembers(cls)[0]; editor.TrackNode(fieldX); var newRoot = editor.GetChangedRoot(); var currentFieldX = newRoot.GetCurrentNode(fieldX); Assert.NotNull(currentFieldX); } [Fact] public void TestMultipleEdits() { var code = @" public class C { public int X; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var editor = GetEditor(cu); var fieldX = editor.Generator.GetMembers(cls)[0]; editor.InsertAfter(fieldX, editor.Generator.FieldDeclaration("Y", editor.Generator.TypeExpression(SpecialType.System_String), Accessibility.Public)); editor.InsertBefore(fieldX, editor.Generator.FieldDeclaration("Z", editor.Generator.TypeExpression(SpecialType.System_Object), Accessibility.Public)); editor.RemoveNode(fieldX); var newRoot = editor.GetChangedRoot(); VerifySyntax<CompilationUnitSyntax>( newRoot, @" public class C { public object Z; public string Y; }"); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Workspaces/Core/Portable/xlf/WorkspacesResources.es.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="es" original="../WorkspacesResources.resx"> <body> <trans-unit id="A_project_may_not_reference_itself"> <source>A project may not reference itself.</source> <target state="translated">Un proyecto no puede hacer referencia a sí mismo.</target> <note /> </trans-unit> <trans-unit id="Adding_analyzer_config_documents_is_not_supported"> <source>Adding analyzer config documents is not supported.</source> <target state="translated">No se permite agregar documentos de configuración del analizador.</target> <note /> </trans-unit> <trans-unit id="An_error_occurred_while_reading_the_specified_configuration_file_colon_0"> <source>An error occurred while reading the specified configuration file: {0}</source> <target state="translated">Error al leer el archivo de configuración especificado: {0}</target> <note /> </trans-unit> <trans-unit id="CSharp_files"> <source>C# files</source> <target state="translated">Archivos de C#</target> <note /> </trans-unit> <trans-unit id="Cannot_apply_action_that_is_not_in_0"> <source>Cannot apply action that is not in '{0}'</source> <target state="translated">No se puede aplicar una acción que no está en "{0}".</target> <note /> </trans-unit> <trans-unit id="Changing_analyzer_config_documents_is_not_supported"> <source>Changing analyzer config documents is not supported.</source> <target state="translated">No se permite cambiar documentos de configuración del analizador.</target> <note /> </trans-unit> <trans-unit id="Changing_document_0_is_not_supported"> <source>Changing document '{0}' is not supported.</source> <target state="translated">Documento cambiante '{0}' no es compatible.</target> <note /> </trans-unit> <trans-unit id="CodeAction_{0}_did_not_produce_a_changed_solution"> <source>CodeAction '{0}' did not produce a changed solution</source> <target state="translated">El tipo CodeAction "{0}" no generó una solución modificada</target> <note>"CodeAction" is a specific type, and {0} represents the title shown by the action.</note> </trans-unit> <trans-unit id="Core_EditorConfig_Options"> <source>Core EditorConfig Options</source> <target state="translated">Opciones principales de EditorConfig</target> <note /> </trans-unit> <trans-unit id="DateTimeKind_must_be_Utc"> <source>DateTimeKind must be Utc</source> <target state="translated">DateTimeKind debe ser Utc</target> <note /> </trans-unit> <trans-unit id="Destination_type_must_be_a_0_1_2_or_3_but_given_one_is_4"> <source>Destination type must be a {0}, {1}, {2} or {3}, but given one is {4}.</source> <target state="translated">El tipo de destino debe ser una instancia de {0}, {1}, {2} o {3}, pero el proporcionado es {4}.</target> <note /> </trans-unit> <trans-unit id="Document_does_not_support_syntax_trees"> <source>Document does not support syntax trees</source> <target state="translated">El documento no admite árboles de sintaxis</target> <note /> </trans-unit> <trans-unit id="Error_reading_content_of_source_file_0_1"> <source>Error reading content of source file '{0}' -- '{1}'.</source> <target state="translated">Error al leer el contenido del archivo de origen "{0}"--"{1}".</target> <note /> </trans-unit> <trans-unit id="Indentation_and_spacing"> <source>Indentation and spacing</source> <target state="translated">Sangría y espaciado</target> <note /> </trans-unit> <trans-unit id="New_line_preferences"> <source>New line preferences</source> <target state="translated">Nuevas preferencias de línea</target> <note /> </trans-unit> <trans-unit id="Only_submission_project_can_reference_submission_projects"> <source>Only submission project can reference submission projects.</source> <target state="translated">Solo un proyecto de envío puede hacer referencia a proyectos de envío.</target> <note /> </trans-unit> <trans-unit id="Options_did_not_come_from_specified_Solution"> <source>Options did not come from specified Solution</source> <target state="translated">Las opciones no procedían de la solución especificada.</target> <note /> </trans-unit> <trans-unit id="Predefined_conversion_from_0_to_1"> <source>Predefined conversion from {0} to {1}.</source> <target state="translated">Conversión predefinida de {0} a {1}</target> <note /> </trans-unit> <trans-unit id="Project_does_not_contain_specified_reference"> <source>Project does not contain specified reference</source> <target state="translated">El proyecto no contiene la referencia especificada.</target> <note /> </trans-unit> <trans-unit id="Refactoring_Only"> <source>Refactoring Only</source> <target state="translated">Solo refactorización</target> <note /> </trans-unit> <trans-unit id="Remove_the_line_below_if_you_want_to_inherit_dot_editorconfig_settings_from_higher_directories"> <source>Remove the line below if you want to inherit .editorconfig settings from higher directories</source> <target state="translated">Elimine la línea siguiente si desea heredar la configuración de .editorconfig de directorios más elevados</target> <note /> </trans-unit> <trans-unit id="Removing_analyzer_config_documents_is_not_supported"> <source>Removing analyzer config documents is not supported.</source> <target state="translated">No se permite quitar documentos de configuración del analizador.</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1"> <source>Rename '{0}' to '{1}'</source> <target state="translated">Cambiar el nombre de '{0}' a '{1}'</target> <note /> </trans-unit> <trans-unit id="Solution_does_not_contain_specified_reference"> <source>Solution does not contain specified reference</source> <target state="translated">La solución no contiene la referencia especificada</target> <note /> </trans-unit> <trans-unit id="Symbol_0_is_not_from_source"> <source>Symbol "{0}" is not from source.</source> <target state="translated">El símbolo "{0}" no procede del código fuente.</target> <note /> </trans-unit> <trans-unit id="Documentation_comment_id_must_start_with_E_F_M_N_P_or_T"> <source>Documentation comment id must start with E, F, M, N, P or T</source> <target state="translated">El Id. del comentario de la documentación debe comenzar por E, F, M, N, P o T</target> <note /> </trans-unit> <trans-unit id="Cycle_detected_in_extensions"> <source>Cycle detected in extensions</source> <target state="translated">Detectado ciclo en extensiones</target> <note /> </trans-unit> <trans-unit id="Destination_type_must_be_a_0_but_given_one_is_1"> <source>Destination type must be a {0}, but given one is {1}.</source> <target state="translated">El tipo de destino debe ser un {0}, pero el proporcionado es {1}.</target> <note /> </trans-unit> <trans-unit id="Destination_type_must_be_a_0_or_a_1_but_given_one_is_2"> <source>Destination type must be a {0} or a {1}, but given one is {2}.</source> <target state="translated">El tipo de destino debe ser un {0} o un {1}, pero el proporcionado es {2}.</target> <note /> </trans-unit> <trans-unit id="Destination_type_must_be_a_0_1_or_2_but_given_one_is_3"> <source>Destination type must be a {0}, {1} or {2}, but given one is {3}.</source> <target state="translated">El tipo de destino debe ser un {0}, {1} o {2}, pero el proporcionado es {3}.</target> <note /> </trans-unit> <trans-unit id="Could_not_find_location_to_generation_symbol_into"> <source>Could not find location to generation symbol into.</source> <target state="translated">No se pudo encontrar una ubicación en la que generar un símbolo.</target> <note /> </trans-unit> <trans-unit id="No_location_provided_to_add_statements_to"> <source>No location provided to add statements to.</source> <target state="translated">No se ha proporcionado ubicación a la que agregar instrucciones.</target> <note /> </trans-unit> <trans-unit id="Destination_location_was_not_in_source"> <source>Destination location was not in source.</source> <target state="translated">La ubicación de destino no estaba en el código fuente.</target> <note /> </trans-unit> <trans-unit id="Destination_location_was_from_a_different_tree"> <source>Destination location was from a different tree.</source> <target state="translated">La ubicación de destino era de otro árbol.</target> <note /> </trans-unit> <trans-unit id="Node_is_of_the_wrong_type"> <source>Node is of the wrong type.</source> <target state="translated">El nodo es del tipo erróneo.</target> <note /> </trans-unit> <trans-unit id="Location_must_be_null_or_from_source"> <source>Location must be null or from source.</source> <target state="translated">La ubicación debe ser null o del código fuente.</target> <note /> </trans-unit> <trans-unit id="Duplicate_source_file_0_in_project_1"> <source>Duplicate source file '{0}' in project '{1}'</source> <target state="translated">Archivo de código fuente '{0}' duplicado en el proyecto '{1}'</target> <note /> </trans-unit> <trans-unit id="Removing_projects_is_not_supported"> <source>Removing projects is not supported.</source> <target state="translated">No se admite la eliminación de proyectos.</target> <note /> </trans-unit> <trans-unit id="Adding_projects_is_not_supported"> <source>Adding projects is not supported.</source> <target state="translated">No se admite la adición de proyectos.</target> <note /> </trans-unit> <trans-unit id="Symbols_project_could_not_be_found_in_the_provided_solution"> <source>Symbol's project could not be found in the provided solution</source> <target state="translated">No se pudo encontrar el proyecto del símbolo en la solución proporcionada.</target> <note /> </trans-unit> <trans-unit id="Sync_namespace_to_folder_structure"> <source>Sync namespace to folder structure</source> <target state="translated">Sincronizar espacio de nombres con estructura de carpetas</target> <note /> </trans-unit> <trans-unit id="The_contents_of_a_SourceGeneratedDocument_may_not_be_changed"> <source>The contents of a SourceGeneratedDocument may not be changed.</source> <target state="translated">No se puede cambiar el contenido de un elemento SourceGeneratedDocument.</target> <note>{locked:SourceGeneratedDocument}</note> </trans-unit> <trans-unit id="The_project_already_contains_the_specified_reference"> <source>The project already contains the specified reference.</source> <target state="translated">El proyecto ya contiene la referencia especificada.</target> <note /> </trans-unit> <trans-unit id="The_solution_already_contains_the_specified_reference"> <source>The solution already contains the specified reference.</source> <target state="translated">La solución ya contiene la referencia especificada.</target> <note /> </trans-unit> <trans-unit id="Unknown"> <source>Unknown</source> <target state="translated">Desconocido</target> <note /> </trans-unit> <trans-unit id="Visual_Basic_files"> <source>Visual Basic files</source> <target state="translated">Archivos de Visual Basic</target> <note /> </trans-unit> <trans-unit id="Warning_adding_imports_will_bring_an_extension_method_into_scope_with_the_same_name_as_member_access"> <source>Adding imports will bring an extension method into scope with the same name as '{0}'</source> <target state="translated">Al agregar importaciones, se incorporará un método de extensión en el ámbito con el mismo nombre que "{0}".</target> <note /> </trans-unit> <trans-unit id="Workspace_error"> <source>Workspace error</source> <target state="translated">Error del área de trabajo</target> <note /> </trans-unit> <trans-unit id="Workspace_is_not_empty"> <source>Workspace is not empty.</source> <target state="translated">El área de trabajo no está vacía.</target> <note /> </trans-unit> <trans-unit id="_0_is_in_a_different_project"> <source>{0} is in a different project.</source> <target state="translated">{0} está en un proyecto distinto.</target> <note /> </trans-unit> <trans-unit id="_0_is_not_part_of_the_workspace"> <source>'{0}' is not part of the workspace.</source> <target state="translated">'{0}' no es parte del área de trabajo.</target> <note /> </trans-unit> <trans-unit id="_0_is_already_part_of_the_workspace"> <source>'{0}' is already part of the workspace.</source> <target state="translated">'{0}' ya es parte del área de trabajo.</target> <note /> </trans-unit> <trans-unit id="_0_is_not_referenced"> <source>'{0}' is not referenced.</source> <target state="translated">'No hay referencia a '{0}'.</target> <note /> </trans-unit> <trans-unit id="_0_is_already_referenced"> <source>'{0}' is already referenced.</source> <target state="translated">'Ya hay una referencia a '{0}'.</target> <note /> </trans-unit> <trans-unit id="Adding_project_reference_from_0_to_1_will_cause_a_circular_reference"> <source>Adding project reference from '{0}' to '{1}' will cause a circular reference.</source> <target state="translated">La adición de una referencia de proyecto de '{0}' a '{1}' originará una referencia circular.</target> <note /> </trans-unit> <trans-unit id="Metadata_is_not_referenced"> <source>Metadata is not referenced.</source> <target state="translated">No hay referencia a los metadatos.</target> <note /> </trans-unit> <trans-unit id="Metadata_is_already_referenced"> <source>Metadata is already referenced.</source> <target state="translated">Ya hay una referencia a los metadatos.</target> <note /> </trans-unit> <trans-unit id="_0_is_not_present"> <source>{0} is not present.</source> <target state="translated">{0} no está presente.</target> <note /> </trans-unit> <trans-unit id="_0_is_already_present"> <source>{0} is already present.</source> <target state="translated">{0} ya está presente.</target> <note /> </trans-unit> <trans-unit id="The_specified_document_is_not_a_version_of_this_document"> <source>The specified document is not a version of this document.</source> <target state="translated">El documento especificado no es una versión de este documento.</target> <note /> </trans-unit> <trans-unit id="The_language_0_is_not_supported"> <source>The language '{0}' is not supported.</source> <target state="translated">El lenguaje '{0}' no es compatible.</target> <note /> </trans-unit> <trans-unit id="The_solution_already_contains_the_specified_project"> <source>The solution already contains the specified project.</source> <target state="translated">La solución ya contiene el proyecto especificado.</target> <note /> </trans-unit> <trans-unit id="The_solution_does_not_contain_the_specified_project"> <source>The solution does not contain the specified project.</source> <target state="translated">La solución no contiene el proyecto especificado.</target> <note /> </trans-unit> <trans-unit id="The_project_already_references_the_target_project"> <source>The project already references the target project.</source> <target state="translated">El proyecto ya hace referencia al proyecto de destino.</target> <note /> </trans-unit> <trans-unit id="The_solution_already_contains_the_specified_document"> <source>The solution already contains the specified document.</source> <target state="translated">La solución ya contiene el documento especificado.</target> <note /> </trans-unit> <trans-unit id="Temporary_storage_cannot_be_written_more_than_once"> <source>Temporary storage cannot be written more than once.</source> <target state="translated">No se puede escribir más de una vez en el almacenamiento temporal.</target> <note /> </trans-unit> <trans-unit id="_0_is_not_open"> <source>'{0}' is not open.</source> <target state="translated">'{0}' no está abierto.</target> <note /> </trans-unit> <trans-unit id="A_language_name_cannot_be_specified_for_this_option"> <source>A language name cannot be specified for this option.</source> <target state="translated">No se puede especificar un nombre de lenguaje para esta opción.</target> <note /> </trans-unit> <trans-unit id="A_language_name_must_be_specified_for_this_option"> <source>A language name must be specified for this option.</source> <target state="translated">Se debe especificar un nombre de lenguaje para esta opción.</target> <note /> </trans-unit> <trans-unit id="File_was_externally_modified_colon_0"> <source>File was externally modified: {0}.</source> <target state="translated">El archivo se modificó externamente: {0}.</target> <note /> </trans-unit> <trans-unit id="Unrecognized_language_name"> <source>Unrecognized language name.</source> <target state="translated">Nombre de lenguaje no reconocido.</target> <note /> </trans-unit> <trans-unit id="Can_t_resolve_metadata_reference_colon_0"> <source>Can't resolve metadata reference: '{0}'.</source> <target state="translated">No se puede resolver la referencia de metadatos: '{0}'.</target> <note /> </trans-unit> <trans-unit id="Can_t_resolve_analyzer_reference_colon_0"> <source>Can't resolve analyzer reference: '{0}'.</source> <target state="translated">No se puede resolver la referencia del analizador: '{0}'.</target> <note /> </trans-unit> <trans-unit id="Invalid_project_block_expected_after_Project"> <source>Invalid project block, expected "=" after Project.</source> <target state="translated">Bloque de proyecto no válido, se esperaba "=" después de Project.</target> <note /> </trans-unit> <trans-unit id="Invalid_project_block_expected_after_project_name"> <source>Invalid project block, expected "," after project name.</source> <target state="translated">Bloque de proyecto no válido, se esperaba "," después del nombre del proyecto.</target> <note /> </trans-unit> <trans-unit id="Invalid_project_block_expected_after_project_path"> <source>Invalid project block, expected "," after project path.</source> <target state="translated">Bloque de proyecto no válido, se esperaba "," después de la ruta de acceso del proyecto.</target> <note /> </trans-unit> <trans-unit id="Expected_0"> <source>Expected {0}.</source> <target state="translated">Se esperaba {0}.</target> <note /> </trans-unit> <trans-unit id="_0_must_be_a_non_null_and_non_empty_string"> <source>"{0}" must be a non-null and non-empty string.</source> <target state="translated">"{0}" debe ser una cadena que no sea Null ni esté vacía.</target> <note /> </trans-unit> <trans-unit id="Expected_header_colon_0"> <source>Expected header: "{0}".</source> <target state="translated">Se esperaba encabezado: "{0}".</target> <note /> </trans-unit> <trans-unit id="Expected_end_of_file"> <source>Expected end-of-file.</source> <target state="translated">Se esperaba fin de archivo.</target> <note /> </trans-unit> <trans-unit id="Expected_0_line"> <source>Expected {0} line.</source> <target state="translated">Se esperaba línea {0}.</target> <note /> </trans-unit> <trans-unit id="This_submission_already_references_another_submission_project"> <source>This submission already references another submission project.</source> <target state="translated">Este envío ya hace referencia a otro proyecto de envío.</target> <note /> </trans-unit> <trans-unit id="_0_still_contains_open_documents"> <source>{0} still contains open documents.</source> <target state="translated">{0} aún contiene documentos abiertos.</target> <note /> </trans-unit> <trans-unit id="_0_is_still_open"> <source>{0} is still open.</source> <target state="translated">{0} aún está abierto.</target> <note /> </trans-unit> <trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized"> <source>Arrays with more than one dimension cannot be serialized.</source> <target state="translated">Las matrices con más de una dimensión no se pueden serializar.</target> <note /> </trans-unit> <trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer"> <source>Value too large to be represented as a 30 bit unsigned integer.</source> <target state="translated">Valor demasiado largo para representarse como entero sin signo de 30 bits.</target> <note /> </trans-unit> <trans-unit id="Specified_path_must_be_absolute"> <source>Specified path must be absolute.</source> <target state="translated">La ruta de acceso especificada debe ser absoluta.</target> <note /> </trans-unit> <trans-unit id="Name_can_be_simplified"> <source>Name can be simplified.</source> <target state="translated">El nombre se puede simplificar.</target> <note /> </trans-unit> <trans-unit id="Unknown_identifier"> <source>Unknown identifier.</source> <target state="translated">Identificador desconocido.</target> <note /> </trans-unit> <trans-unit id="Cannot_generate_code_for_unsupported_operator_0"> <source>Cannot generate code for unsupported operator '{0}'</source> <target state="translated">No se puede generar código para el operador no compatible '{0}'</target> <note /> </trans-unit> <trans-unit id="Invalid_number_of_parameters_for_binary_operator"> <source>Invalid number of parameters for binary operator.</source> <target state="translated">Número de parámetros no válido para el operador binario.</target> <note /> </trans-unit> <trans-unit id="Invalid_number_of_parameters_for_unary_operator"> <source>Invalid number of parameters for unary operator.</source> <target state="translated">Número de parámetros no válido para el operador unario.</target> <note /> </trans-unit> <trans-unit id="Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language"> <source>Cannot open project '{0}' because the file extension '{1}' is not associated with a language.</source> <target state="translated">No se puede abrir el proyecto '{0}' porque la extensión de archivo '{1}' no está asociada a un lenguaje.</target> <note /> </trans-unit> <trans-unit id="Cannot_open_project_0_because_the_language_1_is_not_supported"> <source>Cannot open project '{0}' because the language '{1}' is not supported.</source> <target state="translated">No se puede abrir el proyecto '{0}' porque el lenguaje '{1}' no es compatible.</target> <note /> </trans-unit> <trans-unit id="Invalid_project_file_path_colon_0"> <source>Invalid project file path: '{0}'</source> <target state="translated">Ruta de acceso del archivo de proyecto no válida: '{0}'</target> <note /> </trans-unit> <trans-unit id="Invalid_solution_file_path_colon_0"> <source>Invalid solution file path: '{0}'</source> <target state="translated">Ruta de acceso del archivo de solución no válida: '{0}'</target> <note /> </trans-unit> <trans-unit id="Project_file_not_found_colon_0"> <source>Project file not found: '{0}'</source> <target state="translated">Archivo de proyecto no encontrado: '{0}'</target> <note /> </trans-unit> <trans-unit id="Solution_file_not_found_colon_0"> <source>Solution file not found: '{0}'</source> <target state="translated">Archivo de solución no encontrado: '{0}'</target> <note /> </trans-unit> <trans-unit id="Unmerged_change_from_project_0"> <source>Unmerged change from project '{0}'</source> <target state="translated">Cambio no fusionado mediante combinación del proyecto '{0}'</target> <note /> </trans-unit> <trans-unit id="Added_colon"> <source>Added:</source> <target state="translated">Agregado:</target> <note /> </trans-unit> <trans-unit id="After_colon"> <source>After:</source> <target state="translated">Después:</target> <note /> </trans-unit> <trans-unit id="Before_colon"> <source>Before:</source> <target state="translated">Antes:</target> <note /> </trans-unit> <trans-unit id="Removed_colon"> <source>Removed:</source> <target state="translated">Quitado:</target> <note /> </trans-unit> <trans-unit id="Invalid_CodePage_value_colon_0"> <source>Invalid CodePage value: {0}</source> <target state="translated">Valor de página de códigos no válido: {0}</target> <note /> </trans-unit> <trans-unit id="Adding_additional_documents_is_not_supported"> <source>Adding additional documents is not supported.</source> <target state="translated">No se permite agregar documentos adicionales.</target> <note /> </trans-unit> <trans-unit id="Adding_analyzer_references_is_not_supported"> <source>Adding analyzer references is not supported.</source> <target state="translated">No se permite agregar referencias de analizador.</target> <note /> </trans-unit> <trans-unit id="Adding_documents_is_not_supported"> <source>Adding documents is not supported.</source> <target state="translated">No se permite agregar documentos.</target> <note /> </trans-unit> <trans-unit id="Adding_metadata_references_is_not_supported"> <source>Adding metadata references is not supported.</source> <target state="translated">No se permite agregar referencias de metadatos.</target> <note /> </trans-unit> <trans-unit id="Adding_project_references_is_not_supported"> <source>Adding project references is not supported.</source> <target state="translated">No se permite agregar referencias de proyectos.</target> <note /> </trans-unit> <trans-unit id="Changing_additional_documents_is_not_supported"> <source>Changing additional documents is not supported.</source> <target state="translated">No se permite cambiar documentos adicionales.</target> <note /> </trans-unit> <trans-unit id="Changing_documents_is_not_supported"> <source>Changing documents is not supported.</source> <target state="translated">No se permite cambiar documentos.</target> <note /> </trans-unit> <trans-unit id="Changing_project_properties_is_not_supported"> <source>Changing project properties is not supported.</source> <target state="translated">No se permite cambiar propiedades de proyectos.</target> <note /> </trans-unit> <trans-unit id="Removing_additional_documents_is_not_supported"> <source>Removing additional documents is not supported.</source> <target state="translated">No se permite quitar documentos adicionales.</target> <note /> </trans-unit> <trans-unit id="Removing_analyzer_references_is_not_supported"> <source>Removing analyzer references is not supported.</source> <target state="translated">No se permite quitar referencias de analizador.</target> <note /> </trans-unit> <trans-unit id="Removing_documents_is_not_supported"> <source>Removing documents is not supported.</source> <target state="translated">No se permite quitar documentos.</target> <note /> </trans-unit> <trans-unit id="Removing_metadata_references_is_not_supported"> <source>Removing metadata references is not supported.</source> <target state="translated">No se permite quitar referencias de metadatos.</target> <note /> </trans-unit> <trans-unit id="Removing_project_references_is_not_supported"> <source>Removing project references is not supported.</source> <target state="translated">No se permite quitar referencias de proyectos.</target> <note /> </trans-unit> <trans-unit id="Service_of_type_0_is_required_to_accomplish_the_task_but_is_not_available_from_the_workspace"> <source>Service of type '{0}' is required to accomplish the task but is not available from the workspace.</source> <target state="translated">El servicio de tipo '{0}' es necesario para realizar la tarea, pero no está disponibles desde el área de trabajo.</target> <note /> </trans-unit> <trans-unit id="At_least_one_diagnostic_must_be_supplied"> <source>At least one diagnostic must be supplied.</source> <target state="translated">Se debe suministrar al menos un diagnóstico.</target> <note /> </trans-unit> <trans-unit id="Diagnostic_must_have_span_0"> <source>Diagnostic must have span '{0}'</source> <target state="translated">El diagnóstico debe tener el intervalo '{0}'</target> <note /> </trans-unit> <trans-unit id="Cannot_deserialize_type_0"> <source>Cannot deserialize type '{0}'.</source> <target state="translated">No se puede deserializar el tipo "{0}".</target> <note /> </trans-unit> <trans-unit id="Cannot_serialize_type_0"> <source>Cannot serialize type '{0}'.</source> <target state="translated">No se puede serializar el tipo "{0}".</target> <note /> </trans-unit> <trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder"> <source>The type '{0}' is not understood by the serialization binder.</source> <target state="translated">El enlazador de serialización no comprende el tipo "{0}".</target> <note /> </trans-unit> <trans-unit id="Label_for_node_0_is_invalid_it_must_be_within_bracket_0_1"> <source>Label for node '{0}' is invalid, it must be within [0, {1}).</source> <target state="translated">La etiqueta para el nodo "{0}" no es válida; debe estar dentro del intervalo [0, {1}).</target> <note /> </trans-unit> <trans-unit id="Matching_nodes_0_and_1_must_have_the_same_label"> <source>Matching nodes '{0}' and '{1}' must have the same label.</source> <target state="translated">Los nodos coincidentes "{0}" y "{1}" deben tener la misma etiqueta.</target> <note /> </trans-unit> <trans-unit id="Node_0_must_be_contained_in_the_new_tree"> <source>Node '{0}' must be contained in the new tree.</source> <target state="translated">El nodo "{0}" debe incluirse en el árbol nuevo.</target> <note /> </trans-unit> <trans-unit id="Node_0_must_be_contained_in_the_old_tree"> <source>Node '{0}' must be contained in the old tree.</source> <target state="translated">El nodo "{0}" debe incluirse en el árbol antiguo.</target> <note /> </trans-unit> <trans-unit id="The_member_0_is_not_declared_within_the_declaration_of_the_symbol"> <source>The member '{0}' is not declared within the declaration of the symbol.</source> <target state="translated">No se ha declarado el miembro '{0}' dentro de la declaración del símbolo.</target> <note /> </trans-unit> <trans-unit id="The_position_is_not_within_the_symbol_s_declaration"> <source>The position is not within the symbol's declaration</source> <target state="translated">La posición no se encuentra dentro de la declaración del símbolo</target> <note /> </trans-unit> <trans-unit id="The_symbol_0_cannot_be_located_within_the_current_solution"> <source>The symbol '{0}' cannot be located within the current solution.</source> <target state="translated">El símbolo '{0}' no puede estar dentro de la solución actual.</target> <note /> </trans-unit> <trans-unit id="Changing_compilation_options_is_not_supported"> <source>Changing compilation options is not supported.</source> <target state="translated">No se admite el cambio de las opciones de compilación.</target> <note /> </trans-unit> <trans-unit id="Changing_parse_options_is_not_supported"> <source>Changing parse options is not supported.</source> <target state="translated">No se admite el cambio de las opciones de análisis.</target> <note /> </trans-unit> <trans-unit id="The_node_is_not_part_of_the_tree"> <source>The node is not part of the tree.</source> <target state="translated">El nodo no forma parte del árbol.</target> <note /> </trans-unit> <trans-unit id="This_workspace_does_not_support_opening_and_closing_documents"> <source>This workspace does not support opening and closing documents.</source> <target state="translated">Esta área de trabajo no admite la apertura y el cierre de documentos.</target> <note /> </trans-unit> <trans-unit id="Exceptions_colon"> <source>Exceptions:</source> <target state="translated">Excepciones:</target> <note /> </trans-unit> <trans-unit id="_0_returned_an_uninitialized_ImmutableArray"> <source>'{0}' returned an uninitialized ImmutableArray</source> <target state="translated">'{0}' devolvió una ImmutableArray sin inicializar</target> <note /> </trans-unit> <trans-unit id="Failure"> <source>Failure</source> <target state="translated">Error</target> <note /> </trans-unit> <trans-unit id="Warning"> <source>Warning</source> <target state="translated">Advertencia</target> <note /> </trans-unit> <trans-unit id="Enable"> <source>Enable</source> <target state="translated">Habilitar</target> <note /> </trans-unit> <trans-unit id="Enable_and_ignore_future_errors"> <source>Enable and ignore future errors</source> <target state="translated">Habilitar y omitir futuros errores</target> <note /> </trans-unit> <trans-unit id="_0_encountered_an_error_and_has_been_disabled"> <source>'{0}' encountered an error and has been disabled.</source> <target state="translated">'{0}' detectó un error y se ha deshabilitado.</target> <note /> </trans-unit> <trans-unit id="Show_Stack_Trace"> <source>Show Stack Trace</source> <target state="translated">Mostrar seguimiento de la pila</target> <note /> </trans-unit> <trans-unit id="Stream_is_too_long"> <source>Stream is too long.</source> <target state="translated">Secuencia demasiado larga.</target> <note /> </trans-unit> <trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values"> <source>Deserialization reader for '{0}' read incorrect number of values.</source> <target state="translated">El lector de deserialización de "{0}" leyó un número incorrecto de valores.</target> <note /> </trans-unit> <trans-unit id="Async_Method"> <source>Async Method</source> <target state="translated">Metodo asincrónico</target> <note>{locked: async}{locked: method} These are keywords (unless the order of words or capitalization should be handled differently)</note> </trans-unit> <trans-unit id="Error"> <source>Error</source> <target state="translated">Fehler</target> <note /> </trans-unit> <trans-unit id="None"> <source>None</source> <target state="translated">NONE</target> <note /> </trans-unit> <trans-unit id="Suggestion"> <source>Suggestion</source> <target state="translated">Sugerencia</target> <note /> </trans-unit> <trans-unit id="File_0_size_of_1_exceeds_maximum_allowed_size_of_2"> <source>File '{0}' size of {1} exceeds maximum allowed size of {2}</source> <target state="translated">El archivo "{0}" con un tamaño de {1} supera el tamaño máximo permitido de {2}</target> <note /> </trans-unit> <trans-unit id="Changing_document_property_is_not_supported"> <source>Changing document properties is not supported</source> <target state="translated">No se admite el cambio de propiedades de documentos</target> <note /> </trans-unit> <trans-unit id="dot_NET_Coding_Conventions"> <source>.NET Coding Conventions</source> <target state="translated">Convenciones de codificación .NET</target> <note /> </trans-unit> <trans-unit id="Variables_captured_colon"> <source>Variables captured:</source> <target state="translated">Variables capturadas:</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="es" original="../WorkspacesResources.resx"> <body> <trans-unit id="A_project_may_not_reference_itself"> <source>A project may not reference itself.</source> <target state="translated">Un proyecto no puede hacer referencia a sí mismo.</target> <note /> </trans-unit> <trans-unit id="Adding_analyzer_config_documents_is_not_supported"> <source>Adding analyzer config documents is not supported.</source> <target state="translated">No se permite agregar documentos de configuración del analizador.</target> <note /> </trans-unit> <trans-unit id="An_error_occurred_while_reading_the_specified_configuration_file_colon_0"> <source>An error occurred while reading the specified configuration file: {0}</source> <target state="translated">Error al leer el archivo de configuración especificado: {0}</target> <note /> </trans-unit> <trans-unit id="CSharp_files"> <source>C# files</source> <target state="translated">Archivos de C#</target> <note /> </trans-unit> <trans-unit id="Cannot_apply_action_that_is_not_in_0"> <source>Cannot apply action that is not in '{0}'</source> <target state="translated">No se puede aplicar una acción que no está en "{0}".</target> <note /> </trans-unit> <trans-unit id="Changing_analyzer_config_documents_is_not_supported"> <source>Changing analyzer config documents is not supported.</source> <target state="translated">No se permite cambiar documentos de configuración del analizador.</target> <note /> </trans-unit> <trans-unit id="Changing_document_0_is_not_supported"> <source>Changing document '{0}' is not supported.</source> <target state="translated">Documento cambiante '{0}' no es compatible.</target> <note /> </trans-unit> <trans-unit id="CodeAction_{0}_did_not_produce_a_changed_solution"> <source>CodeAction '{0}' did not produce a changed solution</source> <target state="translated">El tipo CodeAction "{0}" no generó una solución modificada</target> <note>"CodeAction" is a specific type, and {0} represents the title shown by the action.</note> </trans-unit> <trans-unit id="Core_EditorConfig_Options"> <source>Core EditorConfig Options</source> <target state="translated">Opciones principales de EditorConfig</target> <note /> </trans-unit> <trans-unit id="DateTimeKind_must_be_Utc"> <source>DateTimeKind must be Utc</source> <target state="translated">DateTimeKind debe ser Utc</target> <note /> </trans-unit> <trans-unit id="Destination_type_must_be_a_0_1_2_or_3_but_given_one_is_4"> <source>Destination type must be a {0}, {1}, {2} or {3}, but given one is {4}.</source> <target state="translated">El tipo de destino debe ser una instancia de {0}, {1}, {2} o {3}, pero el proporcionado es {4}.</target> <note /> </trans-unit> <trans-unit id="Document_does_not_support_syntax_trees"> <source>Document does not support syntax trees</source> <target state="translated">El documento no admite árboles de sintaxis</target> <note /> </trans-unit> <trans-unit id="Error_reading_content_of_source_file_0_1"> <source>Error reading content of source file '{0}' -- '{1}'.</source> <target state="translated">Error al leer el contenido del archivo de origen "{0}"--"{1}".</target> <note /> </trans-unit> <trans-unit id="Indentation_and_spacing"> <source>Indentation and spacing</source> <target state="translated">Sangría y espaciado</target> <note /> </trans-unit> <trans-unit id="New_line_preferences"> <source>New line preferences</source> <target state="translated">Nuevas preferencias de línea</target> <note /> </trans-unit> <trans-unit id="Only_submission_project_can_reference_submission_projects"> <source>Only submission project can reference submission projects.</source> <target state="translated">Solo un proyecto de envío puede hacer referencia a proyectos de envío.</target> <note /> </trans-unit> <trans-unit id="Options_did_not_come_from_specified_Solution"> <source>Options did not come from specified Solution</source> <target state="translated">Las opciones no procedían de la solución especificada.</target> <note /> </trans-unit> <trans-unit id="Predefined_conversion_from_0_to_1"> <source>Predefined conversion from {0} to {1}.</source> <target state="translated">Conversión predefinida de {0} a {1}</target> <note /> </trans-unit> <trans-unit id="Project_does_not_contain_specified_reference"> <source>Project does not contain specified reference</source> <target state="translated">El proyecto no contiene la referencia especificada.</target> <note /> </trans-unit> <trans-unit id="Refactoring_Only"> <source>Refactoring Only</source> <target state="translated">Solo refactorización</target> <note /> </trans-unit> <trans-unit id="Remove_the_line_below_if_you_want_to_inherit_dot_editorconfig_settings_from_higher_directories"> <source>Remove the line below if you want to inherit .editorconfig settings from higher directories</source> <target state="translated">Elimine la línea siguiente si desea heredar la configuración de .editorconfig de directorios más elevados</target> <note /> </trans-unit> <trans-unit id="Removing_analyzer_config_documents_is_not_supported"> <source>Removing analyzer config documents is not supported.</source> <target state="translated">No se permite quitar documentos de configuración del analizador.</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1"> <source>Rename '{0}' to '{1}'</source> <target state="translated">Cambiar el nombre de '{0}' a '{1}'</target> <note /> </trans-unit> <trans-unit id="Solution_does_not_contain_specified_reference"> <source>Solution does not contain specified reference</source> <target state="translated">La solución no contiene la referencia especificada</target> <note /> </trans-unit> <trans-unit id="Symbol_0_is_not_from_source"> <source>Symbol "{0}" is not from source.</source> <target state="translated">El símbolo "{0}" no procede del código fuente.</target> <note /> </trans-unit> <trans-unit id="Documentation_comment_id_must_start_with_E_F_M_N_P_or_T"> <source>Documentation comment id must start with E, F, M, N, P or T</source> <target state="translated">El Id. del comentario de la documentación debe comenzar por E, F, M, N, P o T</target> <note /> </trans-unit> <trans-unit id="Cycle_detected_in_extensions"> <source>Cycle detected in extensions</source> <target state="translated">Detectado ciclo en extensiones</target> <note /> </trans-unit> <trans-unit id="Destination_type_must_be_a_0_but_given_one_is_1"> <source>Destination type must be a {0}, but given one is {1}.</source> <target state="translated">El tipo de destino debe ser un {0}, pero el proporcionado es {1}.</target> <note /> </trans-unit> <trans-unit id="Destination_type_must_be_a_0_or_a_1_but_given_one_is_2"> <source>Destination type must be a {0} or a {1}, but given one is {2}.</source> <target state="translated">El tipo de destino debe ser un {0} o un {1}, pero el proporcionado es {2}.</target> <note /> </trans-unit> <trans-unit id="Destination_type_must_be_a_0_1_or_2_but_given_one_is_3"> <source>Destination type must be a {0}, {1} or {2}, but given one is {3}.</source> <target state="translated">El tipo de destino debe ser un {0}, {1} o {2}, pero el proporcionado es {3}.</target> <note /> </trans-unit> <trans-unit id="Could_not_find_location_to_generation_symbol_into"> <source>Could not find location to generation symbol into.</source> <target state="translated">No se pudo encontrar una ubicación en la que generar un símbolo.</target> <note /> </trans-unit> <trans-unit id="No_location_provided_to_add_statements_to"> <source>No location provided to add statements to.</source> <target state="translated">No se ha proporcionado ubicación a la que agregar instrucciones.</target> <note /> </trans-unit> <trans-unit id="Destination_location_was_not_in_source"> <source>Destination location was not in source.</source> <target state="translated">La ubicación de destino no estaba en el código fuente.</target> <note /> </trans-unit> <trans-unit id="Destination_location_was_from_a_different_tree"> <source>Destination location was from a different tree.</source> <target state="translated">La ubicación de destino era de otro árbol.</target> <note /> </trans-unit> <trans-unit id="Node_is_of_the_wrong_type"> <source>Node is of the wrong type.</source> <target state="translated">El nodo es del tipo erróneo.</target> <note /> </trans-unit> <trans-unit id="Location_must_be_null_or_from_source"> <source>Location must be null or from source.</source> <target state="translated">La ubicación debe ser null o del código fuente.</target> <note /> </trans-unit> <trans-unit id="Duplicate_source_file_0_in_project_1"> <source>Duplicate source file '{0}' in project '{1}'</source> <target state="translated">Archivo de código fuente '{0}' duplicado en el proyecto '{1}'</target> <note /> </trans-unit> <trans-unit id="Removing_projects_is_not_supported"> <source>Removing projects is not supported.</source> <target state="translated">No se admite la eliminación de proyectos.</target> <note /> </trans-unit> <trans-unit id="Adding_projects_is_not_supported"> <source>Adding projects is not supported.</source> <target state="translated">No se admite la adición de proyectos.</target> <note /> </trans-unit> <trans-unit id="Symbols_project_could_not_be_found_in_the_provided_solution"> <source>Symbol's project could not be found in the provided solution</source> <target state="translated">No se pudo encontrar el proyecto del símbolo en la solución proporcionada.</target> <note /> </trans-unit> <trans-unit id="Sync_namespace_to_folder_structure"> <source>Sync namespace to folder structure</source> <target state="translated">Sincronizar espacio de nombres con estructura de carpetas</target> <note /> </trans-unit> <trans-unit id="The_contents_of_a_SourceGeneratedDocument_may_not_be_changed"> <source>The contents of a SourceGeneratedDocument may not be changed.</source> <target state="translated">No se puede cambiar el contenido de un elemento SourceGeneratedDocument.</target> <note>{locked:SourceGeneratedDocument}</note> </trans-unit> <trans-unit id="The_project_already_contains_the_specified_reference"> <source>The project already contains the specified reference.</source> <target state="translated">El proyecto ya contiene la referencia especificada.</target> <note /> </trans-unit> <trans-unit id="The_solution_already_contains_the_specified_reference"> <source>The solution already contains the specified reference.</source> <target state="translated">La solución ya contiene la referencia especificada.</target> <note /> </trans-unit> <trans-unit id="Unknown"> <source>Unknown</source> <target state="translated">Desconocido</target> <note /> </trans-unit> <trans-unit id="Visual_Basic_files"> <source>Visual Basic files</source> <target state="translated">Archivos de Visual Basic</target> <note /> </trans-unit> <trans-unit id="Warning_adding_imports_will_bring_an_extension_method_into_scope_with_the_same_name_as_member_access"> <source>Adding imports will bring an extension method into scope with the same name as '{0}'</source> <target state="translated">Al agregar importaciones, se incorporará un método de extensión en el ámbito con el mismo nombre que "{0}".</target> <note /> </trans-unit> <trans-unit id="Workspace_error"> <source>Workspace error</source> <target state="translated">Error del área de trabajo</target> <note /> </trans-unit> <trans-unit id="Workspace_is_not_empty"> <source>Workspace is not empty.</source> <target state="translated">El área de trabajo no está vacía.</target> <note /> </trans-unit> <trans-unit id="_0_is_in_a_different_project"> <source>{0} is in a different project.</source> <target state="translated">{0} está en un proyecto distinto.</target> <note /> </trans-unit> <trans-unit id="_0_is_not_part_of_the_workspace"> <source>'{0}' is not part of the workspace.</source> <target state="translated">'{0}' no es parte del área de trabajo.</target> <note /> </trans-unit> <trans-unit id="_0_is_already_part_of_the_workspace"> <source>'{0}' is already part of the workspace.</source> <target state="translated">'{0}' ya es parte del área de trabajo.</target> <note /> </trans-unit> <trans-unit id="_0_is_not_referenced"> <source>'{0}' is not referenced.</source> <target state="translated">'No hay referencia a '{0}'.</target> <note /> </trans-unit> <trans-unit id="_0_is_already_referenced"> <source>'{0}' is already referenced.</source> <target state="translated">'Ya hay una referencia a '{0}'.</target> <note /> </trans-unit> <trans-unit id="Adding_project_reference_from_0_to_1_will_cause_a_circular_reference"> <source>Adding project reference from '{0}' to '{1}' will cause a circular reference.</source> <target state="translated">La adición de una referencia de proyecto de '{0}' a '{1}' originará una referencia circular.</target> <note /> </trans-unit> <trans-unit id="Metadata_is_not_referenced"> <source>Metadata is not referenced.</source> <target state="translated">No hay referencia a los metadatos.</target> <note /> </trans-unit> <trans-unit id="Metadata_is_already_referenced"> <source>Metadata is already referenced.</source> <target state="translated">Ya hay una referencia a los metadatos.</target> <note /> </trans-unit> <trans-unit id="_0_is_not_present"> <source>{0} is not present.</source> <target state="translated">{0} no está presente.</target> <note /> </trans-unit> <trans-unit id="_0_is_already_present"> <source>{0} is already present.</source> <target state="translated">{0} ya está presente.</target> <note /> </trans-unit> <trans-unit id="The_specified_document_is_not_a_version_of_this_document"> <source>The specified document is not a version of this document.</source> <target state="translated">El documento especificado no es una versión de este documento.</target> <note /> </trans-unit> <trans-unit id="The_language_0_is_not_supported"> <source>The language '{0}' is not supported.</source> <target state="translated">El lenguaje '{0}' no es compatible.</target> <note /> </trans-unit> <trans-unit id="The_solution_already_contains_the_specified_project"> <source>The solution already contains the specified project.</source> <target state="translated">La solución ya contiene el proyecto especificado.</target> <note /> </trans-unit> <trans-unit id="The_solution_does_not_contain_the_specified_project"> <source>The solution does not contain the specified project.</source> <target state="translated">La solución no contiene el proyecto especificado.</target> <note /> </trans-unit> <trans-unit id="The_project_already_references_the_target_project"> <source>The project already references the target project.</source> <target state="translated">El proyecto ya hace referencia al proyecto de destino.</target> <note /> </trans-unit> <trans-unit id="The_solution_already_contains_the_specified_document"> <source>The solution already contains the specified document.</source> <target state="translated">La solución ya contiene el documento especificado.</target> <note /> </trans-unit> <trans-unit id="Temporary_storage_cannot_be_written_more_than_once"> <source>Temporary storage cannot be written more than once.</source> <target state="translated">No se puede escribir más de una vez en el almacenamiento temporal.</target> <note /> </trans-unit> <trans-unit id="_0_is_not_open"> <source>'{0}' is not open.</source> <target state="translated">'{0}' no está abierto.</target> <note /> </trans-unit> <trans-unit id="A_language_name_cannot_be_specified_for_this_option"> <source>A language name cannot be specified for this option.</source> <target state="translated">No se puede especificar un nombre de lenguaje para esta opción.</target> <note /> </trans-unit> <trans-unit id="A_language_name_must_be_specified_for_this_option"> <source>A language name must be specified for this option.</source> <target state="translated">Se debe especificar un nombre de lenguaje para esta opción.</target> <note /> </trans-unit> <trans-unit id="File_was_externally_modified_colon_0"> <source>File was externally modified: {0}.</source> <target state="translated">El archivo se modificó externamente: {0}.</target> <note /> </trans-unit> <trans-unit id="Unrecognized_language_name"> <source>Unrecognized language name.</source> <target state="translated">Nombre de lenguaje no reconocido.</target> <note /> </trans-unit> <trans-unit id="Can_t_resolve_metadata_reference_colon_0"> <source>Can't resolve metadata reference: '{0}'.</source> <target state="translated">No se puede resolver la referencia de metadatos: '{0}'.</target> <note /> </trans-unit> <trans-unit id="Can_t_resolve_analyzer_reference_colon_0"> <source>Can't resolve analyzer reference: '{0}'.</source> <target state="translated">No se puede resolver la referencia del analizador: '{0}'.</target> <note /> </trans-unit> <trans-unit id="Invalid_project_block_expected_after_Project"> <source>Invalid project block, expected "=" after Project.</source> <target state="translated">Bloque de proyecto no válido, se esperaba "=" después de Project.</target> <note /> </trans-unit> <trans-unit id="Invalid_project_block_expected_after_project_name"> <source>Invalid project block, expected "," after project name.</source> <target state="translated">Bloque de proyecto no válido, se esperaba "," después del nombre del proyecto.</target> <note /> </trans-unit> <trans-unit id="Invalid_project_block_expected_after_project_path"> <source>Invalid project block, expected "," after project path.</source> <target state="translated">Bloque de proyecto no válido, se esperaba "," después de la ruta de acceso del proyecto.</target> <note /> </trans-unit> <trans-unit id="Expected_0"> <source>Expected {0}.</source> <target state="translated">Se esperaba {0}.</target> <note /> </trans-unit> <trans-unit id="_0_must_be_a_non_null_and_non_empty_string"> <source>"{0}" must be a non-null and non-empty string.</source> <target state="translated">"{0}" debe ser una cadena que no sea Null ni esté vacía.</target> <note /> </trans-unit> <trans-unit id="Expected_header_colon_0"> <source>Expected header: "{0}".</source> <target state="translated">Se esperaba encabezado: "{0}".</target> <note /> </trans-unit> <trans-unit id="Expected_end_of_file"> <source>Expected end-of-file.</source> <target state="translated">Se esperaba fin de archivo.</target> <note /> </trans-unit> <trans-unit id="Expected_0_line"> <source>Expected {0} line.</source> <target state="translated">Se esperaba línea {0}.</target> <note /> </trans-unit> <trans-unit id="This_submission_already_references_another_submission_project"> <source>This submission already references another submission project.</source> <target state="translated">Este envío ya hace referencia a otro proyecto de envío.</target> <note /> </trans-unit> <trans-unit id="_0_still_contains_open_documents"> <source>{0} still contains open documents.</source> <target state="translated">{0} aún contiene documentos abiertos.</target> <note /> </trans-unit> <trans-unit id="_0_is_still_open"> <source>{0} is still open.</source> <target state="translated">{0} aún está abierto.</target> <note /> </trans-unit> <trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized"> <source>Arrays with more than one dimension cannot be serialized.</source> <target state="translated">Las matrices con más de una dimensión no se pueden serializar.</target> <note /> </trans-unit> <trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer"> <source>Value too large to be represented as a 30 bit unsigned integer.</source> <target state="translated">Valor demasiado largo para representarse como entero sin signo de 30 bits.</target> <note /> </trans-unit> <trans-unit id="Specified_path_must_be_absolute"> <source>Specified path must be absolute.</source> <target state="translated">La ruta de acceso especificada debe ser absoluta.</target> <note /> </trans-unit> <trans-unit id="Name_can_be_simplified"> <source>Name can be simplified.</source> <target state="translated">El nombre se puede simplificar.</target> <note /> </trans-unit> <trans-unit id="Unknown_identifier"> <source>Unknown identifier.</source> <target state="translated">Identificador desconocido.</target> <note /> </trans-unit> <trans-unit id="Cannot_generate_code_for_unsupported_operator_0"> <source>Cannot generate code for unsupported operator '{0}'</source> <target state="translated">No se puede generar código para el operador no compatible '{0}'</target> <note /> </trans-unit> <trans-unit id="Invalid_number_of_parameters_for_binary_operator"> <source>Invalid number of parameters for binary operator.</source> <target state="translated">Número de parámetros no válido para el operador binario.</target> <note /> </trans-unit> <trans-unit id="Invalid_number_of_parameters_for_unary_operator"> <source>Invalid number of parameters for unary operator.</source> <target state="translated">Número de parámetros no válido para el operador unario.</target> <note /> </trans-unit> <trans-unit id="Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language"> <source>Cannot open project '{0}' because the file extension '{1}' is not associated with a language.</source> <target state="translated">No se puede abrir el proyecto '{0}' porque la extensión de archivo '{1}' no está asociada a un lenguaje.</target> <note /> </trans-unit> <trans-unit id="Cannot_open_project_0_because_the_language_1_is_not_supported"> <source>Cannot open project '{0}' because the language '{1}' is not supported.</source> <target state="translated">No se puede abrir el proyecto '{0}' porque el lenguaje '{1}' no es compatible.</target> <note /> </trans-unit> <trans-unit id="Invalid_project_file_path_colon_0"> <source>Invalid project file path: '{0}'</source> <target state="translated">Ruta de acceso del archivo de proyecto no válida: '{0}'</target> <note /> </trans-unit> <trans-unit id="Invalid_solution_file_path_colon_0"> <source>Invalid solution file path: '{0}'</source> <target state="translated">Ruta de acceso del archivo de solución no válida: '{0}'</target> <note /> </trans-unit> <trans-unit id="Project_file_not_found_colon_0"> <source>Project file not found: '{0}'</source> <target state="translated">Archivo de proyecto no encontrado: '{0}'</target> <note /> </trans-unit> <trans-unit id="Solution_file_not_found_colon_0"> <source>Solution file not found: '{0}'</source> <target state="translated">Archivo de solución no encontrado: '{0}'</target> <note /> </trans-unit> <trans-unit id="Unmerged_change_from_project_0"> <source>Unmerged change from project '{0}'</source> <target state="translated">Cambio no fusionado mediante combinación del proyecto '{0}'</target> <note /> </trans-unit> <trans-unit id="Added_colon"> <source>Added:</source> <target state="translated">Agregado:</target> <note /> </trans-unit> <trans-unit id="After_colon"> <source>After:</source> <target state="translated">Después:</target> <note /> </trans-unit> <trans-unit id="Before_colon"> <source>Before:</source> <target state="translated">Antes:</target> <note /> </trans-unit> <trans-unit id="Removed_colon"> <source>Removed:</source> <target state="translated">Quitado:</target> <note /> </trans-unit> <trans-unit id="Invalid_CodePage_value_colon_0"> <source>Invalid CodePage value: {0}</source> <target state="translated">Valor de página de códigos no válido: {0}</target> <note /> </trans-unit> <trans-unit id="Adding_additional_documents_is_not_supported"> <source>Adding additional documents is not supported.</source> <target state="translated">No se permite agregar documentos adicionales.</target> <note /> </trans-unit> <trans-unit id="Adding_analyzer_references_is_not_supported"> <source>Adding analyzer references is not supported.</source> <target state="translated">No se permite agregar referencias de analizador.</target> <note /> </trans-unit> <trans-unit id="Adding_documents_is_not_supported"> <source>Adding documents is not supported.</source> <target state="translated">No se permite agregar documentos.</target> <note /> </trans-unit> <trans-unit id="Adding_metadata_references_is_not_supported"> <source>Adding metadata references is not supported.</source> <target state="translated">No se permite agregar referencias de metadatos.</target> <note /> </trans-unit> <trans-unit id="Adding_project_references_is_not_supported"> <source>Adding project references is not supported.</source> <target state="translated">No se permite agregar referencias de proyectos.</target> <note /> </trans-unit> <trans-unit id="Changing_additional_documents_is_not_supported"> <source>Changing additional documents is not supported.</source> <target state="translated">No se permite cambiar documentos adicionales.</target> <note /> </trans-unit> <trans-unit id="Changing_documents_is_not_supported"> <source>Changing documents is not supported.</source> <target state="translated">No se permite cambiar documentos.</target> <note /> </trans-unit> <trans-unit id="Changing_project_properties_is_not_supported"> <source>Changing project properties is not supported.</source> <target state="translated">No se permite cambiar propiedades de proyectos.</target> <note /> </trans-unit> <trans-unit id="Removing_additional_documents_is_not_supported"> <source>Removing additional documents is not supported.</source> <target state="translated">No se permite quitar documentos adicionales.</target> <note /> </trans-unit> <trans-unit id="Removing_analyzer_references_is_not_supported"> <source>Removing analyzer references is not supported.</source> <target state="translated">No se permite quitar referencias de analizador.</target> <note /> </trans-unit> <trans-unit id="Removing_documents_is_not_supported"> <source>Removing documents is not supported.</source> <target state="translated">No se permite quitar documentos.</target> <note /> </trans-unit> <trans-unit id="Removing_metadata_references_is_not_supported"> <source>Removing metadata references is not supported.</source> <target state="translated">No se permite quitar referencias de metadatos.</target> <note /> </trans-unit> <trans-unit id="Removing_project_references_is_not_supported"> <source>Removing project references is not supported.</source> <target state="translated">No se permite quitar referencias de proyectos.</target> <note /> </trans-unit> <trans-unit id="Service_of_type_0_is_required_to_accomplish_the_task_but_is_not_available_from_the_workspace"> <source>Service of type '{0}' is required to accomplish the task but is not available from the workspace.</source> <target state="translated">El servicio de tipo '{0}' es necesario para realizar la tarea, pero no está disponibles desde el área de trabajo.</target> <note /> </trans-unit> <trans-unit id="At_least_one_diagnostic_must_be_supplied"> <source>At least one diagnostic must be supplied.</source> <target state="translated">Se debe suministrar al menos un diagnóstico.</target> <note /> </trans-unit> <trans-unit id="Diagnostic_must_have_span_0"> <source>Diagnostic must have span '{0}'</source> <target state="translated">El diagnóstico debe tener el intervalo '{0}'</target> <note /> </trans-unit> <trans-unit id="Cannot_deserialize_type_0"> <source>Cannot deserialize type '{0}'.</source> <target state="translated">No se puede deserializar el tipo "{0}".</target> <note /> </trans-unit> <trans-unit id="Cannot_serialize_type_0"> <source>Cannot serialize type '{0}'.</source> <target state="translated">No se puede serializar el tipo "{0}".</target> <note /> </trans-unit> <trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder"> <source>The type '{0}' is not understood by the serialization binder.</source> <target state="translated">El enlazador de serialización no comprende el tipo "{0}".</target> <note /> </trans-unit> <trans-unit id="Label_for_node_0_is_invalid_it_must_be_within_bracket_0_1"> <source>Label for node '{0}' is invalid, it must be within [0, {1}).</source> <target state="translated">La etiqueta para el nodo "{0}" no es válida; debe estar dentro del intervalo [0, {1}).</target> <note /> </trans-unit> <trans-unit id="Matching_nodes_0_and_1_must_have_the_same_label"> <source>Matching nodes '{0}' and '{1}' must have the same label.</source> <target state="translated">Los nodos coincidentes "{0}" y "{1}" deben tener la misma etiqueta.</target> <note /> </trans-unit> <trans-unit id="Node_0_must_be_contained_in_the_new_tree"> <source>Node '{0}' must be contained in the new tree.</source> <target state="translated">El nodo "{0}" debe incluirse en el árbol nuevo.</target> <note /> </trans-unit> <trans-unit id="Node_0_must_be_contained_in_the_old_tree"> <source>Node '{0}' must be contained in the old tree.</source> <target state="translated">El nodo "{0}" debe incluirse en el árbol antiguo.</target> <note /> </trans-unit> <trans-unit id="The_member_0_is_not_declared_within_the_declaration_of_the_symbol"> <source>The member '{0}' is not declared within the declaration of the symbol.</source> <target state="translated">No se ha declarado el miembro '{0}' dentro de la declaración del símbolo.</target> <note /> </trans-unit> <trans-unit id="The_position_is_not_within_the_symbol_s_declaration"> <source>The position is not within the symbol's declaration</source> <target state="translated">La posición no se encuentra dentro de la declaración del símbolo</target> <note /> </trans-unit> <trans-unit id="The_symbol_0_cannot_be_located_within_the_current_solution"> <source>The symbol '{0}' cannot be located within the current solution.</source> <target state="translated">El símbolo '{0}' no puede estar dentro de la solución actual.</target> <note /> </trans-unit> <trans-unit id="Changing_compilation_options_is_not_supported"> <source>Changing compilation options is not supported.</source> <target state="translated">No se admite el cambio de las opciones de compilación.</target> <note /> </trans-unit> <trans-unit id="Changing_parse_options_is_not_supported"> <source>Changing parse options is not supported.</source> <target state="translated">No se admite el cambio de las opciones de análisis.</target> <note /> </trans-unit> <trans-unit id="The_node_is_not_part_of_the_tree"> <source>The node is not part of the tree.</source> <target state="translated">El nodo no forma parte del árbol.</target> <note /> </trans-unit> <trans-unit id="This_workspace_does_not_support_opening_and_closing_documents"> <source>This workspace does not support opening and closing documents.</source> <target state="translated">Esta área de trabajo no admite la apertura y el cierre de documentos.</target> <note /> </trans-unit> <trans-unit id="Exceptions_colon"> <source>Exceptions:</source> <target state="translated">Excepciones:</target> <note /> </trans-unit> <trans-unit id="_0_returned_an_uninitialized_ImmutableArray"> <source>'{0}' returned an uninitialized ImmutableArray</source> <target state="translated">'{0}' devolvió una ImmutableArray sin inicializar</target> <note /> </trans-unit> <trans-unit id="Failure"> <source>Failure</source> <target state="translated">Error</target> <note /> </trans-unit> <trans-unit id="Warning"> <source>Warning</source> <target state="translated">Advertencia</target> <note /> </trans-unit> <trans-unit id="Enable"> <source>Enable</source> <target state="translated">Habilitar</target> <note /> </trans-unit> <trans-unit id="Enable_and_ignore_future_errors"> <source>Enable and ignore future errors</source> <target state="translated">Habilitar y omitir futuros errores</target> <note /> </trans-unit> <trans-unit id="_0_encountered_an_error_and_has_been_disabled"> <source>'{0}' encountered an error and has been disabled.</source> <target state="translated">'{0}' detectó un error y se ha deshabilitado.</target> <note /> </trans-unit> <trans-unit id="Show_Stack_Trace"> <source>Show Stack Trace</source> <target state="translated">Mostrar seguimiento de la pila</target> <note /> </trans-unit> <trans-unit id="Stream_is_too_long"> <source>Stream is too long.</source> <target state="translated">Secuencia demasiado larga.</target> <note /> </trans-unit> <trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values"> <source>Deserialization reader for '{0}' read incorrect number of values.</source> <target state="translated">El lector de deserialización de "{0}" leyó un número incorrecto de valores.</target> <note /> </trans-unit> <trans-unit id="Async_Method"> <source>Async Method</source> <target state="translated">Metodo asincrónico</target> <note>{locked: async}{locked: method} These are keywords (unless the order of words or capitalization should be handled differently)</note> </trans-unit> <trans-unit id="Error"> <source>Error</source> <target state="translated">Fehler</target> <note /> </trans-unit> <trans-unit id="None"> <source>None</source> <target state="translated">NONE</target> <note /> </trans-unit> <trans-unit id="Suggestion"> <source>Suggestion</source> <target state="translated">Sugerencia</target> <note /> </trans-unit> <trans-unit id="File_0_size_of_1_exceeds_maximum_allowed_size_of_2"> <source>File '{0}' size of {1} exceeds maximum allowed size of {2}</source> <target state="translated">El archivo "{0}" con un tamaño de {1} supera el tamaño máximo permitido de {2}</target> <note /> </trans-unit> <trans-unit id="Changing_document_property_is_not_supported"> <source>Changing document properties is not supported</source> <target state="translated">No se admite el cambio de propiedades de documentos</target> <note /> </trans-unit> <trans-unit id="dot_NET_Coding_Conventions"> <source>.NET Coding Conventions</source> <target state="translated">Convenciones de codificación .NET</target> <note /> </trans-unit> <trans-unit id="Variables_captured_colon"> <source>Variables captured:</source> <target state="translated">Variables capturadas:</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/VisualBasic/Portable/Lowering/LambdaRewriter/LambdaFrame.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A class that represents the set of variables in a scope that have been ''' captured by lambdas within that scope. ''' </summary> Friend NotInheritable Class LambdaFrame Inherits SynthesizedContainer Implements ISynthesizedMethodBodyImplementationSymbol Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol) Private ReadOnly _topLevelMethod As MethodSymbol Private ReadOnly _sharedConstructor As MethodSymbol Private ReadOnly _singletonCache As FieldSymbol Friend ReadOnly ClosureOrdinal As Integer 'NOTE: this does not include captured parent frame references Friend ReadOnly CapturedLocals As New ArrayBuilder(Of LambdaCapturedVariable) Private ReadOnly _constructor As SynthesizedLambdaConstructor Friend ReadOnly TypeMap As TypeSubstitution Private ReadOnly _scopeSyntaxOpt As SyntaxNode Private Shared ReadOnly s_typeSubstitutionFactory As Func(Of Symbol, TypeSubstitution) = Function(container) Dim f = TryCast(container, LambdaFrame) Return If(f IsNot Nothing, f.TypeMap, DirectCast(container, SynthesizedMethod).TypeMap) End Function Friend Shared ReadOnly CreateTypeParameter As Func(Of TypeParameterSymbol, Symbol, TypeParameterSymbol) = Function(typeParameter, container) New SynthesizedClonedTypeParameterSymbol(typeParameter, container, GeneratedNames.MakeDisplayClassGenericParameterName(typeParameter.Ordinal), s_typeSubstitutionFactory) Friend Sub New(topLevelMethod As MethodSymbol, scopeSyntaxOpt As SyntaxNode, methodId As DebugId, closureId As DebugId, copyConstructor As Boolean, isStatic As Boolean, isDelegateRelaxationFrame As Boolean) MyBase.New(topLevelMethod, MakeName(scopeSyntaxOpt, methodId, closureId, isStatic, isDelegateRelaxationFrame), topLevelMethod.ContainingType, ImmutableArray(Of NamedTypeSymbol).Empty) If copyConstructor Then Me._constructor = New SynthesizedLambdaCopyConstructor(scopeSyntaxOpt, Me) Else Me._constructor = New SynthesizedLambdaConstructor(scopeSyntaxOpt, Me) End If ' static lambdas technically have the class scope so the scope syntax is Nothing If isStatic Then Me._sharedConstructor = New SynthesizedConstructorSymbol(Nothing, Me, isShared:=True, isDebuggable:=False, binder:=Nothing, diagnostics:=Nothing) Dim cacheVariableName = GeneratedNames.MakeCachedFrameInstanceName() Me._singletonCache = New SynthesizedLambdaCacheFieldSymbol(Me, Me, Me, cacheVariableName, topLevelMethod, Accessibility.Public, isReadOnly:=True, isShared:=True) _scopeSyntaxOpt = Nothing Else _scopeSyntaxOpt = scopeSyntaxOpt End If If Not isDelegateRelaxationFrame Then AssertIsClosureScopeSyntax(_scopeSyntaxOpt) End If Me._typeParameters = SynthesizedClonedTypeParameterSymbol.MakeTypeParameters(topLevelMethod.TypeParameters, Me, CreateTypeParameter) Me.TypeMap = TypeSubstitution.Create(topLevelMethod, topLevelMethod.TypeParameters, Me.TypeArgumentsNoUseSiteDiagnostics) Me._topLevelMethod = topLevelMethod End Sub Private Shared Function MakeName(scopeSyntaxOpt As SyntaxNode, methodId As DebugId, closureId As DebugId, isStatic As Boolean, isDelegateRelaxation As Boolean) As String If isStatic Then ' Display class is shared among static non-generic lambdas across generations, method ordinal is -1 in that case. ' A new display class of a static generic lambda is created for each method and each generation. Return GeneratedNames.MakeStaticLambdaDisplayClassName(methodId.Ordinal, methodId.Generation) End If Debug.Assert(methodId.Ordinal >= 0) Return GeneratedNames.MakeLambdaDisplayClassName(methodId.Ordinal, methodId.Generation, closureId.Ordinal, closureId.Generation, isDelegateRelaxation) End Function <Conditional("DEBUG")> Private Shared Sub AssertIsClosureScopeSyntax(syntaxOpt As SyntaxNode) ' static lambdas technically have the class scope so the scope syntax is nothing If syntaxOpt Is Nothing Then Return End If If LambdaUtilities.IsClosureScope(syntaxOpt) Then Return End If Select Case syntaxOpt.Kind() Case SyntaxKind.ObjectMemberInitializer ' TODO: Closure capturing a synthesized "with" variable Return End Select ExceptionUtilities.UnexpectedValue(syntaxOpt.Kind()) End Sub Public ReadOnly Property ScopeSyntax As SyntaxNode Get Return _constructor.Syntax End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get ' Dev11 uses "assembly" here. No need to be different. Return Accessibility.Friend End Get End Property Public Overloads Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol) Return ImmutableArray(Of Symbol).Empty End Function Public Overloads Overrides Function GetMembers() As ImmutableArray(Of Symbol) Dim members = StaticCast(Of Symbol).From(CapturedLocals.AsImmutable()) If _sharedConstructor IsNot Nothing Then members = members.AddRange(ImmutableArray.Create(Of Symbol)(_constructor, _sharedConstructor, _singletonCache)) Else members = members.Add(_constructor) End If Return members End Function Protected Friend Overrides ReadOnly Property Constructor As MethodSymbol Get Return _constructor End Get End Property Protected Friend ReadOnly Property SharedConstructor As MethodSymbol Get Return _sharedConstructor End Get End Property Friend ReadOnly Property SingletonCache As FieldSymbol Get Return _singletonCache End Get End Property Public Overrides ReadOnly Property IsSerializable As Boolean Get Return _singletonCache IsNot Nothing End Get End Property Friend Overrides Function GetFieldsToEmit() As IEnumerable(Of FieldSymbol) If _singletonCache Is Nothing Then Return CapturedLocals Else Return DirectCast(CapturedLocals, IEnumerable(Of FieldSymbol)).Concat(Me._singletonCache) End If End Function Friend Overrides Function MakeAcyclicBaseType(diagnostics As BindingDiagnosticBag) As NamedTypeSymbol Dim type = ContainingAssembly.GetSpecialType(SpecialType.System_Object) ' WARN: We assume that if System_Object was not found we would never reach ' this point because the error should have been/processed generated earlier Debug.Assert(type.GetUseSiteInfo().DiagnosticInfo Is Nothing) Return type End Function Friend Overrides Function MakeAcyclicInterfaces(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Friend Overrides Function MakeDeclaredBase(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As NamedTypeSymbol Dim type = ContainingAssembly.GetSpecialType(SpecialType.System_Object) ' WARN: We assume that if System_Object was not found we would never reach ' this point because the error should have been/processed generated earlier Debug.Assert(type.GetUseSiteInfo().DiagnosticInfo Is Nothing) Return type End Function Friend Overrides Function MakeDeclaredInterfaces(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overrides ReadOnly Property MemberNames As IEnumerable(Of String) Get Return SpecializedCollections.EmptyEnumerable(Of String)() End Get End Property Public Overrides ReadOnly Property TypeKind As TypeKind Get Return TypeKind.Class End Get End Property Public Overrides ReadOnly Property Arity As Integer Get Return Me._typeParameters.Length End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return Me._typeParameters End Get End Property Friend Overrides ReadOnly Property IsInterface As Boolean Get Return False End Get End Property Public ReadOnly Property HasMethodBodyDependency As Boolean Implements ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency Get ' This method contains user code from the lambda. Return True End Get End Property Public ReadOnly Property Method As IMethodSymbolInternal Implements ISynthesizedMethodBodyImplementationSymbol.Method Get Return _topLevelMethod End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A class that represents the set of variables in a scope that have been ''' captured by lambdas within that scope. ''' </summary> Friend NotInheritable Class LambdaFrame Inherits SynthesizedContainer Implements ISynthesizedMethodBodyImplementationSymbol Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol) Private ReadOnly _topLevelMethod As MethodSymbol Private ReadOnly _sharedConstructor As MethodSymbol Private ReadOnly _singletonCache As FieldSymbol Friend ReadOnly ClosureOrdinal As Integer 'NOTE: this does not include captured parent frame references Friend ReadOnly CapturedLocals As New ArrayBuilder(Of LambdaCapturedVariable) Private ReadOnly _constructor As SynthesizedLambdaConstructor Friend ReadOnly TypeMap As TypeSubstitution Private ReadOnly _scopeSyntaxOpt As SyntaxNode Private Shared ReadOnly s_typeSubstitutionFactory As Func(Of Symbol, TypeSubstitution) = Function(container) Dim f = TryCast(container, LambdaFrame) Return If(f IsNot Nothing, f.TypeMap, DirectCast(container, SynthesizedMethod).TypeMap) End Function Friend Shared ReadOnly CreateTypeParameter As Func(Of TypeParameterSymbol, Symbol, TypeParameterSymbol) = Function(typeParameter, container) New SynthesizedClonedTypeParameterSymbol(typeParameter, container, GeneratedNames.MakeDisplayClassGenericParameterName(typeParameter.Ordinal), s_typeSubstitutionFactory) Friend Sub New(topLevelMethod As MethodSymbol, scopeSyntaxOpt As SyntaxNode, methodId As DebugId, closureId As DebugId, copyConstructor As Boolean, isStatic As Boolean, isDelegateRelaxationFrame As Boolean) MyBase.New(topLevelMethod, MakeName(scopeSyntaxOpt, methodId, closureId, isStatic, isDelegateRelaxationFrame), topLevelMethod.ContainingType, ImmutableArray(Of NamedTypeSymbol).Empty) If copyConstructor Then Me._constructor = New SynthesizedLambdaCopyConstructor(scopeSyntaxOpt, Me) Else Me._constructor = New SynthesizedLambdaConstructor(scopeSyntaxOpt, Me) End If ' static lambdas technically have the class scope so the scope syntax is Nothing If isStatic Then Me._sharedConstructor = New SynthesizedConstructorSymbol(Nothing, Me, isShared:=True, isDebuggable:=False, binder:=Nothing, diagnostics:=Nothing) Dim cacheVariableName = GeneratedNames.MakeCachedFrameInstanceName() Me._singletonCache = New SynthesizedLambdaCacheFieldSymbol(Me, Me, Me, cacheVariableName, topLevelMethod, Accessibility.Public, isReadOnly:=True, isShared:=True) _scopeSyntaxOpt = Nothing Else _scopeSyntaxOpt = scopeSyntaxOpt End If If Not isDelegateRelaxationFrame Then AssertIsClosureScopeSyntax(_scopeSyntaxOpt) End If Me._typeParameters = SynthesizedClonedTypeParameterSymbol.MakeTypeParameters(topLevelMethod.TypeParameters, Me, CreateTypeParameter) Me.TypeMap = TypeSubstitution.Create(topLevelMethod, topLevelMethod.TypeParameters, Me.TypeArgumentsNoUseSiteDiagnostics) Me._topLevelMethod = topLevelMethod End Sub Private Shared Function MakeName(scopeSyntaxOpt As SyntaxNode, methodId As DebugId, closureId As DebugId, isStatic As Boolean, isDelegateRelaxation As Boolean) As String If isStatic Then ' Display class is shared among static non-generic lambdas across generations, method ordinal is -1 in that case. ' A new display class of a static generic lambda is created for each method and each generation. Return GeneratedNames.MakeStaticLambdaDisplayClassName(methodId.Ordinal, methodId.Generation) End If Debug.Assert(methodId.Ordinal >= 0) Return GeneratedNames.MakeLambdaDisplayClassName(methodId.Ordinal, methodId.Generation, closureId.Ordinal, closureId.Generation, isDelegateRelaxation) End Function <Conditional("DEBUG")> Private Shared Sub AssertIsClosureScopeSyntax(syntaxOpt As SyntaxNode) ' static lambdas technically have the class scope so the scope syntax is nothing If syntaxOpt Is Nothing Then Return End If If LambdaUtilities.IsClosureScope(syntaxOpt) Then Return End If Select Case syntaxOpt.Kind() Case SyntaxKind.ObjectMemberInitializer ' TODO: Closure capturing a synthesized "with" variable Return End Select ExceptionUtilities.UnexpectedValue(syntaxOpt.Kind()) End Sub Public ReadOnly Property ScopeSyntax As SyntaxNode Get Return _constructor.Syntax End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get ' Dev11 uses "assembly" here. No need to be different. Return Accessibility.Friend End Get End Property Public Overloads Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol) Return ImmutableArray(Of Symbol).Empty End Function Public Overloads Overrides Function GetMembers() As ImmutableArray(Of Symbol) Dim members = StaticCast(Of Symbol).From(CapturedLocals.AsImmutable()) If _sharedConstructor IsNot Nothing Then members = members.AddRange(ImmutableArray.Create(Of Symbol)(_constructor, _sharedConstructor, _singletonCache)) Else members = members.Add(_constructor) End If Return members End Function Protected Friend Overrides ReadOnly Property Constructor As MethodSymbol Get Return _constructor End Get End Property Protected Friend ReadOnly Property SharedConstructor As MethodSymbol Get Return _sharedConstructor End Get End Property Friend ReadOnly Property SingletonCache As FieldSymbol Get Return _singletonCache End Get End Property Public Overrides ReadOnly Property IsSerializable As Boolean Get Return _singletonCache IsNot Nothing End Get End Property Friend Overrides Function GetFieldsToEmit() As IEnumerable(Of FieldSymbol) If _singletonCache Is Nothing Then Return CapturedLocals Else Return DirectCast(CapturedLocals, IEnumerable(Of FieldSymbol)).Concat(Me._singletonCache) End If End Function Friend Overrides Function MakeAcyclicBaseType(diagnostics As BindingDiagnosticBag) As NamedTypeSymbol Dim type = ContainingAssembly.GetSpecialType(SpecialType.System_Object) ' WARN: We assume that if System_Object was not found we would never reach ' this point because the error should have been/processed generated earlier Debug.Assert(type.GetUseSiteInfo().DiagnosticInfo Is Nothing) Return type End Function Friend Overrides Function MakeAcyclicInterfaces(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Friend Overrides Function MakeDeclaredBase(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As NamedTypeSymbol Dim type = ContainingAssembly.GetSpecialType(SpecialType.System_Object) ' WARN: We assume that if System_Object was not found we would never reach ' this point because the error should have been/processed generated earlier Debug.Assert(type.GetUseSiteInfo().DiagnosticInfo Is Nothing) Return type End Function Friend Overrides Function MakeDeclaredInterfaces(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overrides ReadOnly Property MemberNames As IEnumerable(Of String) Get Return SpecializedCollections.EmptyEnumerable(Of String)() End Get End Property Public Overrides ReadOnly Property TypeKind As TypeKind Get Return TypeKind.Class End Get End Property Public Overrides ReadOnly Property Arity As Integer Get Return Me._typeParameters.Length End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return Me._typeParameters End Get End Property Friend Overrides ReadOnly Property IsInterface As Boolean Get Return False End Get End Property Public ReadOnly Property HasMethodBodyDependency As Boolean Implements ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency Get ' This method contains user code from the lambda. Return True End Get End Property Public ReadOnly Property Method As IMethodSymbolInternal Implements ISynthesizedMethodBodyImplementationSymbol.Method Get Return _topLevelMethod End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ContextQuery/CSharpSyntaxContextService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery { [ExportLanguageService(typeof(ISyntaxContextService), LanguageNames.CSharp), Shared] internal class CSharpSyntaxContextService : ISyntaxContextService { [ImportingConstructor] [System.Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSyntaxContextService() { } public SyntaxContext CreateContext(Workspace workspace, SemanticModel semanticModel, int position, CancellationToken cancellationToken) => CSharpSyntaxContext.CreateContext(workspace, semanticModel, position, 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.Composition; using System.Threading; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery { [ExportLanguageService(typeof(ISyntaxContextService), LanguageNames.CSharp), Shared] internal class CSharpSyntaxContextService : ISyntaxContextService { [ImportingConstructor] [System.Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSyntaxContextService() { } public SyntaxContext CreateContext(Workspace workspace, SemanticModel semanticModel, int position, CancellationToken cancellationToken) => CSharpSyntaxContext.CreateContext(workspace, semanticModel, position, cancellationToken); } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/VisualBasic/Test/Syntax/IncrementalParser/IncrementalParser.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.ObjectModel Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Public Class IncrementalParser Private ReadOnly _s As String = <![CDATA[ '----------------------- ' ' Copyright (c) ' '----------------------- #const BLAH = true Imports Roslyn.Compilers Imports Roslyn.Compilers.Common Imports Roslyn.Compilers.VisualBasic Public Module ParseExprSemantics Dim text = SourceText.From("") Dim tree As SyntaxTree = Nothing #const x = 1 ''' <summary> ''' This is just gibberish to test parser ''' </summary> ''' <param name="ITERS"> haha </param> ''' <remarks></remarks> Public Sub Run(ByVal ITERS As Long) Console.WriteLine() #if BLAH Console.WriteLine("==== Parsing file: " & "Sample_ExpressionSemantics.vb") Console.WriteLine("Iterations:" & ITERS) #end if Dim str = IO.File.ReadAllText("Sample_ExpressionSemantics.vb") Dim lineNumber = 28335 Dim root As SyntaxNode = Nothing dim s1 = sub () If True Then Console.WriteLine(1) : dim s2 = sub () If True Then Console.WriteLine(1) ::Console.WriteLine(1):: dim s3 = sub() If True Then Console.WriteLine(1) :::: Console.WriteLine(1) Dim sw = System.Diagnostics.Stopwatch.StartNew() For i As Integer = 0 To ITERS - 1 tree = SyntaxTree.Parse(text, Nothing) root = tree.Root Console.Write(".") Dim highWater As Integer = Math.Max(highWater, System.GC.GetTotalMemory(False)) Next Dim grouped = From node In root.GetNodesWhile(root.FullSpan, Function() True) Group By node.Kind Into Group, Count() Order By Count Descending Take 30 Console.WriteLine("Quick token cache-hits: {0} ({1:G2}%)", Stats.quickReturnedToken, 100.0 * Stats.quickReturnedToken / Stats.quickAttempts) End Sub End Module]]>.Value <Fact> Public Sub FakeEdits() Dim text As SourceText = SourceText.From(_s) Dim tree As SyntaxTree = Nothing Dim root As SyntaxNode = Nothing tree = VisualBasicSyntaxTree.ParseText(text) root = tree.GetRoot() Assert.Equal(False, root.ContainsDiagnostics) For i As Integer = 0 To text.Length - 11 Dim span = New TextSpan(i, 10) text = text.WithChanges(New TextChange(span, text.ToString(span))) tree = tree.WithChangedText(text) Dim prevRoot = root root = tree.GetRoot() Assert.True(prevRoot.IsEquivalentTo(root)) Next End Sub <Fact> Public Sub TypeAFile() Dim text As SourceText = SourceText.From("") Dim tree As SyntaxTree = Nothing tree = VisualBasicSyntaxTree.ParseText(text) Assert.Equal(False, tree.GetRoot().ContainsDiagnostics) For i As Integer = 0 To _s.Length - 1 ' add next character in file 's' to text Dim newText = text.WithChanges(New TextChange(New TextSpan(text.Length, 0), _s.Substring(i, 1))) Dim newTree = tree.WithChangedText(newText) Dim tmpTree = VisualBasicSyntaxTree.ParseText(newText) VerifyEquivalent(newTree, tmpTree) text = newText tree = newTree Next End Sub <Fact> Public Sub Preprocessor() Dim oldText = SourceText.From(_s) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' commenting out the #const Dim pos = _s.IndexOf("#const", StringComparison.Ordinal) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(pos, 0), "'")) Dim newTree = oldTree.WithChangedText(newText) Dim tmpTree = VisualBasicSyntaxTree.ParseText(newText) VerifyEquivalent(newTree, tmpTree) ' removes ' from the '#const Dim newString = newText.ToString() pos = newString.IndexOf("'#const", StringComparison.Ordinal) Dim anotherText = newText.WithChanges(New TextChange(New TextSpan(pos, 1), "")) newTree = newTree.WithChangedText(anotherText) tmpTree = VisualBasicSyntaxTree.ParseText(anotherText) VerifyEquivalent(newTree, tmpTree) End Sub #Region "Regressions" <WorkItem(899264, "DevDiv/Personal")> <Fact> Public Sub IncParseWithEventsFollowingProperty() 'Unable to verify this using CDATA, since CDATA value only has Cr appended at end of each line, 'where as this bug is reproducible only with CrLf at the end of each line Dim code As String = "Public Class HasPublicMembersToConflictWith" & vbCrLf & "Public ConflictWithProp" & vbCrLf & "" & vbCrLf & "Public Property _ConflictWithBF() As String" & vbCrLf & " Get" & vbCrLf & " End Get" & vbCrLf & " Set(value As String)" & vbCrLf & " End Set" & vbCrLf & "End Property" & vbCrLf & "" & vbCrLf & "Public WithEvents ConflictWithBoth As Ob" ParseAndVerify(code, <errors> <error id="30481"/> </errors>) IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "j", .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(899596, "DevDiv/Personal")> <Fact> Public Sub IncParseClassFollowingDocComments() Dim code As String = <![CDATA[Class VBQATestcase '''----------------------------------------------------------------------------- ''' <summary> '''Text ''' </summary> '''-----------------------------------------------------------------------------]]>.Value ParseAndVerify(code, <errors> <error id="30481"/> </errors>) IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf & "Pub", .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(899918, "DevDiv/Personal")> <Fact> Public Sub IncParseDirInElse() Dim code As String = "Sub Sub1()" & vbCr & "If true Then" & vbCr & "goo("""")" & vbCr & "Else" & vbCr & vbCr & "#If Not ULTRAVIOLET Then" & vbCr ParseAndVerify(code, <errors> <error id="30012"/> <error id="30081"/> <error id="30026"/> </errors>) IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "a", .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(899938, "DevDiv/Personal")> <Fact> Public Sub IncParseNamespaceFollowingEvent() Dim code As String = "Class cls1" & vbCrLf & "Custom Event myevent As del" & vbCrLf & "End Event" & vbCrLf & "End Class" & vbCrLf & "Namespace r" IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "e", .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(900209, "DevDiv/Personal")> <Fact> Public Sub IncParseCaseElse() Dim code As String = (<![CDATA[ Sub main() Select Case 5 Case Else vvv = 6 Case Else vvv = 7 ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(901386, "DevDiv/Personal")> <Fact> Public Sub IncParseExplicitOnGroupBy() Dim code As String = (<![CDATA[ Option Explicit On Sub goo() Dim q2 = From x In col let y = x Group x, y By]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "a", .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(901639, "DevDiv/Personal")> <Fact> Public Sub IncParseExprLambdaInSubContext() Dim code As String = (<![CDATA[Function() NewTextPI.UnwrapObject().FileCodeModel) If True Then End If End Sub Class WillHaveAnError End class Class willBeReused End class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "(", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <Fact> Public Sub IncParseExprLambdaInSubContext2() Dim code As String = (<![CDATA[Function() NewTextPI.UnwrapObject().FileCodeModel) If True Then Else End If End Sub Class WillHaveAnError End class Class willBeReused End class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "(", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(901645, "DevDiv/Personal")> <Fact> Public Sub IncParseExitFunction() Dim code As String = (<![CDATA[Function If strSwitches <> "" Then strCLine = strCLine & " " & strSwitches End Sub]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Exit ", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(901655, "DevDiv/Personal")> <Fact> Public Sub IncParseDateLiteral() IncParseAndVerify(New IncParseNode With { .oldText = "", .changeText = "#10/18/1969# hello 123", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <Fact> Public Sub IncParsePPElse() Dim code As String = (<![CDATA[ Function goo() As Boolean #Else Dim roleName As Object For Each roleName In wbirFields Next roleName End Function ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "#End If", .changeSpan = New TextSpan(code.IndexOf("Next roleName", StringComparison.Ordinal) + 15, 2), .changeType = ChangeType.Replace}) End Sub <Fact> Public Sub IncParsePPElse1() Dim code As String = (<![CDATA[ Function goo() As Boolean #Else Dim roleName As Object For Each roleName In wbirFields Next roleName #End IF End Function ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "#If true " & vbCrLf, .changeSpan = New TextSpan(code.IndexOf("#Else", StringComparison.Ordinal), 0), .changeType = ChangeType.Replace}) End Sub <WorkItem(901669, "DevDiv/Personal")> <Fact> Public Sub ParseXmlTagWithExprHole() Dim code As String = (<![CDATA[e a=<%= b %>>]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "<", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(901671, "DevDiv/Personal")> <Fact> Public Sub IncParseEndBeforeSubWithX() Dim code As String = (<![CDATA[Sub End Class X]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "End ", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(901676, "DevDiv/Personal")> <Fact> Public Sub IncParseInterfaceFollByConstructs() Dim code As String = (<![CDATA[ Public Interface I2 End Interface Sub SEHIllegal501() Try Catch End Try Exit Sub End Sub X]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Interface", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(901680, "DevDiv/Personal")> <Fact> Public Sub IncParseLCFunctionCompoundAsn() Dim code As String = (<![CDATA[Public Function goo() As String For i As Integer = 0 To 1 total += y(i) Next End Function]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "> _" & vbCrLf, .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(902710, "DevDiv/Personal")> <Fact> Public Sub IncParseInsertFunctionBeforeEndClass() Dim code As String = (<![CDATA[End Class MustInherit Class C10 End Class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Function" & vbCrLf, .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(903134, "DevDiv/Personal")> <Fact> Public Sub InsertSubBeforeCustomEvent() Dim code As String = (<![CDATA[ Custom Event e As del AddHandler(ByVal value As del) End AddHandler End Event]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Sub" & vbCrLf, .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(903555, "DevDiv/Personal")> <Fact> Public Sub ParseMergedForEachAndDecl() Dim code As String = (<![CDATA[#Region "abc" Function goo() As Boolean Dim roleName As Object For Each roleName In wbirFields Next roleName End Function #End Region]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(code.IndexOf("Dim roleName As Object", StringComparison.Ordinal) + 22, 2), .changeType = ChangeType.Remove}) End Sub <WorkItem(903805, "DevDiv/Personal")> <Fact> Public Sub ParseEnumWithoutEnd() Dim code As String = (<![CDATA[Public Class Class2 Protected Enum e e1 e2 End Enum Public Function Goo(ByVal arg1 As e) As e End Function End Class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(code.IndexOf("e2", StringComparison.Ordinal) + 2, 2), .changeType = ChangeType.Remove}) End Sub <WorkItem(903826, "DevDiv/Personal")> <Fact> Public Sub IncParseWrongSelectFollByIf() Dim code As String = (<![CDATA[ Sub goo() Select Case lng Case 44 int1 = 4 End Select If true Then End If End Sub]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "End ", .changeSpan = New TextSpan(code.IndexOf("End ", StringComparison.Ordinal), 4), .changeType = ChangeType.Remove}) End Sub <WorkItem(904768, "DevDiv/Personal")> <Fact> Public Sub IncParseDoLoop() Dim code As String = (<![CDATA[ Sub AnonTConStmnt() Do i += 1 Loop Until true End Sub ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(code.IndexOf("Do", StringComparison.Ordinal) + 2, 2), .changeType = ChangeType.Remove}) End Sub <WorkItem(904771, "DevDiv/Personal")> <Fact> Public Sub IncParseClassWithOpDecl() Dim code As String = (<![CDATA[ Friend Module m1 Class Class1 Shared Operator -(ByVal x As Class1) As Boolean End Operator End Class End Module ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Class ", .changeSpan = New TextSpan(code.IndexOf("Class ", StringComparison.Ordinal), 6), .changeType = ChangeType.Remove}) End Sub <WorkItem(904782, "DevDiv/Personal")> <Fact> Public Sub IncParsePropFollIncompleteLambda() Dim code As String = (<![CDATA[ Class c1 Public Function goo() As Object Dim res = Function(x As Integer) c1.Goo(x) End Function Default Public Property Prop(ByVal y As String) As Integer Get End Get Set(ByVal value As Integer) End Set End Property End Class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = ")", .changeSpan = New TextSpan(code.IndexOf("x As Integer)", StringComparison.Ordinal) + 12, 1), .changeType = ChangeType.Remove}) End Sub <WorkItem(904792, "DevDiv/Personal")> <Fact> Public Sub IncParseErroneousGroupByQuery() Dim code As String = (<![CDATA[ Sub goo() Dim q2 = From i In str Group i By key1 = x Dim q3 =From j In str Group By key = i End Sub]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = " By", .changeSpan = New TextSpan(code.IndexOf(" By key1", StringComparison.Ordinal), 3), .changeType = ChangeType.Remove}) End Sub <WorkItem(904804, "DevDiv/Personal")> <Fact> Public Sub IncParseSetAfterIncompleteSub() Dim code As String = (<![CDATA[Sub goo() End Sub Public WriteOnly Property bar() as short Set End Set End Property]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(code.IndexOf("End Sub", StringComparison.Ordinal) + 7, 2), .changeType = ChangeType.Remove}) End Sub <WorkItem(911100, "DevDiv/Personal")> <Fact> Public Sub IncParseEmbeddedIfsInsideCondCompile() Dim code As String = "Sub bar() " & vbCrLf & "#If true Then" & vbCrLf & "if true Then goo()" & vbCrLf & "If Command() <" & vbCrLf IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = ">", .changeSpan = New TextSpan(code.IndexOf("If Command() <", StringComparison.Ordinal) + 14, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(911103, "DevDiv/Personal")> <Fact> Public Sub IncParseErrorIfStatement() Dim code As String = "Public Sub Run() " & vbCrLf & "If NewTextPI.DTE Is Nothing Then End" & vbCrLf & "End Sub" IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "NewTextPI", .changeSpan = New TextSpan(code.IndexOf("NewTextPI.DTE", StringComparison.Ordinal), 9), .changeType = ChangeType.Remove}) End Sub <WorkItem(537168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537168")> <Fact> Public Sub IncParseSubBeforePartialClass() Dim code As String = (<![CDATA[End Class Partial Class class3 End Class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Sub" & vbCrLf, .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(537172, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537172")> <Fact> Public Sub IncParseInterfaceDeleteWithColon() Dim code As String = (<![CDATA[Interface I : Sub Goo() : End Interface]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Interface ", .changeSpan = New TextSpan(0, 10), .changeType = ChangeType.Remove}) End Sub <WorkItem(537174, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537174")> <Fact> Public Sub IncParseMissingEndAddHandler() Dim code As String = (<![CDATA[ Class C Custom Event e As del AddHandler(ByVal value As del) End AddHandler RemoveHandler(ByVal value As del) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class ]]>).Value Dim change = "End AddHandler" IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = change, .changeSpan = New TextSpan(code.IndexOf(change, StringComparison.Ordinal), change.Length), .changeType = ChangeType.Remove}) End Sub <WorkItem(539038, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539038")> <Fact> Public Sub IncParseInvalidText() Dim code As String = (<![CDATA[1. Verify that INT accepts an constant of each type as the ' argument.]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "os: ", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(539053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539053")> <Fact> Public Sub IncParseAddSubValid() Dim code As String = (<![CDATA[Class CGoo Public S() Dim x As Integer = 0 End Sub End Class]]>).Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(22, 0), " Sub ")) Dim incTree = oldTree.WithChangedText(newText) Dim newTree = VisualBasicSyntaxTree.ParseText(newText) Dim exp1 = newTree.GetRoot().ChildNodesAndTokens()(0).ChildNodesAndTokens()(1) Dim inc1 = incTree.GetRoot().ChildNodesAndTokens()(0).ChildNodesAndTokens()(1) Assert.Equal(SyntaxKind.SubBlock, exp1.Kind()) Assert.Equal(exp1.Kind(), inc1.Kind()) Dim exp2 = exp1.ChildNodesAndTokens()(1) Dim inc2 = inc1.ChildNodesAndTokens()(1) Assert.Equal(SyntaxKind.LocalDeclarationStatement, exp2.Kind()) Assert.Equal(exp2.Kind(), inc2.Kind()) ' this XML output is too much 'IncParseAndVerify(New IncParseNode With { '.oldText = code, '.changeText = " Sub ", '.changeSpan = New TextSpan(22, 0), '.changeType = ChangeType.Insert}) End Sub <WorkItem(538577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538577")> <Fact> Public Sub IncParseAddSpaceAfterForNext() Dim code As String = (<![CDATA[Module M Sub Main() Dim i(1) As Integer For i(0) = 1 To 10 For j = 1 To 10 Next j, i(0) End Sub End Module ]]>).Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(103, 0), " ")) Dim incTree = oldTree.WithChangedText(newText) Dim newTree = VisualBasicSyntaxTree.ParseText(newText) Assert.Equal(False, oldTree.GetRoot().ContainsDiagnostics) Assert.Equal(False, newTree.GetRoot().ContainsDiagnostics) Assert.Equal(False, incTree.GetRoot().ContainsDiagnostics) VerifyEquivalent(incTree, newTree) End Sub <Fact> <WorkItem(540667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540667")> Public Sub IncrementalParseAddSpaceInSingleLineIf() ' The code below intentionally is missing a space between the "Then" and "Console" Dim code As String = (<![CDATA[ Module M Sub Main() If False ThenConsole.WriteLine("FIRST") : Console.WriteLine("TEST") Else Console.WriteLine("TRUE!") : 'comment End Sub End Module ]]>).Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim insertionPoint = code.IndexOf("Console", StringComparison.Ordinal) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(insertionPoint, 0), " ")) Dim expectedTree = VisualBasicSyntaxTree.ParseText(newText) Dim incrementalTree = oldTree.WithChangedText(newText) Assert.Equal(False, expectedTree.GetRoot().ContainsDiagnostics) Assert.Equal(False, incrementalTree.GetRoot().ContainsDiagnostics) VerifyEquivalent(incrementalTree, expectedTree) End Sub <Fact> <WorkItem(405887, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=405887")> Public Sub IncrementalParseInterpolationInSingleLineIf() Dim code As String = (<![CDATA[ Module Module1 Sub Test1(val1 As Integer) If val1 = 1 Then System.Console.WriteLine($"abc '" & sServiceName & "'") End Sub End Module ]]>).Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Const replace = """ &" Dim insertionPoint = code.IndexOf(replace, StringComparison.Ordinal) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(insertionPoint, replace.Length), "{")) Dim expectedTree = VisualBasicSyntaxTree.ParseText(newText) Dim incrementalTree = oldTree.WithChangedText(newText) Assert.Equal(True, expectedTree.GetRoot().ContainsDiagnostics) Assert.Equal(True, incrementalTree.GetRoot().ContainsDiagnostics) VerifyEquivalent(incrementalTree, expectedTree) End Sub #End Region <WorkItem(543489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543489")> <Fact> Public Sub Bug11296() Dim source As String = <![CDATA[ Module M Sub Main() GoTo 100 Dim Flag1 = 1 If Flag1 = 1 Then Flag1 = 100 Else 100: End If End Sub End Module ]]>.Value Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Assert.Equal(1, oldTree.GetDiagnostics().Count) Assert.Equal("Syntax error.", oldTree.GetDiagnostics()(0).GetMessage(EnsureEnglishUICulture.PreferredOrNull)) Assert.Equal("[131..134)", oldTree.GetDiagnostics()(0).Location.SourceSpan.ToString) ' commenting out the goto Dim pos = source.IndexOf("GoTo 100", StringComparison.Ordinal) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(pos, 0), "'")) Dim newTree = oldTree.WithChangedText(newText) Dim tmpTree = VisualBasicSyntaxTree.ParseText(newText) Assert.Equal(1, tmpTree.GetDiagnostics().Count) Assert.Equal("Syntax error.", tmpTree.GetDiagnostics()(0).GetMessage(EnsureEnglishUICulture.PreferredOrNull)) Assert.Equal("[132..135)", tmpTree.GetDiagnostics()(0).Location.SourceSpan.ToString) End Sub <Fact> Public Sub IncParseTypeNewLine() Dim code As String = (<![CDATA[ Module m Sub s End Sub End Module ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(15, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(545667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545667")> <Fact> Public Sub Bug14266() Dim source = <![CDATA[ Enum E A End Enum ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert a single character at the beginning. Dim newText = oldText.Replace(start:=0, length:=0, newText:="B") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(546680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546680")> <Fact> Public Sub Bug16533() Dim source = <![CDATA[ Module M Sub M() If True Then M() Else : End Sub End Module ]]>.Value Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Replace "True" with "True". Dim str = "True" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:=str) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, oldTree) End Sub <WorkItem(546685, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546685")> <Fact> Public Sub MultiLineIf() Dim source = <![CDATA[ Module M Sub M(b As Boolean) If b Then End If End Sub End Module ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Change "End Module" to "End module". Dim position = oldText.ToString().LastIndexOf("Module", StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=1, newText:="m") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' MultiLineIfBlock should not have been reused. Assert.True(diffs.Any(Function(n) n.IsKind(SyntaxKind.MultiLineIfBlock))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub ''' <summary> ''' Changes before a multi-line If should ''' not affect reuse of the If nodes. ''' </summary> <Fact> Public Sub MultiLineIf_2() Dim source = <![CDATA[ Module M Sub M() Dim b = False b = True If b Then End If End Sub End Module ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Change "False" to "True". Dim position = oldText.ToString().IndexOf("False", StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=5, newText:="True") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' MultiLineIfBlock should have been reused and should not appear in diffs. Assert.False(diffs.Any(Function(n) n.IsKind(SyntaxKind.MultiLineIfBlock))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub ''' <summary> ''' Changes sufficiently far after a multi-line If ''' should not affect reuse of the If nodes. ''' </summary> <Fact> Public Sub MultiLineIf_3() Dim source = <![CDATA[ Module M Sub M(b As Boolean) If b Then End If While b End While End Sub End Module ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Change "End Module" to "End module". Dim position = oldText.ToString().LastIndexOf("Module", StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=1, newText:="m") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' MultiLineIfBlock should have been reused and should not appear in diffs. Assert.False(diffs.Any(Function(n) n.IsKind(SyntaxKind.MultiLineIfBlock))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(546692, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546692")> <Fact> Public Sub Bug16575() Dim source = <![CDATA[ Module M Sub M() If True Then Else Dim x = 1 : Dim y = x If True Then Else Dim x = 1 : Dim y = x End Sub End Module ]]>.Value Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Add newline after first single line If Dim str = "y = x" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) + str.Length Dim newText = oldText.Replace(start:=position, length:=0, newText:=vbCrLf) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(546698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546698")> <Fact> Public Sub Bug16596() Dim source = ToText(<![CDATA[ Module M Sub M() If True Then Dim x = Sub() If True Then Return : 'Else End If End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Uncomment "Else". Dim position = oldText.ToString().IndexOf("'Else", StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=1, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(530662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530662")> <Fact> Public Sub Bug16662() Dim source = ToText(<![CDATA[ Module M Sub M() ''' <[ 1: X End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Remove "X". Dim position = oldText.ToString().IndexOf("X"c) Dim newText = oldText.Replace(start:=position, length:=1, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(546774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546774")> <Fact> Public Sub Bug16786() Dim source = <![CDATA[ Namespace N ''' <summary/> Class A End Class End Namespace Class B End Class Class C End Class ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Append "Class". Dim position = oldText.ToString().Length Dim newText = oldText.Replace(start:=position, length:=0, newText:=vbCrLf & "Class") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' Original Namespace should have been reused. Assert.False(diffs.Any(Function(n) n.IsKind(SyntaxKind.NamespaceBlock))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(530841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530841")> <Fact> Public Sub Bug17031() Dim source = ToText(<![CDATA[ Module M Sub M() If True Then Else End If End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Sub M()" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position + str.Length, length:=0, newText:=vbCrLf) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(531017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531017")> <Fact> Public Sub Bug17409() Dim source = ToText(<![CDATA[ Module M Sub M() Dim ch As Char Dim ch As Char Select Case ch Case "~"c Case Else End Select End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Remove second instance of "Dim ch As Char". Const str = "Dim ch As Char" Dim position = oldText.ToString().LastIndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:=String.Empty) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact, WorkItem(547242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547242")> Public Sub IncParseAddRemoveStopAtAofAs() Dim code As String = <![CDATA[ Module M Public obj0 As Object Public obj1 A]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(code) Dim oldIText = tree.GetText() ' Remove first N characters. Dim span = New TextSpan(0, code.IndexOf("j0", StringComparison.Ordinal)) Dim change = New TextChange(span, "") Dim newIText = oldIText.WithChanges(change) Dim newTree = tree.WithChangedText(newIText) Dim fulltree = VisualBasicSyntaxTree.ParseText(newIText.ToString()) Dim children1 = newTree.GetRoot().ChildNodesAndTokens() Dim children2 = fulltree.GetRoot().ChildNodesAndTokens() Assert.Equal(children2.Count, children1.Count) End Sub <Fact, WorkItem(547242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547242")> Public Sub IncParseAddRemoveStopAtAofAs02() Dim code As String = <![CDATA[ Module M Sub M() Try Catch ex A]]>.Value Dim fullTree = VisualBasicSyntaxTree.ParseText(code) Dim fullText = fullTree.GetText() Dim newTree = fullTree.WithChangedText(fullText) Assert.NotSame(newTree, fullTree) ' Relies on #550027 where WithChangedText returns an instance with changes. Assert.Equal(fullTree.GetRoot().ToFullString(), newTree.GetRoot().ToFullString()) End Sub <Fact, WorkItem(547251, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547251")> Public Sub IncParseAddRemoveStopAtAofPropAs() Dim code As String = <![CDATA[Class C Inherits Attribute ]]>.Value Dim code1 As String = <![CDATA[ Property goo() A]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(code) Dim oldIText = tree.GetText() ' insert code1 after code Dim span = New TextSpan(oldIText.Length, 0) Dim change = New TextChange(span, code1) Dim newIText = oldIText.WithChanges(change) Dim newTree = tree.WithChangedText(newIText) ' remove span = New TextSpan(0, code1.Length) change = New TextChange(span, "") newIText = newIText.WithChanges(change) ' InvalidCastException newTree = newTree.WithChangedText(newIText) Dim fulltree = VisualBasicSyntaxTree.ParseText(newIText.ToString()) Assert.Equal(fulltree.GetRoot().ToFullString(), newTree.GetRoot().ToFullString()) End Sub <Fact, WorkItem(547303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547303")> Public Sub IncParseAddRemoveStopAtTofThen() Dim code As String = <![CDATA[ Module M Sub M() If True Then ElseIf False T]]>.Value Dim fullTree = VisualBasicSyntaxTree.ParseText(code) Dim fullText = fullTree.GetText() Dim newTree = fullTree.WithChangedText(fullText) Assert.NotSame(newTree, fullTree) ' Relies on #550027 where WithChangedText returns an instance with changes. Assert.Equal(fullTree.GetRoot().ToFullString(), newTree.GetRoot().ToFullString()) End Sub <WorkItem(571105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/571105")> <Fact()> Public Sub IncParseInsertLineBreakBeforeLambda() Dim code As String = <![CDATA[ Module M Sub F() Dim a1 = If(Sub() End Sub, Nothing) End Sub End Module]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(code) Dim oldText = tree.GetText() ' insert line break after '=' Dim span = New TextSpan(code.IndexOf("="c), 0) Dim change = New TextChange(span, vbCrLf) Dim newText = oldText.WithChanges(change) Dim newTree = tree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(578279, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578279")> <Fact()> Public Sub IncParseInsertLineBreakBetweenEndSub() Dim code As String = <![CDATA[Class C Sub M() En Sub Private F = 1 End Class]]>.Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' insert line break Dim position = code.IndexOf("En ", StringComparison.Ordinal) Dim change = New TextChange(New TextSpan(position, 2), "End" + vbCrLf) Dim newText = oldText.WithChanges(change) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact()> Public Sub InsertWithinLookAhead() Dim code As String = <![CDATA[ Module M Function F(s As String) Return From c In s End Function End Module]]>.Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert "Select c" at end of method. Dim position = code.IndexOf(" End Function", StringComparison.Ordinal) Dim change = New TextChange(New TextSpan(position, 0), " Select c" + vbCrLf) Dim newText = oldText.WithChanges(change) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub #Region "Async & Iterator" <Fact> Public Sub AsyncToSyncMethod() Dim source = ToText(<![CDATA[ Class C Async Function M(t As Task) As Task Await (t) End Function Function Await(t) Return Nothing End Function End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Async" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub AsyncToSyncLambda() Dim source = ToText(<![CDATA[ Class C Function M(t As Task) Dim lambda = Async Function() Await(t) End Function Function Await(t) Return Nothing End Function End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Async" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub SyncToAsyncMethod() Dim source = ToText(<![CDATA[ Class C Function M(t As Task) As Task Await (t) End Function Function Await(t) Return Nothing End Function End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Function " Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="Async Function ") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub SyncToAsyncLambda() Dim source = ToText(<![CDATA[ Class C Function M(t As Task) Dim lambda = Function() Await(t) End Function Function Await(t) Return Nothing End Function End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Function()" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="Async Function ") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub AsyncToSyncMethodDecl() Dim source = ToText(<![CDATA[ Class C Async Function M(a As Await, t As Task) As Task Await t End Function End Class Class Await End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Async" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub SyncToAsyncMethodDecl() Dim source = ToText(<![CDATA[ Class C Function M(a As Await, t As Task) As Task Await t End Function End Class Class Await End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Function " Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="Async Function ") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IteratorToNonIteratorMethod() Dim source = ToText(<![CDATA[ Module Program Iterator Function Goo() As IEnumerable Yield (1) End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Iterator" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub NonIteratorToIteratorMethod() Dim source = ToText(<![CDATA[ Module Program Function Goo() As IEnumerable Yield (1) End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Function " Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="Iterator Function ") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IteratorToNonIteratorMethodDecl() Dim source = ToText(<![CDATA[ Module Program Iterator Function Goo(Yield As Integer) As IEnumerable Yield (1) End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Iterator" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub NonIteratorToIteratorMethodDecl() Dim source = ToText(<![CDATA[ Module Program Function Goo(Yield As Integer) As IEnumerable Yield (1) End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Function " Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="Iterator Function ") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub #End Region <WorkItem(554442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554442")> <Fact> Public Sub SplitCommentAtPreprocessorSymbol() Dim source = ToText(<![CDATA[ Module M Function F() ' comment # 1 and # 2 ' comment ' comment Return Nothing End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Split comment at "#". Dim position = oldText.ToString().IndexOf("#"c) Dim newText = oldText.Replace(start:=position, length:=0, newText:=vbCrLf) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(586698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/586698")> <Fact> Public Sub SortUsings() Dim oldSource = ToText(<![CDATA[ Imports System.Linq Imports System Imports Microsoft.VisualBasic Module Module1 Sub Main() End Sub End Module ]]>) Dim newSource = ToText(<![CDATA[ Imports System Imports System.Linq Imports Microsoft.VisualBasic Module Module1 Sub Main() End Sub End Module ]]>) Dim oldText = SourceText.From(oldSource) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Changes: ' 1. "" => "System\r\nImports " ' 2. "System\r\nImports " => "" Dim newText = oldText.WithChanges( New TextChange(TextSpan.FromBounds(8, 8), "System" + vbCrLf + "Imports "), New TextChange(TextSpan.FromBounds(29, 45), "")) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub Reformat() Dim oldSource = ToText(<![CDATA[ Class C Sub Method() Dim i = 1 Select Case i Case 1 , 2 , 3 End Select End Sub End Class ]]>) Dim newSource = ToText(<![CDATA[ Class C Sub Method() Dim i = 1 Select Case i Case 1, 2, 3 End Select End Sub End Class ]]>) Dim oldText = SourceText.From(oldSource) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim startOfNew = newSource.IndexOf("Dim", StringComparison.Ordinal) Dim endOfNew = newSource.LastIndexOf("Select", StringComparison.Ordinal) + 6 Dim startOfOld = startOfNew Dim endOfOld = oldSource.Length - newSource.Length + endOfNew Dim newText = oldText.Replace(TextSpan.FromBounds(startOfOld, endOfOld), newSource.Substring(startOfNew, endOfNew - startOfNew + 1)) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(604044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/604044")> <Fact> Public Sub BunchALabels() Dim source = ToText(<![CDATA[ Module Program Sub Main() &HF: &HFF: &HFFF: &HFFFF: &HFFFFF: &HFFFFFF: &HFFFFFFF: &HFFFFFFFF: &HFFFFFFFFF: &HFFFFFFFFFF: End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Add enter after &HFFFFFFFFFF:. Dim position = oldText.ToString().IndexOf("&HFFFFFFFFFF:", StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position + "&HFFFFFFFFFF:".Length, length:=0, newText:=vbCrLf) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(625612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/625612")> <Fact()> Public Sub LabelAfterColon() ' Label following another label on separate lines. LabelAfterColonCore(True, <![CDATA[Module M Sub M() 10: 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) ' Label following another label on separate lines. LabelAfterColonCore(True, <![CDATA[Module M Sub M() 10: : 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) ' Label following on the same line as another label. LabelAfterColonCore(False, <![CDATA[Module M Sub M() 10: 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) ' Label following on the same line as another label. LabelAfterColonCore(False, <![CDATA[Module M Sub M() 10: : 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) ' Label following on the same line as another statement. LabelAfterColonCore(False, <![CDATA[Module M Sub M() M() : 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) ' Label following a colon within a single-line statement. LabelAfterColonCore(False, <![CDATA[Module M Sub M() If True Then M() : 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) End Sub Private Sub LabelAfterColonCore(valid As Boolean, code As String) Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim diagnostics = oldTree.GetDiagnostics() Assert.Equal(valid, diagnostics.Count = 0) ' Replace "70". Dim position = code.IndexOf("70", StringComparison.Ordinal) Dim change = New TextChange(New TextSpan(position, 2), "71") Dim newText = oldText.WithChanges(change) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(529260, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529260")> <Fact()> Public Sub DoNotReuseAnnotatedNodes() Dim text As String = <![CDATA[ Class C End Class Class D End Class ]]>.Value.Replace(vbCr, vbCrLf) ' NOTE: We're using the class statement, rather than the block, because the ' change region is expanded enough to impinge on the block. Dim extractGreenClassC As Func(Of SyntaxTree, Syntax.InternalSyntax.VisualBasicSyntaxNode) = Function(tree) DirectCast(tree.GetRoot().DescendantNodes().First(Function(n) n.IsKind(SyntaxKind.ClassStatement)), VisualBasicSyntaxNode).VbGreen '''''''''' ' Check reuse after a trivial change in an unannotated tree. '''''''''' Dim oldTree1 = VisualBasicSyntaxTree.ParseText(text) Dim newTree1 = oldTree1.WithInsertAt(text.Length, " ") ' Class declaration is reused. Assert.Same(extractGreenClassC(oldTree1), extractGreenClassC(newTree1)) '''''''''' ' Check reuse after a trivial change in an annotated tree. '''''''''' Dim tempTree2 = VisualBasicSyntaxTree.ParseText(text) Dim tempRoot2 = tempTree2.GetRoot() Dim tempToken2 = tempRoot2.DescendantTokens().First(Function(t) t.Kind = SyntaxKind.IdentifierToken) Dim oldRoot2 = tempRoot2.ReplaceToken(tempToken2, tempToken2.WithAdditionalAnnotations(New SyntaxAnnotation())) Assert.True(oldRoot2.ContainsAnnotations, "Should contain annotations.") Assert.Equal(text, oldRoot2.ToFullString()) Dim oldTree2 = VisualBasicSyntaxTree.Create(DirectCast(oldRoot2, VisualBasicSyntaxNode), DirectCast(tempTree2.Options, VisualBasicParseOptions), tempTree2.FilePath, Encoding.UTF8) Dim newTree2 = oldTree2.WithInsertAt(text.Length, " ") Dim oldClassC2 = extractGreenClassC(oldTree2) Dim newClassC2 = extractGreenClassC(newTree2) Assert.True(oldClassC2.ContainsAnnotations, "Should contain annotations") Assert.False(newClassC2.ContainsAnnotations, "Annotations should have been removed.") ' Class declaration is not reused... Assert.NotSame(oldClassC2, newClassC2) ' ...even though the text is the same. Assert.Equal(oldClassC2.ToFullString(), newClassC2.ToFullString()) Dim oldToken2 = DirectCast(oldClassC2, Syntax.InternalSyntax.ClassStatementSyntax).Identifier Dim newToken2 = DirectCast(newClassC2, Syntax.InternalSyntax.ClassStatementSyntax).Identifier Assert.True(oldToken2.ContainsAnnotations, "Should contain annotations") Assert.False(newToken2.ContainsAnnotations, "Annotations should have been removed.") ' Token is not reused... Assert.NotSame(oldToken2, newToken2) ' ...even though the text is the same. Assert.Equal(oldToken2.ToFullString(), newToken2.ToFullString()) End Sub <Fact> Public Sub IncrementalParsing_NamespaceBlock_TryLinkSyntaxMethodsBlock() 'Sub Block 'Function Block 'Property Block Dim source = ToText(<![CDATA[ Namespace N Module M Function F() as Boolean Return True End Function Sub M() End Sub Function Fn() as Boolean Return True End Function Property as Integer = 1 End Module End Namespace ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Module M" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_ExecutableStatementBlock_TryLinkSyntaxClass() 'Class Block Dim source = ToText(<![CDATA[ Module M Sub M() End Sub Dim x = Nothing Public Class C1 End Class Class C2 End Class End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Sub" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_ExecutableStatementBlock_TryLinkSyntaxStructure() 'Structure Block Dim source = ToText(<![CDATA[ Module M Sub M() End Sub Dim x = Nothing Structure S2 1 Dim i as integer End Structure Public Structure S2 Dim i as integer End Structure End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Sub" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact()> Public Sub IncrementalParsing_ExecutableStatementBlock_TryLinkSyntaxOptionStatement() 'Option Statement Dim source = ToText(<![CDATA[ Option Strict Off Option Infer On Option Explicit On ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Sub" Dim TextToAdd As String = "Module Module1" & Environment.NewLine & "Sub Goo()" & Environment.NewLine Dim position = 0 Dim newText = oldText.Replace(start:=position, length:=1, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact()> Public Sub IncrementalParsing_ExecutableStatementBlock_TryLinkSyntaxImports() 'Imports Statement Dim source = ToText(<![CDATA[ Imports System Imports System.Collections Imports Microsoft.Visualbasic ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Sub" Dim TextToAdd As String = "Module Module1" & Environment.NewLine & "Sub Goo()" & Environment.NewLine Dim position = 0 Dim newText = oldText.Replace(start:=position, length:=1, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_ExecutableStatementBlock_TryLinkSyntaxDelegateSub() 'ExecutableStatementBlock -> DelegateSub Dim source = ToText(<![CDATA[ Module Module1 Sub Main() End Sub Dim x = Nothing Delegate Sub Goo() Public Delegate Sub GooWithModifier() End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Sub" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxOperatorBlock() Dim source = ToText(<![CDATA[ Module Module1 Sub Main() Dim x As New SomeClass Dim y As Boolean = -x End Sub Class SomeClass Dim member As Long = 2 Public Overloads Shared Operator -(ByVal value As SomeClass) As Boolean If value.member Mod 5 = 0 Then Return True End If Return False End Operator End Class End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Class SomeClass" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxEventBlock() Dim source = ToText(<![CDATA[ Module Module1 Sub Main() End Sub Class SomeClass Dim member As Long = 2 Public Custom Event AnyName As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event End Class End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Class SomeClass" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxPropertyBlock() Dim source = ToText(<![CDATA[ Module Module1 Sub Main() End Sub Class SomeClass Dim member As Long = 2 Public Property abc As Integer Set(value As Integer) End Set Get End Get End Property End Class End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Class SomeClass" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxNamespaceModuleBlock() Dim source = ToText(<![CDATA[ Namespace NS1 Module Module1 Sub Goo() End Sub Dim x End Module 'Remove Namespace vs End Namespace Module Module1 Dim x End Module End Namespace ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Module 'Remove" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxNamespaceNamespaceBlock() Dim source = ToText(<![CDATA[ Namespace NS1 Module Module1 Sub Goo() End Sub Dim x End Module 'Remove Namespace vs Namespace vs2 End Namespace End Namespace Namespace vs3 End Namespace End Namespace ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Module 'Remove" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxItems() Dim source = ToText(<![CDATA[ Class SomeClass Dim member As Long = 2 Sub abc() 'Remove Dim xyz as integer = 2 IF member = 1 then Console.writeline("TEST"); Dim SingleLineDeclare as integer = 2 End Sub Dim member2 As Long = 2 Dim member3 As Long = 2 Enum EnumItem Item1 End Enum End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Sub abc() 'Remove" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_PropertyContextBlock_TryLinkSyntaxSetAccessor() 'PropertyContextBlock -> SetAccessor Dim source = ToText(<![CDATA[ Class C Private _p As Integer = 0 Property p2 As Integer Set(value As Integer) End Set Get End Get End Property Private _d As Integer = 1 End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Property" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_BlockContext_TryLinkSyntaxSelectBlock() Dim source = ToText(<![CDATA[ Module Module1 Private _p As Integer = 0 Sub Bar() End Sub Function Goo(i As Integer) As Integer Dim y As Integer = i Select Case y Case 1 Case 2, 3 Case Else End Select Return y + 1 Try Catch ex As exception End Try If y = 1 Then Console.WriteLine("Test") Y = 1 While y <= 10 y = y + 1 End While Using f As New Goo End Using Dim Obj_C As New OtherClass With Obj_C End With SyncLock Obj_C End SyncLock Select Case y Case 10 Case Else End Select y = 0 Do y = y + 1 If y >= 3 Then Exit Do Loop y = 0 Do While y < 4 y = y + 1 Loop y = 0 Do Until y > 5 y = y + 1 Loop End Function End Module Class Goo Implements IDisposable #Region "IDisposable Support" Private disposedValue As Boolean ' To detect redundant calls ' IDisposable Protected Overridable Sub Dispose(disposing As Boolean) If Not Me.disposedValue Then If disposing Then End If End If Me.disposedValue = True End Sub Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub #End Region End Class Class OtherClass End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Select" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_EventBlockContext_TryLinkSyntax1() Dim source = ToText(<![CDATA[ Module Module1 Public Custom Event AnyName As EventHandler AddHandler(ByVal value As EventHandler) _P = 1 End AddHandler RemoveHandler(ByVal value As EventHandler) _P = 2 End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) _P = 3 End RaiseEvent End Event Private _p As Integer = 0 Sub Main() End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "RemoveHandler(ByVal value As EventHandler)" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_EventBlockContext_TryLinkSyntax2() Dim source = ToText(<![CDATA[ Module Module1 Public Custom Event AnyName As EventHandler AddHandler(ByVal value As EventHandler) _P = 1 End AddHandler RemoveHandler(ByVal value As EventHandler) _P = 2 End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) _P = 3 _P = _P +1 End RaiseEvent End Event Private _p As Integer = 0 Sub Main() End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "_P = 3" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_InterfaceBlockContext_TryLinkSyntaxClass() Dim source = ToText(<![CDATA[ Module Module1 Sub Main() End Sub Interface IGoo End Interface Dim _p Class C End Class End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Interface" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_InterfaceBlockContext_TryLinkSyntaxEnum() Dim source = ToText(<![CDATA[ Module Module1 Sub Main() End Sub Interface IGoo End Interface Dim _p Public Enum TestEnum Item End Enum End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Interface" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_CaseBlockContext_TryLinkSyntaxCase() Dim source = ToText(<![CDATA[ Module Module1 Sub Goo() Dim i As Integer Dim y As Integer Select Case i Case 1 _p = 1 Case 2, 3 _p = 2 Case Else _p = 3 End Select End Sub Private _p As Integer = 0 Sub Main() End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Case 2, 3" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_CatchContext_TryLinkSyntaxCatch() Dim source = ToText(<![CDATA[ Module Module1 Sub Goo() Dim x1 As Integer = 1 Try x1 = 2 Catch ex As NullReferenceException Dim z = 1 Catch ex As ArgumentException 'Remove Dim z = 1 Catch ex As Exception _p = 3 Dim s = Bar() Finally _p = 4 End Try End Sub Private _p As Integer = 0 Function Bar() As String End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Catch ex As ArgumentException 'Remove" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact()> Public Sub IncrementalParsing_NamespaceBlockContext_TryLinkSyntaxModule() Dim source = ToText(<![CDATA[ Namespace NS1 Module ModuleTemp 'Remove End Module Module Module1 'Remove Sub Goo() Dim x1 As Integer = 1 End Sub Private _p As Integer = 0 Function Bar() As String End Function End Module End Namespace ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Module ModuleTemp 'Remove" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_IfBlockContext_TryLinkSyntax() Dim source = ToText(<![CDATA[ Module Module1 Private _p As Integer = 0 Sub Goo() If x = 1 Then _p=1 elseIf x = 2 Then _p=2 elseIf x = 3 Then _p=3 else If y = 1 Then _p=2 End If End If End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "elseIf x = 2 Then" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(719787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/719787")> <Fact()> Public Sub Bug719787_EOF() Dim source = <![CDATA[ Namespace N Class C Property P As Integer End Class Structure S Private F As Object End Structure End Namespace ]]>.Value.Trim() ' Add two line breaks at end. source += vbCrLf Dim position = source.Length source += vbCrLf Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Add "Delegate" to end of file between line breaks. Dim newText = oldText.Replace(start:=position, length:=0, newText:="Delegate") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' Most of the Namespace should have been reused. Assert.False(diffs.Any(Function(n) n.IsKind(SyntaxKind.StructureStatement))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(719787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/719787")> <Fact> Public Sub Bug719787_MultiLineIf() Dim source = <![CDATA[ Class C Sub M() If e1 Then If e2 Then M11() Else M12() End If ElseIf e2 Then If e2 Then M21() Else M22() End If ElseIf e3 Then If e2 Then M31() Else M32() End If ElseIf e4 Then If e2 Then M41() Else M42() End If Else If e2 Then M51() Else M52() End If End If End Sub ' Comment End Class ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim toReplace = "' Comment" Dim position = source.IndexOf(toReplace, StringComparison.Ordinal) ' Replace "' Comment" with "Property" Dim newText = oldText.Replace(start:=position, length:=toReplace.Length, newText:="Property") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' The ElseIfBlocks should have been reused. Assert.False(diffs.Any(Function(n) n.IsKind(SyntaxKind.ElseIfBlock))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub #Region "Helpers" Private Shared Function GetTokens(root As SyntaxNode) As InternalSyntax.VisualBasicSyntaxNode() Return root.DescendantTokens().Select(Function(t) DirectCast(t.Node, InternalSyntax.VisualBasicSyntaxNode)).ToArray() End Function Private Shared Sub VerifyTokensEquivalent(rootA As SyntaxNode, rootB As SyntaxNode) Dim tokensA = GetTokens(rootA) Dim tokensB = GetTokens(rootB) Assert.Equal(tokensA.Count, tokensB.Count) For i = 0 To tokensA.Count - 1 Dim tokenA = tokensA(i) Dim tokenB = tokensB(i) Assert.Equal(tokenA.Kind, tokenB.Kind) Assert.Equal(tokenA.ToFullString(), tokenB.ToFullString()) Next End Sub Private Shared Sub VerifyEquivalent(treeA As SyntaxTree, treeB As SyntaxTree) Dim rootA = treeA.GetRoot() Dim rootB = treeB.GetRoot() VerifyTokensEquivalent(rootA, rootB) Dim diagnosticsA = treeA.GetDiagnostics() Dim diagnosticsB = treeB.GetDiagnostics() Assert.True(rootA.IsEquivalentTo(rootB)) Assert.Equal(diagnosticsA.Count, diagnosticsB.Count) For i = 0 To diagnosticsA.Count - 1 Assert.Equal(diagnosticsA(i).Inspect(), diagnosticsB(i).Inspect()) Next End Sub Private Shared Function ToText(code As XCData) As String Dim str = code.Value.Trim() ' Normalize line terminators. Dim builder = ArrayBuilder(Of Char).GetInstance() For i = 0 To str.Length - 1 Dim c = str(i) If (c = vbLf(0)) AndAlso ((i = str.Length - 1) OrElse (str(i + 1) <> vbCr(0))) Then builder.AddRange(vbCrLf) Else builder.Add(c) End If Next Return New String(builder.ToArrayAndFree()) End Function #End Region End Class
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.ObjectModel Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Public Class IncrementalParser Private ReadOnly _s As String = <![CDATA[ '----------------------- ' ' Copyright (c) ' '----------------------- #const BLAH = true Imports Roslyn.Compilers Imports Roslyn.Compilers.Common Imports Roslyn.Compilers.VisualBasic Public Module ParseExprSemantics Dim text = SourceText.From("") Dim tree As SyntaxTree = Nothing #const x = 1 ''' <summary> ''' This is just gibberish to test parser ''' </summary> ''' <param name="ITERS"> haha </param> ''' <remarks></remarks> Public Sub Run(ByVal ITERS As Long) Console.WriteLine() #if BLAH Console.WriteLine("==== Parsing file: " & "Sample_ExpressionSemantics.vb") Console.WriteLine("Iterations:" & ITERS) #end if Dim str = IO.File.ReadAllText("Sample_ExpressionSemantics.vb") Dim lineNumber = 28335 Dim root As SyntaxNode = Nothing dim s1 = sub () If True Then Console.WriteLine(1) : dim s2 = sub () If True Then Console.WriteLine(1) ::Console.WriteLine(1):: dim s3 = sub() If True Then Console.WriteLine(1) :::: Console.WriteLine(1) Dim sw = System.Diagnostics.Stopwatch.StartNew() For i As Integer = 0 To ITERS - 1 tree = SyntaxTree.Parse(text, Nothing) root = tree.Root Console.Write(".") Dim highWater As Integer = Math.Max(highWater, System.GC.GetTotalMemory(False)) Next Dim grouped = From node In root.GetNodesWhile(root.FullSpan, Function() True) Group By node.Kind Into Group, Count() Order By Count Descending Take 30 Console.WriteLine("Quick token cache-hits: {0} ({1:G2}%)", Stats.quickReturnedToken, 100.0 * Stats.quickReturnedToken / Stats.quickAttempts) End Sub End Module]]>.Value <Fact> Public Sub FakeEdits() Dim text As SourceText = SourceText.From(_s) Dim tree As SyntaxTree = Nothing Dim root As SyntaxNode = Nothing tree = VisualBasicSyntaxTree.ParseText(text) root = tree.GetRoot() Assert.Equal(False, root.ContainsDiagnostics) For i As Integer = 0 To text.Length - 11 Dim span = New TextSpan(i, 10) text = text.WithChanges(New TextChange(span, text.ToString(span))) tree = tree.WithChangedText(text) Dim prevRoot = root root = tree.GetRoot() Assert.True(prevRoot.IsEquivalentTo(root)) Next End Sub <Fact> Public Sub TypeAFile() Dim text As SourceText = SourceText.From("") Dim tree As SyntaxTree = Nothing tree = VisualBasicSyntaxTree.ParseText(text) Assert.Equal(False, tree.GetRoot().ContainsDiagnostics) For i As Integer = 0 To _s.Length - 1 ' add next character in file 's' to text Dim newText = text.WithChanges(New TextChange(New TextSpan(text.Length, 0), _s.Substring(i, 1))) Dim newTree = tree.WithChangedText(newText) Dim tmpTree = VisualBasicSyntaxTree.ParseText(newText) VerifyEquivalent(newTree, tmpTree) text = newText tree = newTree Next End Sub <Fact> Public Sub Preprocessor() Dim oldText = SourceText.From(_s) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' commenting out the #const Dim pos = _s.IndexOf("#const", StringComparison.Ordinal) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(pos, 0), "'")) Dim newTree = oldTree.WithChangedText(newText) Dim tmpTree = VisualBasicSyntaxTree.ParseText(newText) VerifyEquivalent(newTree, tmpTree) ' removes ' from the '#const Dim newString = newText.ToString() pos = newString.IndexOf("'#const", StringComparison.Ordinal) Dim anotherText = newText.WithChanges(New TextChange(New TextSpan(pos, 1), "")) newTree = newTree.WithChangedText(anotherText) tmpTree = VisualBasicSyntaxTree.ParseText(anotherText) VerifyEquivalent(newTree, tmpTree) End Sub #Region "Regressions" <WorkItem(899264, "DevDiv/Personal")> <Fact> Public Sub IncParseWithEventsFollowingProperty() 'Unable to verify this using CDATA, since CDATA value only has Cr appended at end of each line, 'where as this bug is reproducible only with CrLf at the end of each line Dim code As String = "Public Class HasPublicMembersToConflictWith" & vbCrLf & "Public ConflictWithProp" & vbCrLf & "" & vbCrLf & "Public Property _ConflictWithBF() As String" & vbCrLf & " Get" & vbCrLf & " End Get" & vbCrLf & " Set(value As String)" & vbCrLf & " End Set" & vbCrLf & "End Property" & vbCrLf & "" & vbCrLf & "Public WithEvents ConflictWithBoth As Ob" ParseAndVerify(code, <errors> <error id="30481"/> </errors>) IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "j", .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(899596, "DevDiv/Personal")> <Fact> Public Sub IncParseClassFollowingDocComments() Dim code As String = <![CDATA[Class VBQATestcase '''----------------------------------------------------------------------------- ''' <summary> '''Text ''' </summary> '''-----------------------------------------------------------------------------]]>.Value ParseAndVerify(code, <errors> <error id="30481"/> </errors>) IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf & "Pub", .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(899918, "DevDiv/Personal")> <Fact> Public Sub IncParseDirInElse() Dim code As String = "Sub Sub1()" & vbCr & "If true Then" & vbCr & "goo("""")" & vbCr & "Else" & vbCr & vbCr & "#If Not ULTRAVIOLET Then" & vbCr ParseAndVerify(code, <errors> <error id="30012"/> <error id="30081"/> <error id="30026"/> </errors>) IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "a", .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(899938, "DevDiv/Personal")> <Fact> Public Sub IncParseNamespaceFollowingEvent() Dim code As String = "Class cls1" & vbCrLf & "Custom Event myevent As del" & vbCrLf & "End Event" & vbCrLf & "End Class" & vbCrLf & "Namespace r" IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "e", .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(900209, "DevDiv/Personal")> <Fact> Public Sub IncParseCaseElse() Dim code As String = (<![CDATA[ Sub main() Select Case 5 Case Else vvv = 6 Case Else vvv = 7 ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(901386, "DevDiv/Personal")> <Fact> Public Sub IncParseExplicitOnGroupBy() Dim code As String = (<![CDATA[ Option Explicit On Sub goo() Dim q2 = From x In col let y = x Group x, y By]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "a", .changeSpan = New TextSpan(code.Length, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(901639, "DevDiv/Personal")> <Fact> Public Sub IncParseExprLambdaInSubContext() Dim code As String = (<![CDATA[Function() NewTextPI.UnwrapObject().FileCodeModel) If True Then End If End Sub Class WillHaveAnError End class Class willBeReused End class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "(", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <Fact> Public Sub IncParseExprLambdaInSubContext2() Dim code As String = (<![CDATA[Function() NewTextPI.UnwrapObject().FileCodeModel) If True Then Else End If End Sub Class WillHaveAnError End class Class willBeReused End class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "(", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(901645, "DevDiv/Personal")> <Fact> Public Sub IncParseExitFunction() Dim code As String = (<![CDATA[Function If strSwitches <> "" Then strCLine = strCLine & " " & strSwitches End Sub]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Exit ", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(901655, "DevDiv/Personal")> <Fact> Public Sub IncParseDateLiteral() IncParseAndVerify(New IncParseNode With { .oldText = "", .changeText = "#10/18/1969# hello 123", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <Fact> Public Sub IncParsePPElse() Dim code As String = (<![CDATA[ Function goo() As Boolean #Else Dim roleName As Object For Each roleName In wbirFields Next roleName End Function ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "#End If", .changeSpan = New TextSpan(code.IndexOf("Next roleName", StringComparison.Ordinal) + 15, 2), .changeType = ChangeType.Replace}) End Sub <Fact> Public Sub IncParsePPElse1() Dim code As String = (<![CDATA[ Function goo() As Boolean #Else Dim roleName As Object For Each roleName In wbirFields Next roleName #End IF End Function ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "#If true " & vbCrLf, .changeSpan = New TextSpan(code.IndexOf("#Else", StringComparison.Ordinal), 0), .changeType = ChangeType.Replace}) End Sub <WorkItem(901669, "DevDiv/Personal")> <Fact> Public Sub ParseXmlTagWithExprHole() Dim code As String = (<![CDATA[e a=<%= b %>>]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "<", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(901671, "DevDiv/Personal")> <Fact> Public Sub IncParseEndBeforeSubWithX() Dim code As String = (<![CDATA[Sub End Class X]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "End ", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(901676, "DevDiv/Personal")> <Fact> Public Sub IncParseInterfaceFollByConstructs() Dim code As String = (<![CDATA[ Public Interface I2 End Interface Sub SEHIllegal501() Try Catch End Try Exit Sub End Sub X]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Interface", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(901680, "DevDiv/Personal")> <Fact> Public Sub IncParseLCFunctionCompoundAsn() Dim code As String = (<![CDATA[Public Function goo() As String For i As Integer = 0 To 1 total += y(i) Next End Function]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "> _" & vbCrLf, .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(902710, "DevDiv/Personal")> <Fact> Public Sub IncParseInsertFunctionBeforeEndClass() Dim code As String = (<![CDATA[End Class MustInherit Class C10 End Class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Function" & vbCrLf, .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(903134, "DevDiv/Personal")> <Fact> Public Sub InsertSubBeforeCustomEvent() Dim code As String = (<![CDATA[ Custom Event e As del AddHandler(ByVal value As del) End AddHandler End Event]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Sub" & vbCrLf, .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(903555, "DevDiv/Personal")> <Fact> Public Sub ParseMergedForEachAndDecl() Dim code As String = (<![CDATA[#Region "abc" Function goo() As Boolean Dim roleName As Object For Each roleName In wbirFields Next roleName End Function #End Region]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(code.IndexOf("Dim roleName As Object", StringComparison.Ordinal) + 22, 2), .changeType = ChangeType.Remove}) End Sub <WorkItem(903805, "DevDiv/Personal")> <Fact> Public Sub ParseEnumWithoutEnd() Dim code As String = (<![CDATA[Public Class Class2 Protected Enum e e1 e2 End Enum Public Function Goo(ByVal arg1 As e) As e End Function End Class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(code.IndexOf("e2", StringComparison.Ordinal) + 2, 2), .changeType = ChangeType.Remove}) End Sub <WorkItem(903826, "DevDiv/Personal")> <Fact> Public Sub IncParseWrongSelectFollByIf() Dim code As String = (<![CDATA[ Sub goo() Select Case lng Case 44 int1 = 4 End Select If true Then End If End Sub]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "End ", .changeSpan = New TextSpan(code.IndexOf("End ", StringComparison.Ordinal), 4), .changeType = ChangeType.Remove}) End Sub <WorkItem(904768, "DevDiv/Personal")> <Fact> Public Sub IncParseDoLoop() Dim code As String = (<![CDATA[ Sub AnonTConStmnt() Do i += 1 Loop Until true End Sub ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(code.IndexOf("Do", StringComparison.Ordinal) + 2, 2), .changeType = ChangeType.Remove}) End Sub <WorkItem(904771, "DevDiv/Personal")> <Fact> Public Sub IncParseClassWithOpDecl() Dim code As String = (<![CDATA[ Friend Module m1 Class Class1 Shared Operator -(ByVal x As Class1) As Boolean End Operator End Class End Module ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Class ", .changeSpan = New TextSpan(code.IndexOf("Class ", StringComparison.Ordinal), 6), .changeType = ChangeType.Remove}) End Sub <WorkItem(904782, "DevDiv/Personal")> <Fact> Public Sub IncParsePropFollIncompleteLambda() Dim code As String = (<![CDATA[ Class c1 Public Function goo() As Object Dim res = Function(x As Integer) c1.Goo(x) End Function Default Public Property Prop(ByVal y As String) As Integer Get End Get Set(ByVal value As Integer) End Set End Property End Class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = ")", .changeSpan = New TextSpan(code.IndexOf("x As Integer)", StringComparison.Ordinal) + 12, 1), .changeType = ChangeType.Remove}) End Sub <WorkItem(904792, "DevDiv/Personal")> <Fact> Public Sub IncParseErroneousGroupByQuery() Dim code As String = (<![CDATA[ Sub goo() Dim q2 = From i In str Group i By key1 = x Dim q3 =From j In str Group By key = i End Sub]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = " By", .changeSpan = New TextSpan(code.IndexOf(" By key1", StringComparison.Ordinal), 3), .changeType = ChangeType.Remove}) End Sub <WorkItem(904804, "DevDiv/Personal")> <Fact> Public Sub IncParseSetAfterIncompleteSub() Dim code As String = (<![CDATA[Sub goo() End Sub Public WriteOnly Property bar() as short Set End Set End Property]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(code.IndexOf("End Sub", StringComparison.Ordinal) + 7, 2), .changeType = ChangeType.Remove}) End Sub <WorkItem(911100, "DevDiv/Personal")> <Fact> Public Sub IncParseEmbeddedIfsInsideCondCompile() Dim code As String = "Sub bar() " & vbCrLf & "#If true Then" & vbCrLf & "if true Then goo()" & vbCrLf & "If Command() <" & vbCrLf IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = ">", .changeSpan = New TextSpan(code.IndexOf("If Command() <", StringComparison.Ordinal) + 14, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(911103, "DevDiv/Personal")> <Fact> Public Sub IncParseErrorIfStatement() Dim code As String = "Public Sub Run() " & vbCrLf & "If NewTextPI.DTE Is Nothing Then End" & vbCrLf & "End Sub" IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "NewTextPI", .changeSpan = New TextSpan(code.IndexOf("NewTextPI.DTE", StringComparison.Ordinal), 9), .changeType = ChangeType.Remove}) End Sub <WorkItem(537168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537168")> <Fact> Public Sub IncParseSubBeforePartialClass() Dim code As String = (<![CDATA[End Class Partial Class class3 End Class]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Sub" & vbCrLf, .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(537172, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537172")> <Fact> Public Sub IncParseInterfaceDeleteWithColon() Dim code As String = (<![CDATA[Interface I : Sub Goo() : End Interface]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "Interface ", .changeSpan = New TextSpan(0, 10), .changeType = ChangeType.Remove}) End Sub <WorkItem(537174, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537174")> <Fact> Public Sub IncParseMissingEndAddHandler() Dim code As String = (<![CDATA[ Class C Custom Event e As del AddHandler(ByVal value As del) End AddHandler RemoveHandler(ByVal value As del) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class ]]>).Value Dim change = "End AddHandler" IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = change, .changeSpan = New TextSpan(code.IndexOf(change, StringComparison.Ordinal), change.Length), .changeType = ChangeType.Remove}) End Sub <WorkItem(539038, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539038")> <Fact> Public Sub IncParseInvalidText() Dim code As String = (<![CDATA[1. Verify that INT accepts an constant of each type as the ' argument.]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = "os: ", .changeSpan = New TextSpan(0, 0), .changeType = ChangeType.InsertBefore}) End Sub <WorkItem(539053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539053")> <Fact> Public Sub IncParseAddSubValid() Dim code As String = (<![CDATA[Class CGoo Public S() Dim x As Integer = 0 End Sub End Class]]>).Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(22, 0), " Sub ")) Dim incTree = oldTree.WithChangedText(newText) Dim newTree = VisualBasicSyntaxTree.ParseText(newText) Dim exp1 = newTree.GetRoot().ChildNodesAndTokens()(0).ChildNodesAndTokens()(1) Dim inc1 = incTree.GetRoot().ChildNodesAndTokens()(0).ChildNodesAndTokens()(1) Assert.Equal(SyntaxKind.SubBlock, exp1.Kind()) Assert.Equal(exp1.Kind(), inc1.Kind()) Dim exp2 = exp1.ChildNodesAndTokens()(1) Dim inc2 = inc1.ChildNodesAndTokens()(1) Assert.Equal(SyntaxKind.LocalDeclarationStatement, exp2.Kind()) Assert.Equal(exp2.Kind(), inc2.Kind()) ' this XML output is too much 'IncParseAndVerify(New IncParseNode With { '.oldText = code, '.changeText = " Sub ", '.changeSpan = New TextSpan(22, 0), '.changeType = ChangeType.Insert}) End Sub <WorkItem(538577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538577")> <Fact> Public Sub IncParseAddSpaceAfterForNext() Dim code As String = (<![CDATA[Module M Sub Main() Dim i(1) As Integer For i(0) = 1 To 10 For j = 1 To 10 Next j, i(0) End Sub End Module ]]>).Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(103, 0), " ")) Dim incTree = oldTree.WithChangedText(newText) Dim newTree = VisualBasicSyntaxTree.ParseText(newText) Assert.Equal(False, oldTree.GetRoot().ContainsDiagnostics) Assert.Equal(False, newTree.GetRoot().ContainsDiagnostics) Assert.Equal(False, incTree.GetRoot().ContainsDiagnostics) VerifyEquivalent(incTree, newTree) End Sub <Fact> <WorkItem(540667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540667")> Public Sub IncrementalParseAddSpaceInSingleLineIf() ' The code below intentionally is missing a space between the "Then" and "Console" Dim code As String = (<![CDATA[ Module M Sub Main() If False ThenConsole.WriteLine("FIRST") : Console.WriteLine("TEST") Else Console.WriteLine("TRUE!") : 'comment End Sub End Module ]]>).Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim insertionPoint = code.IndexOf("Console", StringComparison.Ordinal) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(insertionPoint, 0), " ")) Dim expectedTree = VisualBasicSyntaxTree.ParseText(newText) Dim incrementalTree = oldTree.WithChangedText(newText) Assert.Equal(False, expectedTree.GetRoot().ContainsDiagnostics) Assert.Equal(False, incrementalTree.GetRoot().ContainsDiagnostics) VerifyEquivalent(incrementalTree, expectedTree) End Sub <Fact> <WorkItem(405887, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=405887")> Public Sub IncrementalParseInterpolationInSingleLineIf() Dim code As String = (<![CDATA[ Module Module1 Sub Test1(val1 As Integer) If val1 = 1 Then System.Console.WriteLine($"abc '" & sServiceName & "'") End Sub End Module ]]>).Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Const replace = """ &" Dim insertionPoint = code.IndexOf(replace, StringComparison.Ordinal) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(insertionPoint, replace.Length), "{")) Dim expectedTree = VisualBasicSyntaxTree.ParseText(newText) Dim incrementalTree = oldTree.WithChangedText(newText) Assert.Equal(True, expectedTree.GetRoot().ContainsDiagnostics) Assert.Equal(True, incrementalTree.GetRoot().ContainsDiagnostics) VerifyEquivalent(incrementalTree, expectedTree) End Sub #End Region <WorkItem(543489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543489")> <Fact> Public Sub Bug11296() Dim source As String = <![CDATA[ Module M Sub Main() GoTo 100 Dim Flag1 = 1 If Flag1 = 1 Then Flag1 = 100 Else 100: End If End Sub End Module ]]>.Value Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Assert.Equal(1, oldTree.GetDiagnostics().Count) Assert.Equal("Syntax error.", oldTree.GetDiagnostics()(0).GetMessage(EnsureEnglishUICulture.PreferredOrNull)) Assert.Equal("[131..134)", oldTree.GetDiagnostics()(0).Location.SourceSpan.ToString) ' commenting out the goto Dim pos = source.IndexOf("GoTo 100", StringComparison.Ordinal) Dim newText = oldText.WithChanges(New TextChange(New TextSpan(pos, 0), "'")) Dim newTree = oldTree.WithChangedText(newText) Dim tmpTree = VisualBasicSyntaxTree.ParseText(newText) Assert.Equal(1, tmpTree.GetDiagnostics().Count) Assert.Equal("Syntax error.", tmpTree.GetDiagnostics()(0).GetMessage(EnsureEnglishUICulture.PreferredOrNull)) Assert.Equal("[132..135)", tmpTree.GetDiagnostics()(0).Location.SourceSpan.ToString) End Sub <Fact> Public Sub IncParseTypeNewLine() Dim code As String = (<![CDATA[ Module m Sub s End Sub End Module ]]>).Value IncParseAndVerify(New IncParseNode With { .oldText = code, .changeText = vbCrLf, .changeSpan = New TextSpan(15, 0), .changeType = ChangeType.Insert}) End Sub <WorkItem(545667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545667")> <Fact> Public Sub Bug14266() Dim source = <![CDATA[ Enum E A End Enum ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert a single character at the beginning. Dim newText = oldText.Replace(start:=0, length:=0, newText:="B") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(546680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546680")> <Fact> Public Sub Bug16533() Dim source = <![CDATA[ Module M Sub M() If True Then M() Else : End Sub End Module ]]>.Value Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Replace "True" with "True". Dim str = "True" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:=str) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, oldTree) End Sub <WorkItem(546685, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546685")> <Fact> Public Sub MultiLineIf() Dim source = <![CDATA[ Module M Sub M(b As Boolean) If b Then End If End Sub End Module ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Change "End Module" to "End module". Dim position = oldText.ToString().LastIndexOf("Module", StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=1, newText:="m") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' MultiLineIfBlock should not have been reused. Assert.True(diffs.Any(Function(n) n.IsKind(SyntaxKind.MultiLineIfBlock))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub ''' <summary> ''' Changes before a multi-line If should ''' not affect reuse of the If nodes. ''' </summary> <Fact> Public Sub MultiLineIf_2() Dim source = <![CDATA[ Module M Sub M() Dim b = False b = True If b Then End If End Sub End Module ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Change "False" to "True". Dim position = oldText.ToString().IndexOf("False", StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=5, newText:="True") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' MultiLineIfBlock should have been reused and should not appear in diffs. Assert.False(diffs.Any(Function(n) n.IsKind(SyntaxKind.MultiLineIfBlock))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub ''' <summary> ''' Changes sufficiently far after a multi-line If ''' should not affect reuse of the If nodes. ''' </summary> <Fact> Public Sub MultiLineIf_3() Dim source = <![CDATA[ Module M Sub M(b As Boolean) If b Then End If While b End While End Sub End Module ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Change "End Module" to "End module". Dim position = oldText.ToString().LastIndexOf("Module", StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=1, newText:="m") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' MultiLineIfBlock should have been reused and should not appear in diffs. Assert.False(diffs.Any(Function(n) n.IsKind(SyntaxKind.MultiLineIfBlock))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(546692, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546692")> <Fact> Public Sub Bug16575() Dim source = <![CDATA[ Module M Sub M() If True Then Else Dim x = 1 : Dim y = x If True Then Else Dim x = 1 : Dim y = x End Sub End Module ]]>.Value Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Add newline after first single line If Dim str = "y = x" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) + str.Length Dim newText = oldText.Replace(start:=position, length:=0, newText:=vbCrLf) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(546698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546698")> <Fact> Public Sub Bug16596() Dim source = ToText(<![CDATA[ Module M Sub M() If True Then Dim x = Sub() If True Then Return : 'Else End If End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Uncomment "Else". Dim position = oldText.ToString().IndexOf("'Else", StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=1, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(530662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530662")> <Fact> Public Sub Bug16662() Dim source = ToText(<![CDATA[ Module M Sub M() ''' <[ 1: X End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Remove "X". Dim position = oldText.ToString().IndexOf("X"c) Dim newText = oldText.Replace(start:=position, length:=1, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(546774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546774")> <Fact> Public Sub Bug16786() Dim source = <![CDATA[ Namespace N ''' <summary/> Class A End Class End Namespace Class B End Class Class C End Class ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Append "Class". Dim position = oldText.ToString().Length Dim newText = oldText.Replace(start:=position, length:=0, newText:=vbCrLf & "Class") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' Original Namespace should have been reused. Assert.False(diffs.Any(Function(n) n.IsKind(SyntaxKind.NamespaceBlock))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(530841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530841")> <Fact> Public Sub Bug17031() Dim source = ToText(<![CDATA[ Module M Sub M() If True Then Else End If End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Sub M()" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position + str.Length, length:=0, newText:=vbCrLf) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(531017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531017")> <Fact> Public Sub Bug17409() Dim source = ToText(<![CDATA[ Module M Sub M() Dim ch As Char Dim ch As Char Select Case ch Case "~"c Case Else End Select End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Remove second instance of "Dim ch As Char". Const str = "Dim ch As Char" Dim position = oldText.ToString().LastIndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:=String.Empty) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact, WorkItem(547242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547242")> Public Sub IncParseAddRemoveStopAtAofAs() Dim code As String = <![CDATA[ Module M Public obj0 As Object Public obj1 A]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(code) Dim oldIText = tree.GetText() ' Remove first N characters. Dim span = New TextSpan(0, code.IndexOf("j0", StringComparison.Ordinal)) Dim change = New TextChange(span, "") Dim newIText = oldIText.WithChanges(change) Dim newTree = tree.WithChangedText(newIText) Dim fulltree = VisualBasicSyntaxTree.ParseText(newIText.ToString()) Dim children1 = newTree.GetRoot().ChildNodesAndTokens() Dim children2 = fulltree.GetRoot().ChildNodesAndTokens() Assert.Equal(children2.Count, children1.Count) End Sub <Fact, WorkItem(547242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547242")> Public Sub IncParseAddRemoveStopAtAofAs02() Dim code As String = <![CDATA[ Module M Sub M() Try Catch ex A]]>.Value Dim fullTree = VisualBasicSyntaxTree.ParseText(code) Dim fullText = fullTree.GetText() Dim newTree = fullTree.WithChangedText(fullText) Assert.NotSame(newTree, fullTree) ' Relies on #550027 where WithChangedText returns an instance with changes. Assert.Equal(fullTree.GetRoot().ToFullString(), newTree.GetRoot().ToFullString()) End Sub <Fact, WorkItem(547251, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547251")> Public Sub IncParseAddRemoveStopAtAofPropAs() Dim code As String = <![CDATA[Class C Inherits Attribute ]]>.Value Dim code1 As String = <![CDATA[ Property goo() A]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(code) Dim oldIText = tree.GetText() ' insert code1 after code Dim span = New TextSpan(oldIText.Length, 0) Dim change = New TextChange(span, code1) Dim newIText = oldIText.WithChanges(change) Dim newTree = tree.WithChangedText(newIText) ' remove span = New TextSpan(0, code1.Length) change = New TextChange(span, "") newIText = newIText.WithChanges(change) ' InvalidCastException newTree = newTree.WithChangedText(newIText) Dim fulltree = VisualBasicSyntaxTree.ParseText(newIText.ToString()) Assert.Equal(fulltree.GetRoot().ToFullString(), newTree.GetRoot().ToFullString()) End Sub <Fact, WorkItem(547303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547303")> Public Sub IncParseAddRemoveStopAtTofThen() Dim code As String = <![CDATA[ Module M Sub M() If True Then ElseIf False T]]>.Value Dim fullTree = VisualBasicSyntaxTree.ParseText(code) Dim fullText = fullTree.GetText() Dim newTree = fullTree.WithChangedText(fullText) Assert.NotSame(newTree, fullTree) ' Relies on #550027 where WithChangedText returns an instance with changes. Assert.Equal(fullTree.GetRoot().ToFullString(), newTree.GetRoot().ToFullString()) End Sub <WorkItem(571105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/571105")> <Fact()> Public Sub IncParseInsertLineBreakBeforeLambda() Dim code As String = <![CDATA[ Module M Sub F() Dim a1 = If(Sub() End Sub, Nothing) End Sub End Module]]>.Value Dim tree = VisualBasicSyntaxTree.ParseText(code) Dim oldText = tree.GetText() ' insert line break after '=' Dim span = New TextSpan(code.IndexOf("="c), 0) Dim change = New TextChange(span, vbCrLf) Dim newText = oldText.WithChanges(change) Dim newTree = tree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(578279, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578279")> <Fact()> Public Sub IncParseInsertLineBreakBetweenEndSub() Dim code As String = <![CDATA[Class C Sub M() En Sub Private F = 1 End Class]]>.Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' insert line break Dim position = code.IndexOf("En ", StringComparison.Ordinal) Dim change = New TextChange(New TextSpan(position, 2), "End" + vbCrLf) Dim newText = oldText.WithChanges(change) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact()> Public Sub InsertWithinLookAhead() Dim code As String = <![CDATA[ Module M Function F(s As String) Return From c In s End Function End Module]]>.Value Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert "Select c" at end of method. Dim position = code.IndexOf(" End Function", StringComparison.Ordinal) Dim change = New TextChange(New TextSpan(position, 0), " Select c" + vbCrLf) Dim newText = oldText.WithChanges(change) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub #Region "Async & Iterator" <Fact> Public Sub AsyncToSyncMethod() Dim source = ToText(<![CDATA[ Class C Async Function M(t As Task) As Task Await (t) End Function Function Await(t) Return Nothing End Function End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Async" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub AsyncToSyncLambda() Dim source = ToText(<![CDATA[ Class C Function M(t As Task) Dim lambda = Async Function() Await(t) End Function Function Await(t) Return Nothing End Function End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Async" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub SyncToAsyncMethod() Dim source = ToText(<![CDATA[ Class C Function M(t As Task) As Task Await (t) End Function Function Await(t) Return Nothing End Function End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Function " Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="Async Function ") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub SyncToAsyncLambda() Dim source = ToText(<![CDATA[ Class C Function M(t As Task) Dim lambda = Function() Await(t) End Function Function Await(t) Return Nothing End Function End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Function()" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="Async Function ") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub AsyncToSyncMethodDecl() Dim source = ToText(<![CDATA[ Class C Async Function M(a As Await, t As Task) As Task Await t End Function End Class Class Await End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Async" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub SyncToAsyncMethodDecl() Dim source = ToText(<![CDATA[ Class C Function M(a As Await, t As Task) As Task Await t End Function End Class Class Await End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Function " Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="Async Function ") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IteratorToNonIteratorMethod() Dim source = ToText(<![CDATA[ Module Program Iterator Function Goo() As IEnumerable Yield (1) End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Iterator" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub NonIteratorToIteratorMethod() Dim source = ToText(<![CDATA[ Module Program Function Goo() As IEnumerable Yield (1) End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Function " Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="Iterator Function ") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IteratorToNonIteratorMethodDecl() Dim source = ToText(<![CDATA[ Module Program Iterator Function Goo(Yield As Integer) As IEnumerable Yield (1) End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Iterator" Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub NonIteratorToIteratorMethodDecl() Dim source = ToText(<![CDATA[ Module Program Function Goo(Yield As Integer) As IEnumerable Yield (1) End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Insert blank line at start of method. Dim str = "Function " Dim position = oldText.ToString().IndexOf(str, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=str.Length, newText:="Iterator Function ") Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub #End Region <WorkItem(554442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554442")> <Fact> Public Sub SplitCommentAtPreprocessorSymbol() Dim source = ToText(<![CDATA[ Module M Function F() ' comment # 1 and # 2 ' comment ' comment Return Nothing End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Split comment at "#". Dim position = oldText.ToString().IndexOf("#"c) Dim newText = oldText.Replace(start:=position, length:=0, newText:=vbCrLf) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(586698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/586698")> <Fact> Public Sub SortUsings() Dim oldSource = ToText(<![CDATA[ Imports System.Linq Imports System Imports Microsoft.VisualBasic Module Module1 Sub Main() End Sub End Module ]]>) Dim newSource = ToText(<![CDATA[ Imports System Imports System.Linq Imports Microsoft.VisualBasic Module Module1 Sub Main() End Sub End Module ]]>) Dim oldText = SourceText.From(oldSource) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Changes: ' 1. "" => "System\r\nImports " ' 2. "System\r\nImports " => "" Dim newText = oldText.WithChanges( New TextChange(TextSpan.FromBounds(8, 8), "System" + vbCrLf + "Imports "), New TextChange(TextSpan.FromBounds(29, 45), "")) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub Reformat() Dim oldSource = ToText(<![CDATA[ Class C Sub Method() Dim i = 1 Select Case i Case 1 , 2 , 3 End Select End Sub End Class ]]>) Dim newSource = ToText(<![CDATA[ Class C Sub Method() Dim i = 1 Select Case i Case 1, 2, 3 End Select End Sub End Class ]]>) Dim oldText = SourceText.From(oldSource) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim startOfNew = newSource.IndexOf("Dim", StringComparison.Ordinal) Dim endOfNew = newSource.LastIndexOf("Select", StringComparison.Ordinal) + 6 Dim startOfOld = startOfNew Dim endOfOld = oldSource.Length - newSource.Length + endOfNew Dim newText = oldText.Replace(TextSpan.FromBounds(startOfOld, endOfOld), newSource.Substring(startOfNew, endOfNew - startOfNew + 1)) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(604044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/604044")> <Fact> Public Sub BunchALabels() Dim source = ToText(<![CDATA[ Module Program Sub Main() &HF: &HFF: &HFFF: &HFFFF: &HFFFFF: &HFFFFFF: &HFFFFFFF: &HFFFFFFFF: &HFFFFFFFFF: &HFFFFFFFFFF: End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Add enter after &HFFFFFFFFFF:. Dim position = oldText.ToString().IndexOf("&HFFFFFFFFFF:", StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position + "&HFFFFFFFFFF:".Length, length:=0, newText:=vbCrLf) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(625612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/625612")> <Fact()> Public Sub LabelAfterColon() ' Label following another label on separate lines. LabelAfterColonCore(True, <![CDATA[Module M Sub M() 10: 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) ' Label following another label on separate lines. LabelAfterColonCore(True, <![CDATA[Module M Sub M() 10: : 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) ' Label following on the same line as another label. LabelAfterColonCore(False, <![CDATA[Module M Sub M() 10: 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) ' Label following on the same line as another label. LabelAfterColonCore(False, <![CDATA[Module M Sub M() 10: : 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) ' Label following on the same line as another statement. LabelAfterColonCore(False, <![CDATA[Module M Sub M() M() : 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) ' Label following a colon within a single-line statement. LabelAfterColonCore(False, <![CDATA[Module M Sub M() If True Then M() : 20: 30: 40: 50: 60: 70: End Sub End Module ]]>.Value) End Sub Private Sub LabelAfterColonCore(valid As Boolean, code As String) Dim oldText = SourceText.From(code) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim diagnostics = oldTree.GetDiagnostics() Assert.Equal(valid, diagnostics.Count = 0) ' Replace "70". Dim position = code.IndexOf("70", StringComparison.Ordinal) Dim change = New TextChange(New TextSpan(position, 2), "71") Dim newText = oldText.WithChanges(change) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(529260, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529260")> <Fact()> Public Sub DoNotReuseAnnotatedNodes() Dim text As String = <![CDATA[ Class C End Class Class D End Class ]]>.Value.Replace(vbCr, vbCrLf) ' NOTE: We're using the class statement, rather than the block, because the ' change region is expanded enough to impinge on the block. Dim extractGreenClassC As Func(Of SyntaxTree, Syntax.InternalSyntax.VisualBasicSyntaxNode) = Function(tree) DirectCast(tree.GetRoot().DescendantNodes().First(Function(n) n.IsKind(SyntaxKind.ClassStatement)), VisualBasicSyntaxNode).VbGreen '''''''''' ' Check reuse after a trivial change in an unannotated tree. '''''''''' Dim oldTree1 = VisualBasicSyntaxTree.ParseText(text) Dim newTree1 = oldTree1.WithInsertAt(text.Length, " ") ' Class declaration is reused. Assert.Same(extractGreenClassC(oldTree1), extractGreenClassC(newTree1)) '''''''''' ' Check reuse after a trivial change in an annotated tree. '''''''''' Dim tempTree2 = VisualBasicSyntaxTree.ParseText(text) Dim tempRoot2 = tempTree2.GetRoot() Dim tempToken2 = tempRoot2.DescendantTokens().First(Function(t) t.Kind = SyntaxKind.IdentifierToken) Dim oldRoot2 = tempRoot2.ReplaceToken(tempToken2, tempToken2.WithAdditionalAnnotations(New SyntaxAnnotation())) Assert.True(oldRoot2.ContainsAnnotations, "Should contain annotations.") Assert.Equal(text, oldRoot2.ToFullString()) Dim oldTree2 = VisualBasicSyntaxTree.Create(DirectCast(oldRoot2, VisualBasicSyntaxNode), DirectCast(tempTree2.Options, VisualBasicParseOptions), tempTree2.FilePath, Encoding.UTF8) Dim newTree2 = oldTree2.WithInsertAt(text.Length, " ") Dim oldClassC2 = extractGreenClassC(oldTree2) Dim newClassC2 = extractGreenClassC(newTree2) Assert.True(oldClassC2.ContainsAnnotations, "Should contain annotations") Assert.False(newClassC2.ContainsAnnotations, "Annotations should have been removed.") ' Class declaration is not reused... Assert.NotSame(oldClassC2, newClassC2) ' ...even though the text is the same. Assert.Equal(oldClassC2.ToFullString(), newClassC2.ToFullString()) Dim oldToken2 = DirectCast(oldClassC2, Syntax.InternalSyntax.ClassStatementSyntax).Identifier Dim newToken2 = DirectCast(newClassC2, Syntax.InternalSyntax.ClassStatementSyntax).Identifier Assert.True(oldToken2.ContainsAnnotations, "Should contain annotations") Assert.False(newToken2.ContainsAnnotations, "Annotations should have been removed.") ' Token is not reused... Assert.NotSame(oldToken2, newToken2) ' ...even though the text is the same. Assert.Equal(oldToken2.ToFullString(), newToken2.ToFullString()) End Sub <Fact> Public Sub IncrementalParsing_NamespaceBlock_TryLinkSyntaxMethodsBlock() 'Sub Block 'Function Block 'Property Block Dim source = ToText(<![CDATA[ Namespace N Module M Function F() as Boolean Return True End Function Sub M() End Sub Function Fn() as Boolean Return True End Function Property as Integer = 1 End Module End Namespace ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Module M" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_ExecutableStatementBlock_TryLinkSyntaxClass() 'Class Block Dim source = ToText(<![CDATA[ Module M Sub M() End Sub Dim x = Nothing Public Class C1 End Class Class C2 End Class End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Sub" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_ExecutableStatementBlock_TryLinkSyntaxStructure() 'Structure Block Dim source = ToText(<![CDATA[ Module M Sub M() End Sub Dim x = Nothing Structure S2 1 Dim i as integer End Structure Public Structure S2 Dim i as integer End Structure End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Sub" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact()> Public Sub IncrementalParsing_ExecutableStatementBlock_TryLinkSyntaxOptionStatement() 'Option Statement Dim source = ToText(<![CDATA[ Option Strict Off Option Infer On Option Explicit On ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Sub" Dim TextToAdd As String = "Module Module1" & Environment.NewLine & "Sub Goo()" & Environment.NewLine Dim position = 0 Dim newText = oldText.Replace(start:=position, length:=1, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact()> Public Sub IncrementalParsing_ExecutableStatementBlock_TryLinkSyntaxImports() 'Imports Statement Dim source = ToText(<![CDATA[ Imports System Imports System.Collections Imports Microsoft.Visualbasic ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Sub" Dim TextToAdd As String = "Module Module1" & Environment.NewLine & "Sub Goo()" & Environment.NewLine Dim position = 0 Dim newText = oldText.Replace(start:=position, length:=1, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_ExecutableStatementBlock_TryLinkSyntaxDelegateSub() 'ExecutableStatementBlock -> DelegateSub Dim source = ToText(<![CDATA[ Module Module1 Sub Main() End Sub Dim x = Nothing Delegate Sub Goo() Public Delegate Sub GooWithModifier() End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Sub" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxOperatorBlock() Dim source = ToText(<![CDATA[ Module Module1 Sub Main() Dim x As New SomeClass Dim y As Boolean = -x End Sub Class SomeClass Dim member As Long = 2 Public Overloads Shared Operator -(ByVal value As SomeClass) As Boolean If value.member Mod 5 = 0 Then Return True End If Return False End Operator End Class End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Class SomeClass" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxEventBlock() Dim source = ToText(<![CDATA[ Module Module1 Sub Main() End Sub Class SomeClass Dim member As Long = 2 Public Custom Event AnyName As EventHandler AddHandler(ByVal value As EventHandler) End AddHandler RemoveHandler(ByVal value As EventHandler) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) End RaiseEvent End Event End Class End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Class SomeClass" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxPropertyBlock() Dim source = ToText(<![CDATA[ Module Module1 Sub Main() End Sub Class SomeClass Dim member As Long = 2 Public Property abc As Integer Set(value As Integer) End Set Get End Get End Property End Class End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Class SomeClass" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxNamespaceModuleBlock() Dim source = ToText(<![CDATA[ Namespace NS1 Module Module1 Sub Goo() End Sub Dim x End Module 'Remove Namespace vs End Namespace Module Module1 Dim x End Module End Namespace ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Module 'Remove" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxNamespaceNamespaceBlock() Dim source = ToText(<![CDATA[ Namespace NS1 Module Module1 Sub Goo() End Sub Dim x End Module 'Remove Namespace vs Namespace vs2 End Namespace End Namespace Namespace vs3 End Namespace End Namespace ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Module 'Remove" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_DeclarationContextBlock_TryLinkSyntaxItems() Dim source = ToText(<![CDATA[ Class SomeClass Dim member As Long = 2 Sub abc() 'Remove Dim xyz as integer = 2 IF member = 1 then Console.writeline("TEST"); Dim SingleLineDeclare as integer = 2 End Sub Dim member2 As Long = 2 Dim member3 As Long = 2 Enum EnumItem Item1 End Enum End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Sub abc() 'Remove" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_PropertyContextBlock_TryLinkSyntaxSetAccessor() 'PropertyContextBlock -> SetAccessor Dim source = ToText(<![CDATA[ Class C Private _p As Integer = 0 Property p2 As Integer Set(value As Integer) End Set Get End Get End Property Private _d As Integer = 1 End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Property" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_BlockContext_TryLinkSyntaxSelectBlock() Dim source = ToText(<![CDATA[ Module Module1 Private _p As Integer = 0 Sub Bar() End Sub Function Goo(i As Integer) As Integer Dim y As Integer = i Select Case y Case 1 Case 2, 3 Case Else End Select Return y + 1 Try Catch ex As exception End Try If y = 1 Then Console.WriteLine("Test") Y = 1 While y <= 10 y = y + 1 End While Using f As New Goo End Using Dim Obj_C As New OtherClass With Obj_C End With SyncLock Obj_C End SyncLock Select Case y Case 10 Case Else End Select y = 0 Do y = y + 1 If y >= 3 Then Exit Do Loop y = 0 Do While y < 4 y = y + 1 Loop y = 0 Do Until y > 5 y = y + 1 Loop End Function End Module Class Goo Implements IDisposable #Region "IDisposable Support" Private disposedValue As Boolean ' To detect redundant calls ' IDisposable Protected Overridable Sub Dispose(disposing As Boolean) If Not Me.disposedValue Then If disposing Then End If End If Me.disposedValue = True End Sub Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub #End Region End Class Class OtherClass End Class ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Select" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_EventBlockContext_TryLinkSyntax1() Dim source = ToText(<![CDATA[ Module Module1 Public Custom Event AnyName As EventHandler AddHandler(ByVal value As EventHandler) _P = 1 End AddHandler RemoveHandler(ByVal value As EventHandler) _P = 2 End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) _P = 3 End RaiseEvent End Event Private _p As Integer = 0 Sub Main() End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "RemoveHandler(ByVal value As EventHandler)" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_EventBlockContext_TryLinkSyntax2() Dim source = ToText(<![CDATA[ Module Module1 Public Custom Event AnyName As EventHandler AddHandler(ByVal value As EventHandler) _P = 1 End AddHandler RemoveHandler(ByVal value As EventHandler) _P = 2 End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) _P = 3 _P = _P +1 End RaiseEvent End Event Private _p As Integer = 0 Sub Main() End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "_P = 3" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_InterfaceBlockContext_TryLinkSyntaxClass() Dim source = ToText(<![CDATA[ Module Module1 Sub Main() End Sub Interface IGoo End Interface Dim _p Class C End Class End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Interface" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_InterfaceBlockContext_TryLinkSyntaxEnum() Dim source = ToText(<![CDATA[ Module Module1 Sub Main() End Sub Interface IGoo End Interface Dim _p Public Enum TestEnum Item End Enum End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "End Interface" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_CaseBlockContext_TryLinkSyntaxCase() Dim source = ToText(<![CDATA[ Module Module1 Sub Goo() Dim i As Integer Dim y As Integer Select Case i Case 1 _p = 1 Case 2, 3 _p = 2 Case Else _p = 3 End Select End Sub Private _p As Integer = 0 Sub Main() End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Case 2, 3" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_CatchContext_TryLinkSyntaxCatch() Dim source = ToText(<![CDATA[ Module Module1 Sub Goo() Dim x1 As Integer = 1 Try x1 = 2 Catch ex As NullReferenceException Dim z = 1 Catch ex As ArgumentException 'Remove Dim z = 1 Catch ex As Exception _p = 3 Dim s = Bar() Finally _p = 4 End Try End Sub Private _p As Integer = 0 Function Bar() As String End Function End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Catch ex As ArgumentException 'Remove" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact()> Public Sub IncrementalParsing_NamespaceBlockContext_TryLinkSyntaxModule() Dim source = ToText(<![CDATA[ Namespace NS1 Module ModuleTemp 'Remove End Module Module Module1 'Remove Sub Goo() Dim x1 As Integer = 1 End Sub Private _p As Integer = 0 Function Bar() As String End Function End Module End Namespace ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "Module ModuleTemp 'Remove" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <Fact> Public Sub IncrementalParsing_IfBlockContext_TryLinkSyntax() Dim source = ToText(<![CDATA[ Module Module1 Private _p As Integer = 0 Sub Goo() If x = 1 Then _p=1 elseIf x = 2 Then _p=2 elseIf x = 3 Then _p=3 else If y = 1 Then _p=2 End If End If End Sub End Module ]]>) Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim TextToRemove As String = "elseIf x = 2 Then" Dim TextToAdd As String = "" Dim position = oldText.ToString.IndexOf(TextToRemove, StringComparison.Ordinal) Dim newText = oldText.Replace(start:=position, length:=TextToRemove.Length, newText:=TextToAdd) Dim newTree = oldTree.WithChangedText(newText) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(719787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/719787")> <Fact()> Public Sub Bug719787_EOF() Dim source = <![CDATA[ Namespace N Class C Property P As Integer End Class Structure S Private F As Object End Structure End Namespace ]]>.Value.Trim() ' Add two line breaks at end. source += vbCrLf Dim position = source.Length source += vbCrLf Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) ' Add "Delegate" to end of file between line breaks. Dim newText = oldText.Replace(start:=position, length:=0, newText:="Delegate") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' Most of the Namespace should have been reused. Assert.False(diffs.Any(Function(n) n.IsKind(SyntaxKind.StructureStatement))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub <WorkItem(719787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/719787")> <Fact> Public Sub Bug719787_MultiLineIf() Dim source = <![CDATA[ Class C Sub M() If e1 Then If e2 Then M11() Else M12() End If ElseIf e2 Then If e2 Then M21() Else M22() End If ElseIf e3 Then If e2 Then M31() Else M32() End If ElseIf e4 Then If e2 Then M41() Else M42() End If Else If e2 Then M51() Else M52() End If End If End Sub ' Comment End Class ]]>.Value.Trim() Dim oldText = SourceText.From(source) Dim oldTree = VisualBasicSyntaxTree.ParseText(oldText) Dim toReplace = "' Comment" Dim position = source.IndexOf(toReplace, StringComparison.Ordinal) ' Replace "' Comment" with "Property" Dim newText = oldText.Replace(start:=position, length:=toReplace.Length, newText:="Property") Dim newTree = oldTree.WithChangedText(newText) Dim diffs = SyntaxDifferences.GetRebuiltNodes(oldTree, newTree) ' The ElseIfBlocks should have been reused. Assert.False(diffs.Any(Function(n) n.IsKind(SyntaxKind.ElseIfBlock))) VerifyEquivalent(newTree, VisualBasicSyntaxTree.ParseText(newText)) End Sub #Region "Helpers" Private Shared Function GetTokens(root As SyntaxNode) As InternalSyntax.VisualBasicSyntaxNode() Return root.DescendantTokens().Select(Function(t) DirectCast(t.Node, InternalSyntax.VisualBasicSyntaxNode)).ToArray() End Function Private Shared Sub VerifyTokensEquivalent(rootA As SyntaxNode, rootB As SyntaxNode) Dim tokensA = GetTokens(rootA) Dim tokensB = GetTokens(rootB) Assert.Equal(tokensA.Count, tokensB.Count) For i = 0 To tokensA.Count - 1 Dim tokenA = tokensA(i) Dim tokenB = tokensB(i) Assert.Equal(tokenA.Kind, tokenB.Kind) Assert.Equal(tokenA.ToFullString(), tokenB.ToFullString()) Next End Sub Private Shared Sub VerifyEquivalent(treeA As SyntaxTree, treeB As SyntaxTree) Dim rootA = treeA.GetRoot() Dim rootB = treeB.GetRoot() VerifyTokensEquivalent(rootA, rootB) Dim diagnosticsA = treeA.GetDiagnostics() Dim diagnosticsB = treeB.GetDiagnostics() Assert.True(rootA.IsEquivalentTo(rootB)) Assert.Equal(diagnosticsA.Count, diagnosticsB.Count) For i = 0 To diagnosticsA.Count - 1 Assert.Equal(diagnosticsA(i).Inspect(), diagnosticsB(i).Inspect()) Next End Sub Private Shared Function ToText(code As XCData) As String Dim str = code.Value.Trim() ' Normalize line terminators. Dim builder = ArrayBuilder(Of Char).GetInstance() For i = 0 To str.Length - 1 Dim c = str(i) If (c = vbLf(0)) AndAlso ((i = str.Length - 1) OrElse (str(i + 1) <> vbCr(0))) Then builder.AddRange(vbCrLf) Else builder.Add(c) End If Next Return New String(builder.ToArrayAndFree()) End Function #End Region End Class
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicErrorListDesktop.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicErrorListDesktop : BasicErrorListCommon { public BasicErrorListDesktop(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, WellKnownProjectTemplates.ClassLibrary) { } [WpfFact, Trait(Traits.Feature, Traits.Features.ErrorList)] public override void ErrorList() { base.ErrorList(); } [WpfFact, Trait(Traits.Feature, Traits.Features.ErrorList)] public override void ErrorsDuringMethodBodyEditing() { base.ErrorsDuringMethodBodyEditing(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicErrorListDesktop : BasicErrorListCommon { public BasicErrorListDesktop(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, WellKnownProjectTemplates.ClassLibrary) { } [WpfFact, Trait(Traits.Feature, Traits.Features.ErrorList)] public override void ErrorList() { base.ErrorList(); } [WpfFact, Trait(Traits.Feature, Traits.Features.ErrorList)] public override void ErrorsDuringMethodBodyEditing() { base.ErrorsDuringMethodBodyEditing(); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/EditorFeatures/CSharpTest2/Recommendations/IntoKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class IntoKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInSelectMemberExpressionOnlyADot() { await VerifyAbsenceAsync(AddInsideMethod( @"var y = from x in new [] { 1,2,3 } select x.$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInSelectMemberExpression() { await VerifyAbsenceAsync(AddInsideMethod( @"var y = from x in new [] { 1,2,3 } select x.i$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterJoinRightExpr() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from x in y join a in e on o1 equals o2 $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterJoinRightExpr_NotAfterInto() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y join a.b c in o1 equals o2 into $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterEquals() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y join a.b c in o1 equals $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSelectClause() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from x in y select z $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSelectClauseWithMemberExpression() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from x in y select z.i $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSelectClause_NotAfterInto() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y select z into $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGroupClause() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from x in y group z by w $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGroupClause_NotAfterInto() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y group z by w into $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSelect() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y select $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGroupKeyword() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y group $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGroupExpression() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y group x $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGroupBy() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y group x by $$")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class IntoKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInSelectMemberExpressionOnlyADot() { await VerifyAbsenceAsync(AddInsideMethod( @"var y = from x in new [] { 1,2,3 } select x.$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInSelectMemberExpression() { await VerifyAbsenceAsync(AddInsideMethod( @"var y = from x in new [] { 1,2,3 } select x.i$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterJoinRightExpr() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from x in y join a in e on o1 equals o2 $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterJoinRightExpr_NotAfterInto() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y join a.b c in o1 equals o2 into $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterEquals() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y join a.b c in o1 equals $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSelectClause() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from x in y select z $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSelectClauseWithMemberExpression() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from x in y select z.i $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSelectClause_NotAfterInto() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y select z into $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGroupClause() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from x in y group z by w $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGroupClause_NotAfterInto() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y group z by w into $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSelect() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y select $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGroupKeyword() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y group $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGroupExpression() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y group x $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGroupBy() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y group x by $$")); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Expressions/GetXmlNamespaceKeywordRecommender.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Expressions ''' <summary> ''' Recommends the "GetXmlNamespace" keyword. ''' </summary> Friend Class GetXmlNamespaceKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.IsAnyExpressionContext Then Return ImmutableArray.Create( CreateRecommendedKeywordForIntrinsicOperator(SyntaxKind.GetXmlNamespaceKeyword, VBFeaturesResources.GetXmlNamespace_function, Glyph.MethodPublic, New GetXmlNamespaceExpressionDocumentation(), context.SemanticModel, context.Position)) End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Expressions ''' <summary> ''' Recommends the "GetXmlNamespace" keyword. ''' </summary> Friend Class GetXmlNamespaceKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.IsAnyExpressionContext Then Return ImmutableArray.Create( CreateRecommendedKeywordForIntrinsicOperator(SyntaxKind.GetXmlNamespaceKeyword, VBFeaturesResources.GetXmlNamespace_function, Glyph.MethodPublic, New GetXmlNamespaceExpressionDocumentation(), context.SemanticModel, context.Position)) End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./docs/wiki/images/how-to-investigate-ci-test-failures-figure15.png
PNG  IHDR2hd$sRGBgAMA a pHYsodtEXtSoftwarepaint.net 4.1.6N IDATx^흿k\G_l+CY\DBFB̒l\B,)Lj@"\Va úú1+B`0rb .Ò8o93g93s^I<Wx33gfkWKL?K[P#`Kjl @-%5F[P#`Kjl @-%5F.o[ƭ[Qo&%zo@ &iRk0uk7/ܚLFڭ ڰԸ~kݨ brF޹5nyd,ؖ-֓FoϏiEH5;-&Çۭ[Q7/z{Wxߺd%ed7ҝқ}{и }\9R ގ=ɖhw8 4#J;xoG'jl p2ٶ}JqV9+Rშ$lCklޏ3۽\6$Qw-GUvZfh|>8qXGTovt^5;o@D-z0|Myf4;#M6Pj~]9iLGZ'G{rv2ܻƩhn>-X1yZ_[T~Pfӆ5ҽq2:ݴ|~$I}rrme2Zor]_7 sr{{V|fC]*:ye)N,ޖ%KjzxZZ٩CL-m?mjx=<ܖ>Gf460iRGCh_l''-w;TӸ~}F.[K{dI}ӗa .`sȻ|unE$J讦эy@>;4oɕ]Ut. `KfJy֖suX3eI대n=$K),7Lgn7[7}wn>XQ7YjVZ qRX:8xfGg^x-ڢ'YxK^3|4tDjY;mވvp+} [~? ?9X&m;T>epZ<?<{"b 6PN[hW.Q.xQݛ?eQbeՁ:ᷴ4+n.bK|B;%<罶ֵ%Pq!iK|E߁tr[+í[{͟GTP2F۴j4u/-. Mٖ&m?6Boc{-d*PDdeujf;]׍qEL<g|noo)*cu~) |lu<7!7'3=~]Ė7É2Jl)x*& R4:t.hWz:=+|D"f~wu?A;uD%[ Y|i Jxds1jIu'(t>ُwɛqzt8=nYk_ks6*wuqrB1wf"MI}060~šㆍj8Ls%>]s[m_9,R mw+4?.HS>ok57oۇ'%.4E1wa[ ĺ-5ᢋᱜ"\MܖOno6gC_veG̎o5<{#uԡrY)Պppy9/[tyTp'B˖O4A1n8lcsyzdM fKI77ْ QÏ"[Z^e/GOSā2TYn҄ki [OT;bfC gb&-z"gfdDU<m=-ɛ\v͖ܜvOkS2Ey+)C: |l-%#b'%1\Z-MXdKA%ߗ#YiLݰnɞ͌JS^cH<1;]hy?쵕%j xpy9?[whz7"&͖/~$pcy L6f<[rV~-l ~+ERv_D+>g #,:%[ΪIlx\gyAa=ے!չdDhc2st|/6&ߎD@}4 %+q׾FX/pϦwRW(g:S/dg̽Zb!%tF@N7g17ndV|Kq G+zY`v)Q#ꙏ}g>GcB_wѳw/~M/;ƽolw+POOKk=sN/@=v w8ܜ-yI2Ŀ0$T:7<-'߼ȏt\mR~]46zΞ 찛R ,;m)VM'!u:ʹ}=>(ƠI<ٹKsÀXz- U;[bsRGfnv{2fKYFM Ͷy"ljnVbq⼞wْ)ͿA "[:.h8M{?yؒAEc?'͵;ޡ>d]J?$sz*~gX#އ~0q[˙?wA?&QYo3vb|ZvZKՂfܭWcYZp`ĿTt̆yMF#S~0ZRy9kSz>N^6È@ۭIf6N^ZM|xe өʿYN^Κ'bJs\iKW*[P#`Kjl _KKXvqlH*K7Ll '?  l + l W'%(%PO`K\Q`K@=-pE-z[[jڒ_N˯'[ֶ49Bl-pO_Z>zVWbS%*N~74L,xMgjbig>,N[|XYiŵW&m;yILe5V= 1K**rqoKSۉﳥ,0TE.cd<4Τ#L멻}sqj?,kkI;7U+. +R)HdfFOf4:""BHWB+,: usdq!N^aՄS{aC.-نLƖ^hB6 ܴON:9\+WZe3Hd%AYg%Z$ӱ -UU5h(5C U–:'m) kl-D-itQ-CuUն3cJ--s'v}"w)0r"P H͔g%>mKr}6TrΕ"D4 mҤZ-Jq&je5B ?T<b2.-Q=:t#I2%?5@:Ą22gO1nJ*FgMM=/bp춚n:+*VS/U [J4S\Y`K%LL%Shhk<UD}NoD)cZH%Q8air9zkb:xl=M%-Pi$Z`PkJ $&JͫC3C[JUogEaVP g1#%N4qc+?ƄϋIt`-z}d` I!9O[)|H%e奢iя"?5Y SuE6MC$d| d>Õq%uŐ-tWe@&$NΘOR6{uFN~'CZs%jVD3e;ycC7;SJT)R X:3XEf='렛-6 Q JI+I8Y0ql=MY@[KAZ.-Gr=p 9>\$!Xє@$M YRT@x!6$ʊCȘA0rY2!UhM,9fgl7C(ʹ ZR$a*<xn4$$z2|t 7Ui 7tZYl5H e]NSU21 (PQ\+ANJO>Tݖ أD>AUKUQvOyծ8f ûQY&t>L3=eR!+P[VEC!9Gc.х@b\&eBˇ2̥'V)[쁱jq"UDТW;ڇ6I5Z돰_rl4i9EQ-+ԟj7 Ncuh5Պsؙ3# S`B=c ђ7(1@jv+<$SyasttUkl)UG+%IuLM V[Je'=|*ےORXsʼ̖vKQPEhIvPg<Hڄ5ZDŦt(G;MT1);T?nTHr^E[J6D/\ۼ yD—ͻSfh;+c 3z$(;sYPʵ1DkrGr ϼlr2[E"4bڒl&QrXheQ."m)PJ>B;G*(}v!84H\k &|S[z\(KD0/D"[t6L 3R:sK<[JPmɬRdKf:e>xMwNESY&+j(.N(+e#R*bdTvXu0N`2K,3DXP4HEklҸD\3a1VѿXrY/ 6 QK>ʠuqFxleu&BG bf<3-9vmC{ۮ eSDkv:AM+;Yv7&$:ԖT/4XS jKbfr$rB*6))#:eo/,Ga4T"8<\$VՂ5ٷž̖g8 gpSne+>ےu^ 5V돺=HԻvTMhnE+ɃxN Bkhzg?泌O*h7 Z2Zv#UMȷU@ DUƪBrͱ;V;n)*L$^GT 2e VpXUA5g^X[2p s#Ɓ9 VFd>jv!FAJNs JEӡ 2NjUe[CSA dŦE؄(𵥅7n6%.Q79RC8weŕ[J 7-?qaKJ_"[d֒4lIL,\[sz ZF2tC Šz$!e`^ul3`MO"(+y˒;vDrږp8[rj'YP RtS[`\[TN l Erul)|w`A,p@`K\Q`K@=-pE-z[[ l +XsqlH*K7Ll @-%5F[P#`Kjl @-%5F[P#`Kjl @-?0[rӲ[o ,'YĿӲ[GpV[J;l YX-eJ%gd1do%篿w( ˿IENDB`
PNG  IHDR2hd$sRGBgAMA a pHYsodtEXtSoftwarepaint.net 4.1.6N IDATx^흿k\G_l+CY\DBFB̒l\B,)Lj@"\Va úú1+B`0rb .Ò8o93g93s^I<Wx33gfkWKL?K[P#`Kjl @-%5F[P#`Kjl @-%5F.o[ƭ[Qo&%zo@ &iRk0uk7/ܚLFڭ ڰԸ~kݨ brF޹5nyd,ؖ-֓FoϏiEH5;-&Çۭ[Q7/z{Wxߺd%ed7ҝқ}{и }\9R ގ=ɖhw8 4#J;xoG'jl p2ٶ}JqV9+Rშ$lCklޏ3۽\6$Qw-GUvZfh|>8qXGTovt^5;o@D-z0|Myf4;#M6Pj~]9iLGZ'G{rv2ܻƩhn>-X1yZ_[T~Pfӆ5ҽq2:ݴ|~$I}rrme2Zor]_7 sr{{V|fC]*:ye)N,ޖ%KjzxZZ٩CL-m?mjx=<ܖ>Gf460iRGCh_l''-w;TӸ~}F.[K{dI}ӗa .`sȻ|unE$J讦эy@>;4oɕ]Ut. `KfJy֖suX3eI대n=$K),7Lgn7[7}wn>XQ7YjVZ qRX:8xfGg^x-ڢ'YxK^3|4tDjY;mވvp+} [~? ?9X&m;T>epZ<?<{"b 6PN[hW.Q.xQݛ?eQbeՁ:ᷴ4+n.bK|B;%<罶ֵ%Pq!iK|E߁tr[+í[{͟GTP2F۴j4u/-. Mٖ&m?6Boc{-d*PDdeujf;]׍qEL<g|noo)*cu~) |lu<7!7'3=~]Ė7É2Jl)x*& R4:t.hWz:=+|D"f~wu?A;uD%[ Y|i Jxds1jIu'(t>ُwɛqzt8=nYk_ks6*wuqrB1wf"MI}060~šㆍj8Ls%>]s[m_9,R mw+4?.HS>ok57oۇ'%.4E1wa[ ĺ-5ᢋᱜ"\MܖOno6gC_veG̎o5<{#uԡrY)Պppy9/[tyTp'B˖O4A1n8lcsyzdM fKI77ْ QÏ"[Z^e/GOSā2TYn҄ki [OT;bfC gb&-z"gfdDU<m=-ɛ\v͖ܜvOkS2Ey+)C: |l-%#b'%1\Z-MXdKA%ߗ#YiLݰnɞ͌JS^cH<1;]hy?쵕%j xpy9?[whz7"&͖/~$pcy L6f<[rV~-l ~+ERv_D+>g #,:%[ΪIlx\gyAa=ے!չdDhc2st|/6&ߎD@}4 %+q׾FX/pϦwRW(g:S/dg̽Zb!%tF@N7g17ndV|Kq G+zY`v)Q#ꙏ}g>GcB_wѳw/~M/;ƽolw+POOKk=sN/@=v w8ܜ-yI2Ŀ0$T:7<-'߼ȏt\mR~]46zΞ 찛R ,;m)VM'!u:ʹ}=>(ƠI<ٹKsÀXz- U;[bsRGfnv{2fKYFM Ͷy"ljnVbq⼞wْ)ͿA "[:.h8M{?yؒAEc?'͵;ޡ>d]J?$sz*~gX#އ~0q[˙?wA?&QYo3vb|ZvZKՂfܭWcYZp`ĿTt̆yMF#S~0ZRy9kSz>N^6È@ۭIf6N^ZM|xe өʿYN^Κ'bJs\iKW*[P#`Kjl _KKXvqlH*K7Ll '?  l + l W'%(%PO`K\Q`K@=-pE-z[[jڒ_N˯'[ֶ49Bl-pO_Z>zVWbS%*N~74L,xMgjbig>,N[|XYiŵW&m;yILe5V= 1K**rqoKSۉﳥ,0TE.cd<4Τ#L멻}sqj?,kkI;7U+. +R)HdfFOf4:""BHWB+,: usdq!N^aՄS{aC.-نLƖ^hB6 ܴON:9\+WZe3Hd%AYg%Z$ӱ -UU5h(5C U–:'m) kl-D-itQ-CuUն3cJ--s'v}"w)0r"P H͔g%>mKr}6TrΕ"D4 mҤZ-Jq&je5B ?T<b2.-Q=:t#I2%?5@:Ą22gO1nJ*FgMM=/bp춚n:+*VS/U [J4S\Y`K%LL%Shhk<UD}NoD)cZH%Q8air9zkb:xl=M%-Pi$Z`PkJ $&JͫC3C[JUogEaVP g1#%N4qc+?ƄϋIt`-z}d` I!9O[)|H%e奢iя"?5Y SuE6MC$d| d>Õq%uŐ-tWe@&$NΘOR6{uFN~'CZs%jVD3e;ycC7;SJT)R X:3XEf='렛-6 Q JI+I8Y0ql=MY@[KAZ.-Gr=p 9>\$!Xє@$M YRT@x!6$ʊCȘA0rY2!UhM,9fgl7C(ʹ ZR$a*<xn4$$z2|t 7Ui 7tZYl5H e]NSU21 (PQ\+ANJO>Tݖ أD>AUKUQvOyծ8f ûQY&t>L3=eR!+P[VEC!9Gc.х@b\&eBˇ2̥'V)[쁱jq"UDТW;ڇ6I5Z돰_rl4i9EQ-+ԟj7 Ncuh5Պsؙ3# S`B=c ђ7(1@jv+<$SyasttUkl)UG+%IuLM V[Je'=|*ےORXsʼ̖vKQPEhIvPg<Hڄ5ZDŦt(G;MT1);T?nTHr^E[J6D/\ۼ yD—ͻSfh;+c 3z$(;sYPʵ1DkrGr ϼlr2[E"4bڒl&QrXheQ."m)PJ>B;G*(}v!84H\k &|S[z\(KD0/D"[t6L 3R:sK<[JPmɬRdKf:e>xMwNESY&+j(.N(+e#R*bdTvXu0N`2K,3DXP4HEklҸD\3a1VѿXrY/ 6 QK>ʠuqFxleu&BG bf<3-9vmC{ۮ eSDkv:AM+;Yv7&$:ԖT/4XS jKbfr$rB*6))#:eo/,Ga4T"8<\$VՂ5ٷž̖g8 gpSne+>ےu^ 5V돺=HԻvTMhnE+ɃxN Bkhzg?泌O*h7 Z2Zv#UMȷU@ DUƪBrͱ;V;n)*L$^GT 2e VpXUA5g^X[2p s#Ɓ9 VFd>jv!FAJNs JEӡ 2NjUe[CSA dŦE؄(𵥅7n6%.Q79RC8weŕ[J 7-?qaKJ_"[d֒4lIL,\[sz ZF2tC Šz$!e`^ul3`MO"(+y˒;vDrږp8[rj'YP RtS[`\[TN l Erul)|w`A,p@`K\Q`K@=-pE-z[[ l +XsqlH*K7Ll @-%5F[P#`Kjl @-%5F[P#`Kjl @-?0[rӲ[o ,'YĿӲ[GpV[J;l YX-eJ%gd1do%篿w( ˿IENDB`
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/Core/Portable/CodeGen/LambdaDebugInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGen { /// <summary> /// Debug information maintained for each lambda. /// </summary> /// <remarks> /// The information is emitted to PDB in Custom Debug Information record for a method containing the lambda. /// </remarks> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal struct LambdaDebugInfo : IEquatable<LambdaDebugInfo> { /// <summary> /// The syntax offset of the syntax node declaring the lambda (lambda expression) or its body (lambda in a query). /// </summary> public readonly int SyntaxOffset; /// <summary> /// The ordinal of the closure frame the lambda belongs to, or /// <see cref="StaticClosureOrdinal"/> if the lambda is static, or /// <see cref="ThisOnlyClosureOrdinal"/> if the lambda is closed over "this" pointer only. /// </summary> public readonly int ClosureOrdinal; public readonly DebugId LambdaId; public const int StaticClosureOrdinal = -1; public const int ThisOnlyClosureOrdinal = -2; public const int MinClosureOrdinal = ThisOnlyClosureOrdinal; public LambdaDebugInfo(int syntaxOffset, DebugId lambdaId, int closureOrdinal) { Debug.Assert(closureOrdinal >= MinClosureOrdinal); SyntaxOffset = syntaxOffset; ClosureOrdinal = closureOrdinal; LambdaId = lambdaId; } public bool Equals(LambdaDebugInfo other) { return SyntaxOffset == other.SyntaxOffset && ClosureOrdinal == other.ClosureOrdinal && LambdaId.Equals(other.LambdaId); } public override bool Equals(object? obj) { return obj is LambdaDebugInfo && Equals((LambdaDebugInfo)obj); } public override int GetHashCode() { return Hash.Combine(ClosureOrdinal, Hash.Combine(SyntaxOffset, LambdaId.GetHashCode())); } internal string GetDebuggerDisplay() { return ClosureOrdinal == StaticClosureOrdinal ? $"({LambdaId.GetDebuggerDisplay()} @{SyntaxOffset}, static)" : ClosureOrdinal == ThisOnlyClosureOrdinal ? $"(#{LambdaId.GetDebuggerDisplay()} @{SyntaxOffset}, this)" : $"({LambdaId.GetDebuggerDisplay()} @{SyntaxOffset} in {ClosureOrdinal})"; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGen { /// <summary> /// Debug information maintained for each lambda. /// </summary> /// <remarks> /// The information is emitted to PDB in Custom Debug Information record for a method containing the lambda. /// </remarks> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal struct LambdaDebugInfo : IEquatable<LambdaDebugInfo> { /// <summary> /// The syntax offset of the syntax node declaring the lambda (lambda expression) or its body (lambda in a query). /// </summary> public readonly int SyntaxOffset; /// <summary> /// The ordinal of the closure frame the lambda belongs to, or /// <see cref="StaticClosureOrdinal"/> if the lambda is static, or /// <see cref="ThisOnlyClosureOrdinal"/> if the lambda is closed over "this" pointer only. /// </summary> public readonly int ClosureOrdinal; public readonly DebugId LambdaId; public const int StaticClosureOrdinal = -1; public const int ThisOnlyClosureOrdinal = -2; public const int MinClosureOrdinal = ThisOnlyClosureOrdinal; public LambdaDebugInfo(int syntaxOffset, DebugId lambdaId, int closureOrdinal) { Debug.Assert(closureOrdinal >= MinClosureOrdinal); SyntaxOffset = syntaxOffset; ClosureOrdinal = closureOrdinal; LambdaId = lambdaId; } public bool Equals(LambdaDebugInfo other) { return SyntaxOffset == other.SyntaxOffset && ClosureOrdinal == other.ClosureOrdinal && LambdaId.Equals(other.LambdaId); } public override bool Equals(object? obj) { return obj is LambdaDebugInfo && Equals((LambdaDebugInfo)obj); } public override int GetHashCode() { return Hash.Combine(ClosureOrdinal, Hash.Combine(SyntaxOffset, LambdaId.GetHashCode())); } internal string GetDebuggerDisplay() { return ClosureOrdinal == StaticClosureOrdinal ? $"({LambdaId.GetDebuggerDisplay()} @{SyntaxOffset}, static)" : ClosureOrdinal == ThisOnlyClosureOrdinal ? $"(#{LambdaId.GetDebuggerDisplay()} @{SyntaxOffset}, this)" : $"({LambdaId.GetDebuggerDisplay()} @{SyntaxOffset} in {ClosureOrdinal})"; } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/VisualStudio/Core/Def/Implementation/Utilities/ComEventSink.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.VisualStudio.OLE.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal sealed class ComEventSink { public static ComEventSink Advise<T>(object obj, T sink) where T : class { if (!typeof(T).IsInterface) { throw new InvalidOperationException(); } if (!(obj is IConnectionPointContainer connectionPointContainer)) { throw new ArgumentException("Not an IConnectionPointContainer", nameof(obj)); } connectionPointContainer.FindConnectionPoint(typeof(T).GUID, out var connectionPoint); if (connectionPoint == null) { throw new InvalidOperationException("Could not find connection point for " + typeof(T).FullName); } connectionPoint.Advise(sink, out var cookie); return new ComEventSink(connectionPoint, cookie); } private readonly IConnectionPoint _connectionPoint; private readonly uint _cookie; private bool _unadvised; public ComEventSink(IConnectionPoint connectionPoint, uint cookie) { _connectionPoint = connectionPoint; _cookie = cookie; } public void Unadvise() { if (_unadvised) { throw new InvalidOperationException("Already unadvised."); } _connectionPoint.Unadvise(_cookie); _unadvised = true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.VisualStudio.OLE.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal sealed class ComEventSink { public static ComEventSink Advise<T>(object obj, T sink) where T : class { if (!typeof(T).IsInterface) { throw new InvalidOperationException(); } if (!(obj is IConnectionPointContainer connectionPointContainer)) { throw new ArgumentException("Not an IConnectionPointContainer", nameof(obj)); } connectionPointContainer.FindConnectionPoint(typeof(T).GUID, out var connectionPoint); if (connectionPoint == null) { throw new InvalidOperationException("Could not find connection point for " + typeof(T).FullName); } connectionPoint.Advise(sink, out var cookie); return new ComEventSink(connectionPoint, cookie); } private readonly IConnectionPoint _connectionPoint; private readonly uint _cookie; private bool _unadvised; public ComEventSink(IConnectionPoint connectionPoint, uint cookie) { _connectionPoint = connectionPoint; _cookie = cookie; } public void Unadvise() { if (_unadvised) { throw new InvalidOperationException("Already unadvised."); } _connectionPoint.Unadvise(_cookie); _unadvised = true; } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/EditorFeatures/CSharpTest/CommentSelection/CSharpCommentSelectionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CommentSelection { [UseExportProvider] public class CSharpCommentSelectionTests { [WpfFact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void UncommentAndFormat1() { var code = @"class A { [| // void Method ( ) // { // // }|] }"; var expected = @"class A { void Method() { } }"; UncommentSelection(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void UncommentAndFormat2() { var code = @"class A { [| /* void Method ( ) { } */|] }"; var expected = @"class A { void Method() { } }"; UncommentSelection(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void UncommentSingleLineCommentInPseudoBlockComment() { var code = @" class C { /// <include file='doc\Control.uex' path='docs/doc[@for=""Control.RtlTranslateAlignment1""]/*' /> protected void RtlTranslateAlignment2() { //[|int x = 0;|] } /* Hello world */ }"; var expected = @" class C { /// <include file='doc\Control.uex' path='docs/doc[@for=""Control.RtlTranslateAlignment1""]/*' /> protected void RtlTranslateAlignment2() { int x = 0; } /* Hello world */ }"; UncommentSelection(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void UncommentAndFormat3() { var code = @"class A { [| // void Method ( ) |] [| // { |] [| // |] [| // } |] }"; var expected = @"class A { void Method() { } }"; UncommentSelection(code, expected); } private static void UncommentSelection(string markup, string expected) { using var workspace = TestWorkspace.CreateCSharp(markup); var doc = workspace.Documents.First(); SetupSelection(doc.GetTextView(), doc.SelectedSpans.Select(s => Span.FromBounds(s.Start, s.End))); var commandHandler = new CommentUncommentSelectionCommandHandler( workspace.ExportProvider.GetExportedValue<ITextUndoHistoryRegistry>(), workspace.ExportProvider.GetExportedValue<IEditorOperationsFactoryService>()); var textView = doc.GetTextView(); var textBuffer = doc.GetTextBuffer(); commandHandler.ExecuteCommand(textView, textBuffer, Operation.Uncomment, TestCommandExecutionContext.Create()); Assert.Equal(expected, doc.GetTextBuffer().CurrentSnapshot.GetText()); } private static void SetupSelection(IWpfTextView textView, IEnumerable<Span> spans) { var snapshot = textView.TextSnapshot; if (spans.Count() == 1) { textView.Selection.Select(new SnapshotSpan(snapshot, spans.Single()), isReversed: false); textView.Caret.MoveTo(new SnapshotPoint(snapshot, spans.Single().End)); } else { textView.Selection.Mode = TextSelectionMode.Box; textView.Selection.Select(new VirtualSnapshotPoint(snapshot, spans.First().Start), new VirtualSnapshotPoint(snapshot, spans.Last().End)); textView.Caret.MoveTo(new SnapshotPoint(snapshot, spans.Last().End)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Implementation.CommentSelection; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CommentSelection { [UseExportProvider] public class CSharpCommentSelectionTests { [WpfFact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void UncommentAndFormat1() { var code = @"class A { [| // void Method ( ) // { // // }|] }"; var expected = @"class A { void Method() { } }"; UncommentSelection(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void UncommentAndFormat2() { var code = @"class A { [| /* void Method ( ) { } */|] }"; var expected = @"class A { void Method() { } }"; UncommentSelection(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void UncommentSingleLineCommentInPseudoBlockComment() { var code = @" class C { /// <include file='doc\Control.uex' path='docs/doc[@for=""Control.RtlTranslateAlignment1""]/*' /> protected void RtlTranslateAlignment2() { //[|int x = 0;|] } /* Hello world */ }"; var expected = @" class C { /// <include file='doc\Control.uex' path='docs/doc[@for=""Control.RtlTranslateAlignment1""]/*' /> protected void RtlTranslateAlignment2() { int x = 0; } /* Hello world */ }"; UncommentSelection(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.CommentSelection)] public void UncommentAndFormat3() { var code = @"class A { [| // void Method ( ) |] [| // { |] [| // |] [| // } |] }"; var expected = @"class A { void Method() { } }"; UncommentSelection(code, expected); } private static void UncommentSelection(string markup, string expected) { using var workspace = TestWorkspace.CreateCSharp(markup); var doc = workspace.Documents.First(); SetupSelection(doc.GetTextView(), doc.SelectedSpans.Select(s => Span.FromBounds(s.Start, s.End))); var commandHandler = new CommentUncommentSelectionCommandHandler( workspace.ExportProvider.GetExportedValue<ITextUndoHistoryRegistry>(), workspace.ExportProvider.GetExportedValue<IEditorOperationsFactoryService>()); var textView = doc.GetTextView(); var textBuffer = doc.GetTextBuffer(); commandHandler.ExecuteCommand(textView, textBuffer, Operation.Uncomment, TestCommandExecutionContext.Create()); Assert.Equal(expected, doc.GetTextBuffer().CurrentSnapshot.GetText()); } private static void SetupSelection(IWpfTextView textView, IEnumerable<Span> spans) { var snapshot = textView.TextSnapshot; if (spans.Count() == 1) { textView.Selection.Select(new SnapshotSpan(snapshot, spans.Single()), isReversed: false); textView.Caret.MoveTo(new SnapshotPoint(snapshot, spans.Single().End)); } else { textView.Selection.Mode = TextSelectionMode.Box; textView.Selection.Select(new VirtualSnapshotPoint(snapshot, spans.First().Start), new VirtualSnapshotPoint(snapshot, spans.Last().End)); textView.Caret.MoveTo(new SnapshotPoint(snapshot, spans.Last().End)); } } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Features/Core/Portable/Completion/Providers/Scripting/GlobalAssemblyCacheCompletionHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal sealed class GlobalAssemblyCacheCompletionHelper { private static readonly Lazy<List<string>> s_lazyAssemblySimpleNames = new(() => GlobalAssemblyCache.Instance.GetAssemblySimpleNames().ToList()); private readonly CompletionItemRules _itemRules; public GlobalAssemblyCacheCompletionHelper(CompletionItemRules itemRules) { Debug.Assert(itemRules != null); _itemRules = itemRules; } public Task<ImmutableArray<CompletionItem>> GetItemsAsync(string directoryPath, CancellationToken cancellationToken) => Task.Run(() => GetItems(directoryPath, cancellationToken)); // internal for testing internal ImmutableArray<CompletionItem> GetItems(string directoryPath, CancellationToken cancellationToken) { using var resultDisposer = ArrayBuilder<CompletionItem>.GetInstance(out var result); var comma = directoryPath.IndexOf(','); if (comma >= 0) { var partialName = directoryPath.Substring(0, comma); foreach (var identity in GetAssemblyIdentities(partialName)) { result.Add(CommonCompletionItem.Create( identity.GetDisplayName(), displayTextSuffix: "", glyph: Glyph.Assembly, rules: _itemRules)); } } else { foreach (var displayName in s_lazyAssemblySimpleNames.Value) { cancellationToken.ThrowIfCancellationRequested(); result.Add(CommonCompletionItem.Create( displayName, displayTextSuffix: "", glyph: Glyph.Assembly, rules: _itemRules)); } } return result.ToImmutable(); } private static IEnumerable<AssemblyIdentity> GetAssemblyIdentities(string partialName) { return IOUtilities.PerformIO(() => GlobalAssemblyCache.Instance.GetAssemblyIdentities(partialName), SpecializedCollections.EmptyEnumerable<AssemblyIdentity>()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal sealed class GlobalAssemblyCacheCompletionHelper { private static readonly Lazy<List<string>> s_lazyAssemblySimpleNames = new(() => GlobalAssemblyCache.Instance.GetAssemblySimpleNames().ToList()); private readonly CompletionItemRules _itemRules; public GlobalAssemblyCacheCompletionHelper(CompletionItemRules itemRules) { Debug.Assert(itemRules != null); _itemRules = itemRules; } public Task<ImmutableArray<CompletionItem>> GetItemsAsync(string directoryPath, CancellationToken cancellationToken) => Task.Run(() => GetItems(directoryPath, cancellationToken)); // internal for testing internal ImmutableArray<CompletionItem> GetItems(string directoryPath, CancellationToken cancellationToken) { using var resultDisposer = ArrayBuilder<CompletionItem>.GetInstance(out var result); var comma = directoryPath.IndexOf(','); if (comma >= 0) { var partialName = directoryPath.Substring(0, comma); foreach (var identity in GetAssemblyIdentities(partialName)) { result.Add(CommonCompletionItem.Create( identity.GetDisplayName(), displayTextSuffix: "", glyph: Glyph.Assembly, rules: _itemRules)); } } else { foreach (var displayName in s_lazyAssemblySimpleNames.Value) { cancellationToken.ThrowIfCancellationRequested(); result.Add(CommonCompletionItem.Create( displayName, displayTextSuffix: "", glyph: Glyph.Assembly, rules: _itemRules)); } } return result.ToImmutable(); } private static IEnumerable<AssemblyIdentity> GetAssemblyIdentities(string partialName) { return IOUtilities.PerformIO(() => GlobalAssemblyCache.Instance.GetAssemblyIdentities(partialName), SpecializedCollections.EmptyEnumerable<AssemblyIdentity>()); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/CSharp/Test/Syntax/Parsing/LanguageVersionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class LanguageVersionTests { [Fact] public void CurrentVersion() { var highest = Enum. GetValues(typeof(LanguageVersion)). Cast<LanguageVersion>(). Where(x => x != LanguageVersion.Latest && x != LanguageVersion.Preview && x != LanguageVersion.LatestMajor). Max(); Assert.Equal(LanguageVersionFacts.CurrentVersion, highest); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class LanguageVersionTests { [Fact] public void CurrentVersion() { var highest = Enum. GetValues(typeof(LanguageVersion)). Cast<LanguageVersion>(). Where(x => x != LanguageVersion.Latest && x != LanguageVersion.Preview && x != LanguageVersion.LatestMajor). Max(); Assert.Equal(LanguageVersionFacts.CurrentVersion, highest); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/VisualBasic/Portable/BoundTree/BoundMethodGroup.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports System.Runtime.InteropServices Imports System.Threading Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundMethodGroup Public Sub New( syntax As SyntaxNode, typeArgumentsOpt As BoundTypeArguments, methods As ImmutableArray(Of MethodSymbol), resultKind As LookupResultKind, receiverOpt As BoundExpression, qualificationKind As QualificationKind, Optional hasErrors As Boolean = False ) Me.New(syntax, typeArgumentsOpt, methods, Nothing, resultKind, receiverOpt, qualificationKind, hasErrors) End Sub ' Lazily filled once the value is requested. Public Function AdditionalExtensionMethods(<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As ImmutableArray(Of MethodSymbol) If _PendingExtensionMethodsOpt Is Nothing Then Return ImmutableArray(Of MethodSymbol).Empty End If Return _PendingExtensionMethodsOpt.LazyLookupAdditionalExtensionMethods(Me, useSiteInfo) End Function End Class Friend Class ExtensionMethodGroup Private ReadOnly _lookupBinder As Binder Private ReadOnly _lookupOptions As LookupOptions Private ReadOnly _withDependencies As Boolean Private _lazyMethods As ImmutableArray(Of MethodSymbol) Private _lazyUseSiteDiagnostics As IReadOnlyCollection(Of DiagnosticInfo) Private _lazyUseSiteDependencies As IReadOnlyCollection(Of AssemblySymbol) Public Sub New(lookupBinder As Binder, lookupOptions As LookupOptions, withDependencies As Boolean) Debug.Assert(lookupBinder IsNot Nothing) _lookupBinder = lookupBinder _lookupOptions = lookupOptions _withDependencies = withDependencies End Sub Public Function LazyLookupAdditionalExtensionMethods(group As BoundMethodGroup, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As ImmutableArray(Of MethodSymbol) Debug.Assert(group.PendingExtensionMethodsOpt Is Me) Debug.Assert(Not useSiteInfo.AccumulatesDependencies OrElse _withDependencies) If _lazyMethods.IsDefault Then Dim receiverOpt As BoundExpression = group.ReceiverOpt Dim methods As ImmutableArray(Of MethodSymbol) = ImmutableArray(Of MethodSymbol).Empty Dim localUseSiteInfo = If(_withDependencies, New CompoundUseSiteInfo(Of AssemblySymbol)(_lookupBinder.Compilation.Assembly), CompoundUseSiteInfo(Of AssemblySymbol).DiscardedDependencies) If receiverOpt IsNot Nothing AndAlso receiverOpt.Type IsNot Nothing Then Dim lookup = LookupResult.GetInstance() _lookupBinder.LookupExtensionMethods(lookup, receiverOpt.Type, group.Methods(0).Name, If(group.TypeArgumentsOpt Is Nothing, 0, group.TypeArgumentsOpt.Arguments.Length), _lookupOptions, localUseSiteInfo) If lookup.IsGood Then methods = lookup.Symbols.ToDowncastedImmutable(Of MethodSymbol)() End If lookup.Free() End If Interlocked.CompareExchange(_lazyUseSiteDiagnostics, localUseSiteInfo.Diagnostics, Nothing) Interlocked.CompareExchange(_lazyUseSiteDependencies, If(localUseSiteInfo.AccumulatesDependencies, localUseSiteInfo.Dependencies, Nothing), Nothing) ImmutableInterlocked.InterlockedCompareExchange(_lazyMethods, methods, Nothing) End If useSiteInfo.AddDiagnostics(System.Threading.Volatile.Read(_lazyUseSiteDiagnostics)) useSiteInfo.AddDependencies(System.Threading.Volatile.Read(_lazyUseSiteDependencies)) Return _lazyMethods End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports System.Runtime.InteropServices Imports System.Threading Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundMethodGroup Public Sub New( syntax As SyntaxNode, typeArgumentsOpt As BoundTypeArguments, methods As ImmutableArray(Of MethodSymbol), resultKind As LookupResultKind, receiverOpt As BoundExpression, qualificationKind As QualificationKind, Optional hasErrors As Boolean = False ) Me.New(syntax, typeArgumentsOpt, methods, Nothing, resultKind, receiverOpt, qualificationKind, hasErrors) End Sub ' Lazily filled once the value is requested. Public Function AdditionalExtensionMethods(<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As ImmutableArray(Of MethodSymbol) If _PendingExtensionMethodsOpt Is Nothing Then Return ImmutableArray(Of MethodSymbol).Empty End If Return _PendingExtensionMethodsOpt.LazyLookupAdditionalExtensionMethods(Me, useSiteInfo) End Function End Class Friend Class ExtensionMethodGroup Private ReadOnly _lookupBinder As Binder Private ReadOnly _lookupOptions As LookupOptions Private ReadOnly _withDependencies As Boolean Private _lazyMethods As ImmutableArray(Of MethodSymbol) Private _lazyUseSiteDiagnostics As IReadOnlyCollection(Of DiagnosticInfo) Private _lazyUseSiteDependencies As IReadOnlyCollection(Of AssemblySymbol) Public Sub New(lookupBinder As Binder, lookupOptions As LookupOptions, withDependencies As Boolean) Debug.Assert(lookupBinder IsNot Nothing) _lookupBinder = lookupBinder _lookupOptions = lookupOptions _withDependencies = withDependencies End Sub Public Function LazyLookupAdditionalExtensionMethods(group As BoundMethodGroup, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As ImmutableArray(Of MethodSymbol) Debug.Assert(group.PendingExtensionMethodsOpt Is Me) Debug.Assert(Not useSiteInfo.AccumulatesDependencies OrElse _withDependencies) If _lazyMethods.IsDefault Then Dim receiverOpt As BoundExpression = group.ReceiverOpt Dim methods As ImmutableArray(Of MethodSymbol) = ImmutableArray(Of MethodSymbol).Empty Dim localUseSiteInfo = If(_withDependencies, New CompoundUseSiteInfo(Of AssemblySymbol)(_lookupBinder.Compilation.Assembly), CompoundUseSiteInfo(Of AssemblySymbol).DiscardedDependencies) If receiverOpt IsNot Nothing AndAlso receiverOpt.Type IsNot Nothing Then Dim lookup = LookupResult.GetInstance() _lookupBinder.LookupExtensionMethods(lookup, receiverOpt.Type, group.Methods(0).Name, If(group.TypeArgumentsOpt Is Nothing, 0, group.TypeArgumentsOpt.Arguments.Length), _lookupOptions, localUseSiteInfo) If lookup.IsGood Then methods = lookup.Symbols.ToDowncastedImmutable(Of MethodSymbol)() End If lookup.Free() End If Interlocked.CompareExchange(_lazyUseSiteDiagnostics, localUseSiteInfo.Diagnostics, Nothing) Interlocked.CompareExchange(_lazyUseSiteDependencies, If(localUseSiteInfo.AccumulatesDependencies, localUseSiteInfo.Dependencies, Nothing), Nothing) ImmutableInterlocked.InterlockedCompareExchange(_lazyMethods, methods, Nothing) End If useSiteInfo.AddDiagnostics(System.Threading.Volatile.Read(_lazyUseSiteDiagnostics)) useSiteInfo.AddDependencies(System.Threading.Volatile.Read(_lazyUseSiteDependencies)) Return _lazyMethods End Function End Class End Namespace
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/VisualBasic/Portable/SourceGeneration/VisualBasicGeneratorDriver.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 Imports System.Threading Imports Microsoft.CodeAnalysis.Diagnostics Namespace Microsoft.CodeAnalysis.VisualBasic Public Class VisualBasicGeneratorDriver Inherits GeneratorDriver Private Sub New(state As GeneratorDriverState) MyBase.New(state) End Sub Friend Sub New(parseOptions As VisualBasicParseOptions, generators As ImmutableArray(Of ISourceGenerator), optionsProvider As AnalyzerConfigOptionsProvider, additionalTexts As ImmutableArray(Of AdditionalText), driverOptions As GeneratorDriverOptions) MyBase.New(parseOptions, generators, optionsProvider, additionalTexts, driverOptions) End Sub Friend Overrides ReadOnly Property MessageProvider As CommonMessageProvider Get Return VisualBasic.MessageProvider.Instance End Get End Property Friend Overrides Function FromState(state As GeneratorDriverState) As GeneratorDriver Return New VisualBasicGeneratorDriver(state) End Function Friend Overrides Function ParseGeneratedSourceText(input As GeneratedSourceText, fileName As String, cancellationToken As CancellationToken) As SyntaxTree Return VisualBasicSyntaxTree.ParseTextLazy(input.Text, CType(_state.ParseOptions, VisualBasicParseOptions), fileName) End Function Public Shared Function Create(generators As ImmutableArray(Of ISourceGenerator), Optional additionalTexts As ImmutableArray(Of AdditionalText) = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider = Nothing, Optional driverOptions As GeneratorDriverOptions = Nothing) As VisualBasicGeneratorDriver Return New VisualBasicGeneratorDriver(parseOptions, generators, If(analyzerConfigOptionsProvider, CompilerAnalyzerConfigOptionsProvider.Empty), additionalTexts.NullToEmpty(), driverOptions) End Function ' 3.11 BACK COMPAT OVERLOAD -- DO NOT TOUCH <EditorBrowsable(EditorBrowsableState.Never)> Public Shared Function Create(generators As ImmutableArray(Of ISourceGenerator), additionalTexts As ImmutableArray(Of AdditionalText), parseOptions As VisualBasicParseOptions, analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider) As VisualBasicGeneratorDriver Return Create(generators, additionalTexts, parseOptions, analyzerConfigOptionsProvider, driverOptions:=Nothing) End Function Friend Overrides Function CreateSourcesCollection() As AdditionalSourcesCollection Return New AdditionalSourcesCollection(".vb") 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.ComponentModel Imports System.Threading Imports Microsoft.CodeAnalysis.Diagnostics Namespace Microsoft.CodeAnalysis.VisualBasic Public Class VisualBasicGeneratorDriver Inherits GeneratorDriver Private Sub New(state As GeneratorDriverState) MyBase.New(state) End Sub Friend Sub New(parseOptions As VisualBasicParseOptions, generators As ImmutableArray(Of ISourceGenerator), optionsProvider As AnalyzerConfigOptionsProvider, additionalTexts As ImmutableArray(Of AdditionalText), driverOptions As GeneratorDriverOptions) MyBase.New(parseOptions, generators, optionsProvider, additionalTexts, driverOptions) End Sub Friend Overrides ReadOnly Property MessageProvider As CommonMessageProvider Get Return VisualBasic.MessageProvider.Instance End Get End Property Friend Overrides Function FromState(state As GeneratorDriverState) As GeneratorDriver Return New VisualBasicGeneratorDriver(state) End Function Friend Overrides Function ParseGeneratedSourceText(input As GeneratedSourceText, fileName As String, cancellationToken As CancellationToken) As SyntaxTree Return VisualBasicSyntaxTree.ParseTextLazy(input.Text, CType(_state.ParseOptions, VisualBasicParseOptions), fileName) End Function Public Shared Function Create(generators As ImmutableArray(Of ISourceGenerator), Optional additionalTexts As ImmutableArray(Of AdditionalText) = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider = Nothing, Optional driverOptions As GeneratorDriverOptions = Nothing) As VisualBasicGeneratorDriver Return New VisualBasicGeneratorDriver(parseOptions, generators, If(analyzerConfigOptionsProvider, CompilerAnalyzerConfigOptionsProvider.Empty), additionalTexts.NullToEmpty(), driverOptions) End Function ' 3.11 BACK COMPAT OVERLOAD -- DO NOT TOUCH <EditorBrowsable(EditorBrowsableState.Never)> Public Shared Function Create(generators As ImmutableArray(Of ISourceGenerator), additionalTexts As ImmutableArray(Of AdditionalText), parseOptions As VisualBasicParseOptions, analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider) As VisualBasicGeneratorDriver Return Create(generators, additionalTexts, parseOptions, analyzerConfigOptionsProvider, driverOptions:=Nothing) End Function Friend Overrides Function CreateSourcesCollection() As AdditionalSourcesCollection Return New AdditionalSourcesCollection(".vb") End Function End Class End Namespace
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Workspaces/CSharp/Portable/Workspace/LanguageServices/CSharpSyntaxTreeFactoryService.PositionalSyntaxReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal partial class CSharpSyntaxTreeFactoryServiceFactory { private partial class CSharpSyntaxTreeFactoryService { /// <summary> /// Represents a syntax reference that doesn't actually hold onto the /// referenced node. Instead, enough data is held onto so that the node /// can be recovered and returned if necessary. /// </summary> private class PositionalSyntaxReference : SyntaxReference { private readonly SyntaxKind _kind; public PositionalSyntaxReference(SyntaxNode node) { SyntaxTree = node.SyntaxTree; Span = node.Span; _kind = node.Kind(); System.Diagnostics.Debug.Assert(Span.Length > 0); } public override SyntaxTree SyntaxTree { get; } public override TextSpan Span { get; } public override SyntaxNode GetSyntax(CancellationToken cancellationToken) { // Find our node going down in the tree. // Try not going deeper than needed. return this.GetNode(SyntaxTree.GetRoot(cancellationToken)); } public override async Task<SyntaxNode> GetSyntaxAsync(CancellationToken cancellationToken = default) { var root = await SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); return this.GetNode(root); } private SyntaxNode GetNode(SyntaxNode root) { var current = root; var spanStart = Span.Start; while (current.FullSpan.Contains(spanStart)) { if (current.Kind() == _kind && current.Span == Span) { return current; } var nodeOrToken = current.ChildThatContainsPosition(spanStart); // we have got a token. It means that the node is in structured trivia if (nodeOrToken.IsToken) { return GetNodeInStructuredTrivia(current); } current = nodeOrToken.AsNode(); } throw new InvalidOperationException("reference to a node that does not exist?"); } private SyntaxNode GetNodeInStructuredTrivia(SyntaxNode parent) { // Syntax references to nonterminals in structured trivia should be uncommon. // Provide more efficient implementation if that is not true var descendantsIntersectingSpan = parent.DescendantNodes(Span, descendIntoTrivia: true); return descendantsIntersectingSpan.First(node => node.IsKind(_kind) && node.Span == Span); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal partial class CSharpSyntaxTreeFactoryServiceFactory { private partial class CSharpSyntaxTreeFactoryService { /// <summary> /// Represents a syntax reference that doesn't actually hold onto the /// referenced node. Instead, enough data is held onto so that the node /// can be recovered and returned if necessary. /// </summary> private class PositionalSyntaxReference : SyntaxReference { private readonly SyntaxKind _kind; public PositionalSyntaxReference(SyntaxNode node) { SyntaxTree = node.SyntaxTree; Span = node.Span; _kind = node.Kind(); System.Diagnostics.Debug.Assert(Span.Length > 0); } public override SyntaxTree SyntaxTree { get; } public override TextSpan Span { get; } public override SyntaxNode GetSyntax(CancellationToken cancellationToken) { // Find our node going down in the tree. // Try not going deeper than needed. return this.GetNode(SyntaxTree.GetRoot(cancellationToken)); } public override async Task<SyntaxNode> GetSyntaxAsync(CancellationToken cancellationToken = default) { var root = await SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); return this.GetNode(root); } private SyntaxNode GetNode(SyntaxNode root) { var current = root; var spanStart = Span.Start; while (current.FullSpan.Contains(spanStart)) { if (current.Kind() == _kind && current.Span == Span) { return current; } var nodeOrToken = current.ChildThatContainsPosition(spanStart); // we have got a token. It means that the node is in structured trivia if (nodeOrToken.IsToken) { return GetNodeInStructuredTrivia(current); } current = nodeOrToken.AsNode(); } throw new InvalidOperationException("reference to a node that does not exist?"); } private SyntaxNode GetNodeInStructuredTrivia(SyntaxNode parent) { // Syntax references to nonterminals in structured trivia should be uncommon. // Provide more efficient implementation if that is not true var descendantsIntersectingSpan = parent.DescendantNodes(Span, descendIntoTrivia: true); return descendantsIntersectingSpan.First(node => node.IsKind(_kind) && node.Span == Span); } } } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Features/Core/Portable/TodoComments/AbstractTodoCommentsIncrementalAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.TodoComments; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.CodeAnalysis.TodoComments { internal abstract partial class AbstractTodoCommentsIncrementalAnalyzer : IncrementalAnalyzerBase { private readonly object _gate = new(); private string? _lastOptionText = null; private ImmutableArray<TodoCommentDescriptor> _lastDescriptors = default; /// <summary> /// Set of documents that we have reported an non-empty set of todo comments for. Used so that we don't bother /// notifying the host about documents with empty-todo lists (the common case). Note: no locking is needed for /// this set as the incremental analyzer is guaranteed to make all calls sequentially to us. /// </summary> private readonly HashSet<DocumentId> _documentsWithTodoComments = new(); protected AbstractTodoCommentsIncrementalAnalyzer() { } protected abstract ValueTask ReportTodoCommentDataAsync(DocumentId documentId, ImmutableArray<TodoCommentData> data, CancellationToken cancellationToken); public override bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) => e.Option == TodoCommentOptions.TokenList; public override Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) { // Remove the doc id from what we're tracking to prevent unbounded growth in the set. // If the doc that is being removed is not in the set of docs we've told the host has todo comments, // then no need to notify the host at all about it. if (!_documentsWithTodoComments.Remove(documentId)) return Task.CompletedTask; // Otherwise, report that there should now be no todo comments for this doc. return ReportTodoCommentDataAsync(documentId, ImmutableArray<TodoCommentData>.Empty, cancellationToken).AsTask(); } private ImmutableArray<TodoCommentDescriptor> GetTodoCommentDescriptors(Document document) { var optionText = document.Project.Solution.Options.GetOption<string>(TodoCommentOptions.TokenList); lock (_gate) { if (optionText != _lastOptionText) { _lastDescriptors = TodoCommentDescriptor.Parse(optionText); _lastOptionText = optionText; } return _lastDescriptors; } } public override async Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken) { var todoCommentService = document.GetLanguageService<ITodoCommentService>(); if (todoCommentService == null) return; var descriptors = GetTodoCommentDescriptors(document); // We're out of date. Recompute this info. var todoComments = await todoCommentService.GetTodoCommentsAsync( document, descriptors, cancellationToken).ConfigureAwait(false); // Convert the roslyn-level results to the more VS oriented line/col data. using var _ = ArrayBuilder<TodoCommentData>.GetInstance(out var converted); await TodoComment.ConvertAsync( document, todoComments, converted, cancellationToken).ConfigureAwait(false); var data = converted.ToImmutable(); if (data.IsEmpty) { // Remove this doc from the set of docs with todo comments in it. If this was a doc that previously // had todo comments in it, then fall through and notify the host so it can clear them out. // Otherwise, bail out as there's no need to inform the host of this. if (!_documentsWithTodoComments.Remove(document.Id)) return; } else { // Doc has some todo comments, record that, and let the host know. _documentsWithTodoComments.Add(document.Id); } // Now inform VS about this new information await ReportTodoCommentDataAsync(document.Id, data, 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. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.TodoComments; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.CodeAnalysis.TodoComments { internal abstract partial class AbstractTodoCommentsIncrementalAnalyzer : IncrementalAnalyzerBase { private readonly object _gate = new(); private string? _lastOptionText = null; private ImmutableArray<TodoCommentDescriptor> _lastDescriptors = default; /// <summary> /// Set of documents that we have reported an non-empty set of todo comments for. Used so that we don't bother /// notifying the host about documents with empty-todo lists (the common case). Note: no locking is needed for /// this set as the incremental analyzer is guaranteed to make all calls sequentially to us. /// </summary> private readonly HashSet<DocumentId> _documentsWithTodoComments = new(); protected AbstractTodoCommentsIncrementalAnalyzer() { } protected abstract ValueTask ReportTodoCommentDataAsync(DocumentId documentId, ImmutableArray<TodoCommentData> data, CancellationToken cancellationToken); public override bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) => e.Option == TodoCommentOptions.TokenList; public override Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) { // Remove the doc id from what we're tracking to prevent unbounded growth in the set. // If the doc that is being removed is not in the set of docs we've told the host has todo comments, // then no need to notify the host at all about it. if (!_documentsWithTodoComments.Remove(documentId)) return Task.CompletedTask; // Otherwise, report that there should now be no todo comments for this doc. return ReportTodoCommentDataAsync(documentId, ImmutableArray<TodoCommentData>.Empty, cancellationToken).AsTask(); } private ImmutableArray<TodoCommentDescriptor> GetTodoCommentDescriptors(Document document) { var optionText = document.Project.Solution.Options.GetOption<string>(TodoCommentOptions.TokenList); lock (_gate) { if (optionText != _lastOptionText) { _lastDescriptors = TodoCommentDescriptor.Parse(optionText); _lastOptionText = optionText; } return _lastDescriptors; } } public override async Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken) { var todoCommentService = document.GetLanguageService<ITodoCommentService>(); if (todoCommentService == null) return; var descriptors = GetTodoCommentDescriptors(document); // We're out of date. Recompute this info. var todoComments = await todoCommentService.GetTodoCommentsAsync( document, descriptors, cancellationToken).ConfigureAwait(false); // Convert the roslyn-level results to the more VS oriented line/col data. using var _ = ArrayBuilder<TodoCommentData>.GetInstance(out var converted); await TodoComment.ConvertAsync( document, todoComments, converted, cancellationToken).ConfigureAwait(false); var data = converted.ToImmutable(); if (data.IsEmpty) { // Remove this doc from the set of docs with todo comments in it. If this was a doc that previously // had todo comments in it, then fall through and notify the host so it can clear them out. // Otherwise, bail out as there's no need to inform the host of this. if (!_documentsWithTodoComments.Remove(document.Id)) return; } else { // Doc has some todo comments, record that, and let the host know. _documentsWithTodoComments.Add(document.Id); } // Now inform VS about this new information await ReportTodoCommentDataAsync(document.Id, data, cancellationToken).ConfigureAwait(false); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenForeach.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenForeach Inherits BasicTestBase ' The loop object must be an array or an object collection <Fact> Public Sub SimpleForeachTest() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C Shared Sub Main() Dim arr As String() = New String(1) {} arr(0) = "one" arr(1) = "two" For Each s As String In arr Console.WriteLine(s) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ one two ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 46 (0x2e) .maxstack 4 .locals init (String() V_0, Integer V_1) IL_0000: ldc.i4.2 IL_0001: newarr "String" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldstr "one" IL_000d: stelem.ref IL_000e: dup IL_000f: ldc.i4.1 IL_0010: ldstr "two" IL_0015: stelem.ref IL_0016: stloc.0 IL_0017: ldc.i4.0 IL_0018: stloc.1 IL_0019: br.s IL_0027 IL_001b: ldloc.0 IL_001c: ldloc.1 IL_001d: ldelem.ref IL_001e: call "Sub System.Console.WriteLine(String)" IL_0023: ldloc.1 IL_0024: ldc.i4.1 IL_0025: add.ovf IL_0026: stloc.1 IL_0027: ldloc.1 IL_0028: ldloc.0 IL_0029: ldlen IL_002a: conv.i4 IL_002b: blt.s IL_001b IL_002d: ret } ]]>).Compilation End Sub ' Type is not required in a foreach statement <Fact> Public Sub TypeIsNotRequiredTest() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System Class C Shared Sub Main() Dim myarray As Integer() = New Integer(2) {1, 2, 3} For Each item In myarray Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithModuleName("MODULE")).VerifyIL("C.Main", <![CDATA[ { // Code size 37 (0x25) .maxstack 3 .locals init (Integer() V_0, Integer V_1) IL_0000: ldc.i4.3 IL_0001: newarr "Integer" IL_0006: dup IL_0007: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D" IL_000c: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)" IL_0011: stloc.0 IL_0012: ldc.i4.0 IL_0013: stloc.1 IL_0014: br.s IL_001e IL_0016: ldloc.0 IL_0017: ldloc.1 IL_0018: ldelem.i4 IL_0019: pop IL_001a: ldloc.1 IL_001b: ldc.i4.1 IL_001c: add.ovf IL_001d: stloc.1 IL_001e: ldloc.1 IL_001f: ldloc.0 IL_0020: ldlen IL_0021: conv.i4 IL_0022: blt.s IL_0016 IL_0024: ret } ]]>) End Sub ' Narrowing conversions from the elements in group to element are evaluated and performed at run time <Fact> Public Sub NarrowConversions() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Class C Shared Sub Main() For Each number As Integer In New Long() {45, 3} Console.WriteLine(number) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 45 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 42 (0x2a) .maxstack 4 .locals init (Long() V_0, Integer V_1) IL_0000: ldc.i4.2 IL_0001: newarr "Long" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 45 IL_000a: conv.i8 IL_000b: stelem.i8 IL_000c: dup IL_000d: ldc.i4.1 IL_000e: ldc.i4.3 IL_000f: conv.i8 IL_0010: stelem.i8 IL_0011: stloc.0 IL_0012: ldc.i4.0 IL_0013: stloc.1 IL_0014: br.s IL_0023 IL_0016: ldloc.0 IL_0017: ldloc.1 IL_0018: ldelem.i8 IL_0019: conv.ovf.i4 IL_001a: call "Sub System.Console.WriteLine(Integer)" IL_001f: ldloc.1 IL_0020: ldc.i4.1 IL_0021: add.ovf IL_0022: stloc.1 IL_0023: ldloc.1 IL_0024: ldloc.0 IL_0025: ldlen IL_0026: conv.i4 IL_0027: blt.s IL_0016 IL_0029: ret } ]]>) End Sub ' Narrowing conversions from the elements in group to element are evaluated and performed at run time <Fact> Public Sub NarrowConversions_2() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Class C Shared Sub Main() For Each number As Integer In New Long() {9876543210} Console.WriteLine(number) Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 43 (0x2b) .maxstack 4 .locals init (Long() V_0, Integer V_1) IL_0000: ldc.i4.1 IL_0001: newarr "Long" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i8 0x24cb016ea IL_0011: stelem.i8 IL_0012: stloc.0 IL_0013: ldc.i4.0 IL_0014: stloc.1 IL_0015: br.s IL_0024 IL_0017: ldloc.0 IL_0018: ldloc.1 IL_0019: ldelem.i8 IL_001a: conv.ovf.i4 IL_001b: call "Sub System.Console.WriteLine(Integer)" IL_0020: ldloc.1 IL_0021: ldc.i4.1 IL_0022: add.ovf IL_0023: stloc.1 IL_0024: ldloc.1 IL_0025: ldloc.0 IL_0026: ldlen IL_0027: conv.i4 IL_0028: blt.s IL_0017 IL_002a: ret } ]]>) End Sub ' Multiline <Fact> Public Sub Multiline() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Class C Shared Public Sub Main() Dim a() As Integer = New Integer() {7} For Each x As Integer In a : System.Console.WriteLine(x) : Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 34 (0x22) .maxstack 4 .locals init (Integer() V_0, Integer V_1) IL_0000: ldc.i4.1 IL_0001: newarr "Integer" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.7 IL_0009: stelem.i4 IL_000a: stloc.0 IL_000b: ldc.i4.0 IL_000c: stloc.1 IL_000d: br.s IL_001b IL_000f: ldloc.0 IL_0010: ldloc.1 IL_0011: ldelem.i4 IL_0012: call "Sub System.Console.WriteLine(Integer)" IL_0017: ldloc.1 IL_0018: ldc.i4.1 IL_0019: add.ovf IL_001a: stloc.1 IL_001b: ldloc.1 IL_001c: ldloc.0 IL_001d: ldlen IL_001e: conv.i4 IL_001f: blt.s IL_000f IL_0021: ret } ]]>) End Sub ' Line continuations <Fact> Public Sub LineContinuations() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Class C Public Shared Sub Main() Dim a() As Integer = New Integer() {7} For _ Each _ x _ As _ Integer _ In _ a _ _ : Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 30 (0x1e) .maxstack 4 .locals init (Integer() V_0, Integer V_1) IL_0000: ldc.i4.1 IL_0001: newarr "Integer" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.7 IL_0009: stelem.i4 IL_000a: stloc.0 IL_000b: ldc.i4.0 IL_000c: stloc.1 IL_000d: br.s IL_0017 IL_000f: ldloc.0 IL_0010: ldloc.1 IL_0011: ldelem.i4 IL_0012: pop IL_0013: ldloc.1 IL_0014: ldc.i4.1 IL_0015: add.ovf IL_0016: stloc.1 IL_0017: ldloc.1 IL_0018: ldloc.0 IL_0019: ldlen IL_001a: conv.i4 IL_001b: blt.s IL_000f IL_001d: ret } ]]>) End Sub <Fact(), WorkItem(9151, "DevDiv_Projects/Roslyn"), WorkItem(546096, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546096")> Public Sub IterationVarInConditionalExpression() CompileAndVerify( <compilation> <file name="a.vb"> Option Strict Off Class C Shared Sub Main() For Each x As S In If(True, x, 1) Next End Sub End Class Public Structure S End Structure </file> </compilation>).VerifyIL("C.Main", <![CDATA[ { // Code size 77 (0x4d) .maxstack 2 .locals init (S V_0, System.Collections.IEnumerator V_1, S V_2) .try { IL_0000: ldloc.0 IL_0001: box "S" IL_0006: castclass "System.Collections.IEnumerable" IL_000b: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0010: stloc.1 IL_0011: br.s IL_002e IL_0013: ldloc.1 IL_0014: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0019: dup IL_001a: brtrue.s IL_0028 IL_001c: pop IL_001d: ldloca.s V_2 IL_001f: initobj "S" IL_0025: ldloc.2 IL_0026: br.s IL_002d IL_0028: unbox.any "S" IL_002d: pop IL_002e: ldloc.1 IL_002f: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0034: brtrue.s IL_0013 IL_0036: leave.s IL_004c } finally { IL_0038: ldloc.1 IL_0039: isinst "System.IDisposable" IL_003e: brfalse.s IL_004b IL_0040: ldloc.1 IL_0041: isinst "System.IDisposable" IL_0046: callvirt "Sub System.IDisposable.Dispose()" IL_004b: endfinally } IL_004c: ret } ]]>) End Sub ' Use the declared variable to initialize collection <Fact> Public Sub IterationVarInCollectionExpression_1() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() For Each x As Integer In New Integer() {x + 5, x + 6, x + 7} System.Console.WriteLine(x) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 5 6 7 ]]>) End Sub <Fact(), WorkItem(9151, "DevDiv_Projects/Roslyn"), WorkItem(546096, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546096")> Public Sub TraversingNothing() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict Off Class C Shared Sub Main() For Each item In Nothing Next End Sub End Class </file> </compilation>).VerifyIL("C.Main", <![CDATA[ { // Code size 52 (0x34) .maxstack 1 .locals init (System.Collections.IEnumerator V_0) .try { IL_0000: ldnull IL_0001: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0006: stloc.0 IL_0007: br.s IL_0015 IL_0009: ldloc.0 IL_000a: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_000f: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0014: pop IL_0015: ldloc.0 IL_0016: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_001b: brtrue.s IL_0009 IL_001d: leave.s IL_0033 } finally { IL_001f: ldloc.0 IL_0020: isinst "System.IDisposable" IL_0025: brfalse.s IL_0032 IL_0027: ldloc.0 IL_0028: isinst "System.IDisposable" IL_002d: callvirt "Sub System.IDisposable.Dispose()" IL_0032: endfinally } IL_0033: ret } ]]>) End Sub ' Nested ForEach can use a var declared in the outer ForEach <Fact> Public Sub NestedForeach() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim c(3)() As Integer For Each x As Integer() In c ReDim x(3) For i As Integer = 0 To 3 x(i) = i Next For Each y As Integer In x System .Console .WriteLine (y) Next Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 ]]>) End Sub ' Inner foreach loop referencing the outer foreach loop iteration variable <Fact> Public Sub NestedForeach_1() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim S As String() = New String() {"ABC", "XYZ"} For Each x As String In S For Each y As Char In x System.Console.WriteLine(y) Next Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ A B C X Y Z ]]>) End Sub ' Foreach value can't be modified in a loop <Fact> Public Sub ModifyIterationValueInLoop() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Collections Class C Shared Sub Main() Dim list As New ArrayList() list.Add("One") list.Add("Two") For Each s As String In list s = "a" Next For Each s As String In list System.Console.WriteLine(s) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ One Two ]]>) End Sub ' Pass fields as a ref argument for 'foreach iteration variable' <Fact()> Public Sub PassFieldsAsRefArgument() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim sa As S() = New S(2) {New S With {.I = 1}, New S With {.I = 2}, New S With {.I = 3}} For Each s As S In sa f(s.i) Next For Each s As S In sa System.Console.WriteLine(s.i) Next End Sub Private Shared Sub f(ByRef iref As Integer) iref = 1 End Sub End Class Structure S Public I As integer End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>) End Sub ' With multidimensional arrays, you can use one loop to iterate through the elements <Fact> Public Sub TraversingMultidimensionalArray() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim numbers2D(,) As Integer = New Integer (2,1) {} numbers2D(0,0) = 9 numbers2D(0,1) = 99 numbers2D(1,0) = 3 numbers2D(1,1) = 33 numbers2D(2,0) = 5 numbers2D(2,1) = 55 For Each i As Integer In numbers2D System.Console.WriteLine(i) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 9 99 3 33 5 55 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 98 (0x62) .maxstack 5 .locals init (System.Collections.IEnumerator V_0) IL_0000: ldc.i4.3 IL_0001: ldc.i4.2 IL_0002: newobj "Integer(*,*)..ctor" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.0 IL_000a: ldc.i4.s 9 IL_000c: call "Integer(*,*).Set" IL_0011: dup IL_0012: ldc.i4.0 IL_0013: ldc.i4.1 IL_0014: ldc.i4.s 99 IL_0016: call "Integer(*,*).Set" IL_001b: dup IL_001c: ldc.i4.1 IL_001d: ldc.i4.0 IL_001e: ldc.i4.3 IL_001f: call "Integer(*,*).Set" IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.1 IL_0027: ldc.i4.s 33 IL_0029: call "Integer(*,*).Set" IL_002e: dup IL_002f: ldc.i4.2 IL_0030: ldc.i4.0 IL_0031: ldc.i4.5 IL_0032: call "Integer(*,*).Set" IL_0037: dup IL_0038: ldc.i4.2 IL_0039: ldc.i4.1 IL_003a: ldc.i4.s 55 IL_003c: call "Integer(*,*).Set" IL_0041: callvirt "Function System.Array.GetEnumerator() As System.Collections.IEnumerator" IL_0046: stloc.0 IL_0047: br.s IL_0059 IL_0049: ldloc.0 IL_004a: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_004f: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_0054: call "Sub System.Console.WriteLine(Integer)" IL_0059: ldloc.0 IL_005a: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_005f: brtrue.s IL_0049 IL_0061: ret } ]]>) End Sub ' Traversing jagged arrays <Fact> Public Sub TraversingJaggedArray() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim numbers2D As Integer()() = New Integer()() {New Integer() {1, 2}, New Integer() {4, 5, 6}} For Each x As Integer() In numbers2D For Each y As Integer In x System.Console.WriteLine(y) Next Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 4 5 6 ]]>) End Sub ' Optimization to foreach (char c in String) by treating String as a char array <Fact()> Public Sub TraversingString() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() Dim str As String = "ABC" For Each x In str System.Console.WriteLine(x) Next For Each var In "goo" If Not var.[GetType]().Equals(GetType(Char)) Then System.Console.WriteLine("False") End If Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ A B C ]]>) End Sub ' Traversing items in Dictionary <Fact> Public Sub TraversingDictionary() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections.Generic Class C Public Shared Sub Main() Dim s As New Dictionary(Of Integer, Integer)() s.Add(1, 2) s.Add(2, 3) s.Add(3, 4) For Each pair In s System .Console .WriteLine (pair.Key) Next For Each pair As KeyValuePair(Of Integer, Integer) In s System .Console .WriteLine (pair.Value ) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 2 3 4 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 141 (0x8d) .maxstack 3 .locals init (System.Collections.Generic.Dictionary(Of Integer, Integer) V_0, //s System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator V_1, System.Collections.Generic.KeyValuePair(Of Integer, Integer) V_2, //pair System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator V_3, System.Collections.Generic.KeyValuePair(Of Integer, Integer) V_4) //pair IL_0000: newobj "Sub System.Collections.Generic.Dictionary(Of Integer, Integer)..ctor()" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: ldc.i4.2 IL_0009: callvirt "Sub System.Collections.Generic.Dictionary(Of Integer, Integer).Add(Integer, Integer)" IL_000e: ldloc.0 IL_000f: ldc.i4.2 IL_0010: ldc.i4.3 IL_0011: callvirt "Sub System.Collections.Generic.Dictionary(Of Integer, Integer).Add(Integer, Integer)" IL_0016: ldloc.0 IL_0017: ldc.i4.3 IL_0018: ldc.i4.4 IL_0019: callvirt "Sub System.Collections.Generic.Dictionary(Of Integer, Integer).Add(Integer, Integer)" .try { IL_001e: ldloc.0 IL_001f: callvirt "Function System.Collections.Generic.Dictionary(Of Integer, Integer).GetEnumerator() As System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator" IL_0024: stloc.1 IL_0025: br.s IL_003b IL_0027: ldloca.s V_1 IL_0029: call "Function System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator.get_Current() As System.Collections.Generic.KeyValuePair(Of Integer, Integer)" IL_002e: stloc.2 IL_002f: ldloca.s V_2 IL_0031: call "Function System.Collections.Generic.KeyValuePair(Of Integer, Integer).get_Key() As Integer" IL_0036: call "Sub System.Console.WriteLine(Integer)" IL_003b: ldloca.s V_1 IL_003d: call "Function System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator.MoveNext() As Boolean" IL_0042: brtrue.s IL_0027 IL_0044: leave.s IL_0054 } finally { IL_0046: ldloca.s V_1 IL_0048: constrained. "System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator" IL_004e: callvirt "Sub System.IDisposable.Dispose()" IL_0053: endfinally } IL_0054: nop .try { IL_0055: ldloc.0 IL_0056: callvirt "Function System.Collections.Generic.Dictionary(Of Integer, Integer).GetEnumerator() As System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator" IL_005b: stloc.3 IL_005c: br.s IL_0073 IL_005e: ldloca.s V_3 IL_0060: call "Function System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator.get_Current() As System.Collections.Generic.KeyValuePair(Of Integer, Integer)" IL_0065: stloc.s V_4 IL_0067: ldloca.s V_4 IL_0069: call "Function System.Collections.Generic.KeyValuePair(Of Integer, Integer).get_Value() As Integer" IL_006e: call "Sub System.Console.WriteLine(Integer)" IL_0073: ldloca.s V_3 IL_0075: call "Function System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator.MoveNext() As Boolean" IL_007a: brtrue.s IL_005e IL_007c: leave.s IL_008c } finally { IL_007e: ldloca.s V_3 IL_0080: constrained. "System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator" IL_0086: callvirt "Sub System.IDisposable.Dispose()" IL_008b: endfinally } IL_008c: ret } ]]>) End Sub ' Breaking from nested Loops <Fact> Public Sub BreakFromForeach() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim S As String() = New String() {"ABC", "XYZ"} For Each x As String In S For Each y As Char In x If y = "B"c Then Exit For Else System.Console.WriteLine(y) End If Next Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ A X Y Z ]]>) End Sub ' Continuing for nested Loops <Fact> Public Sub ContinueInForeach() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim S As String() = New String() {"ABC", "XYZ"} For Each x As String In S For Each y As Char In x If y = "B"c Then Continue For End If System.Console.WriteLine(y) Next y, x End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ A C X Y Z ]]>) End Sub ' Query expression works in foreach <Fact()> Public Sub QueryExpressionInForeach() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict Off Option Infer On Imports System Imports System.Collections Imports System.Linq Class C Public Shared Sub Main() For Each x In From w In New Integer() {1, 2, 3} Select z = w.ToString() System.Console.WriteLine(x.ToLower()) Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithModuleName("MODULE"), references:={LinqAssemblyRef}, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 103 (0x67) .maxstack 3 .locals init (System.Collections.Generic.IEnumerator(Of String) V_0) .try { IL_0000: ldc.i4.3 IL_0001: newarr "Integer" IL_0006: dup IL_0007: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D" IL_000c: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)" IL_0011: ldsfld "C._Closure$__.$I1-0 As System.Func(Of Integer, String)" IL_0016: brfalse.s IL_001f IL_0018: ldsfld "C._Closure$__.$I1-0 As System.Func(Of Integer, String)" IL_001d: br.s IL_0035 IL_001f: ldsfld "C._Closure$__.$I As C._Closure$__" IL_0024: ldftn "Function C._Closure$__._Lambda$__1-0(Integer) As String" IL_002a: newobj "Sub System.Func(Of Integer, String)..ctor(Object, System.IntPtr)" IL_002f: dup IL_0030: stsfld "C._Closure$__.$I1-0 As System.Func(Of Integer, String)" IL_0035: call "Function System.Linq.Enumerable.Select(Of Integer, String)(System.Collections.Generic.IEnumerable(Of Integer), System.Func(Of Integer, String)) As System.Collections.Generic.IEnumerable(Of String)" IL_003a: callvirt "Function System.Collections.Generic.IEnumerable(Of String).GetEnumerator() As System.Collections.Generic.IEnumerator(Of String)" IL_003f: stloc.0 IL_0040: br.s IL_0052 IL_0042: ldloc.0 IL_0043: callvirt "Function System.Collections.Generic.IEnumerator(Of String).get_Current() As String" IL_0048: callvirt "Function String.ToLower() As String" IL_004d: call "Sub System.Console.WriteLine(String)" IL_0052: ldloc.0 IL_0053: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0058: brtrue.s IL_0042 IL_005a: leave.s IL_0066 } finally { IL_005c: ldloc.0 IL_005d: brfalse.s IL_0065 IL_005f: ldloc.0 IL_0060: callvirt "Sub System.IDisposable.Dispose()" IL_0065: endfinally } IL_0066: ret } ]]>) End Sub ' No confusion in a foreach statement when from is a value type <Fact> Public Sub ReDimFrom() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() Dim src = New System.Collections.ArrayList() src.Add(new from(1)) For Each x As from In src System.Console.WriteLine(x.X) Next End Sub End Class Public Structure from Dim X As Integer Public Sub New(p as integer) x = p End Sub End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 ]]>) End Sub ' Foreach on generic type that implements the Collection Pattern <Fact> Public Sub GenericTypeImplementsCollection() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections.Generic Class C Public Shared Sub Main() For Each j In New Gen(Of Integer)() Next End Sub End Class Public Class Gen(Of T As New) Public Function GetEnumerator() As IEnumerator(Of T) Return Nothing End Function End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 41 (0x29) .maxstack 1 .locals init (System.Collections.Generic.IEnumerator(Of Integer) V_0) .try { IL_0000: newobj "Sub Gen(Of Integer)..ctor()" IL_0005: call "Function Gen(Of Integer).GetEnumerator() As System.Collections.Generic.IEnumerator(Of Integer)" IL_000a: stloc.0 IL_000b: br.s IL_0014 IL_000d: ldloc.0 IL_000e: callvirt "Function System.Collections.Generic.IEnumerator(Of Integer).get_Current() As Integer" IL_0013: pop IL_0014: ldloc.0 IL_0015: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_001a: brtrue.s IL_000d IL_001c: leave.s IL_0028 } finally { IL_001e: ldloc.0 IL_001f: brfalse.s IL_0027 IL_0021: ldloc.0 IL_0022: callvirt "Sub System.IDisposable.Dispose()" IL_0027: endfinally } IL_0028: ret } ]]>) End Sub ' Customer defined type of collection to support 'foreach' <Fact> Public Sub CustomerDefinedCollections() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C Public Shared Sub Main() Dim col As New MyCollection() For Each i As Integer In col Console.WriteLine(i) Next End Sub End Class Public Class MyCollection Private items As Integer() Public Sub New() items = New Integer(4) {1, 4, 3, 2, 5} End Sub Public Function GetEnumerator() As MyEnumerator Return New MyEnumerator(Me) End Function Public Class MyEnumerator Private nIndex As Integer Private collection As MyCollection Public Sub New(coll As MyCollection) collection = coll nIndex = nIndex - 1 End Sub Public Function MoveNext() As Boolean nIndex = nIndex + 1 Return (nIndex &lt; collection.items.GetLength(0)) End Function Public ReadOnly Property Current() As Integer Get Return (collection.items(nIndex)) End Get End Property End Class End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 4 3 2 5 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 33 (0x21) .maxstack 1 .locals init (MyCollection.MyEnumerator V_0) IL_0000: newobj "Sub MyCollection..ctor()" IL_0005: callvirt "Function MyCollection.GetEnumerator() As MyCollection.MyEnumerator" IL_000a: stloc.0 IL_000b: br.s IL_0018 IL_000d: ldloc.0 IL_000e: callvirt "Function MyCollection.MyEnumerator.get_Current() As Integer" IL_0013: call "Sub System.Console.WriteLine(Integer)" IL_0018: ldloc.0 IL_0019: callvirt "Function MyCollection.MyEnumerator.MoveNext() As Boolean" IL_001e: brtrue.s IL_000d IL_0020: ret } ]]>) End Sub <Fact> Public Sub TestForEachPattern() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class Class Enumerator Private x As Integer = 0 Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 33 (0x21) .maxstack 1 .locals init (Enumerator V_0) IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0018 IL_000d: ldloc.0 IL_000e: callvirt "Function Enumerator.get_Current() As Integer" IL_0013: call "Sub System.Console.WriteLine(Integer)" IL_0018: ldloc.0 IL_0019: callvirt "Function Enumerator.MoveNext() As Boolean" IL_001e: brtrue.s IL_000d IL_0020: ret } ]]>) End Sub <Fact> Public Sub TestForEachInterface() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Implements System.Collections.IEnumerable ' Explicit implementation won't match pattern. Private Function System_Collections_IEnumerable_GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Dim list As New System.Collections.Generic.List(Of Integer)() list.Add(3) list.Add(2) list.Add(1) Return list.GetEnumerator() End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ 3 2 1 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 65 (0x41) .maxstack 1 .locals init (System.Collections.IEnumerator V_0) .try { IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_000a: stloc.0 IL_000b: br.s IL_0022 IL_000d: ldloc.0 IL_000e: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0013: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0018: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001d: call "Sub System.Console.WriteLine(Object)" IL_0022: ldloc.0 IL_0023: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0028: brtrue.s IL_000d IL_002a: leave.s IL_0040 } finally { IL_002c: ldloc.0 IL_002d: isinst "System.IDisposable" IL_0032: brfalse.s IL_003f IL_0034: ldloc.0 IL_0035: isinst "System.IDisposable" IL_003a: callvirt "Sub System.IDisposable.Dispose()" IL_003f: endfinally } IL_0040: ret } ]]>) End Sub <Fact> Public Sub TestForEachExplicitlyDisposableStruct() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class Structure Enumerator Implements System.IDisposable Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function Private Sub System_IDisposable_Dispose() Implements System.IDisposable.Dispose End Sub End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 51 (0x33) .maxstack 1 .locals init (Enumerator V_0) .try { IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0019 IL_000d: ldloca.s V_0 IL_000f: call "Function Enumerator.get_Current() As Integer" IL_0014: call "Sub System.Console.WriteLine(Integer)" IL_0019: ldloca.s V_0 IL_001b: call "Function Enumerator.MoveNext() As Boolean" IL_0020: brtrue.s IL_000d IL_0022: leave.s IL_0032 } finally { IL_0024: ldloca.s V_0 IL_0026: constrained. "Enumerator" IL_002c: callvirt "Sub System.IDisposable.Dispose()" IL_0031: endfinally } IL_0032: ret } ]]>) End Sub <Fact> Public Sub TestForEachDisposeStruct() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class Structure Enumerator Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function Public Sub Dispose() End Sub End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 35 (0x23) .maxstack 1 .locals init (Enumerator V_0) IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0019 IL_000d: ldloca.s V_0 IL_000f: call "Function Enumerator.get_Current() As Integer" IL_0014: call "Sub System.Console.WriteLine(Integer)" IL_0019: ldloca.s V_0 IL_001b: call "Function Enumerator.MoveNext() As Boolean" IL_0020: brtrue.s IL_000d IL_0022: ret } ]]>) End Sub <Fact> Public Sub TestForEachNonDisposableStruct() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class Structure Enumerator Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 35 (0x23) .maxstack 1 .locals init (Enumerator V_0) IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0019 IL_000d: ldloca.s V_0 IL_000f: call "Function Enumerator.get_Current() As Integer" IL_0014: call "Sub System.Console.WriteLine(Integer)" IL_0019: ldloca.s V_0 IL_001b: call "Function Enumerator.MoveNext() As Boolean" IL_0020: brtrue.s IL_000d IL_0022: ret } ]]>) End Sub <Fact> Public Sub TestForEachExplicitlyGetEnumeratorStruct() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Structure Enumerable Implements IEnumerable Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return New Integer() {1, 2, 3}.GetEnumerator() End Function End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 79 (0x4f) .maxstack 1 .locals init (System.Collections.IEnumerator V_0, Enumerable V_1) .try { IL_0000: ldloca.s V_1 IL_0002: initobj "Enumerable" IL_0008: ldloc.1 IL_0009: box "Enumerable" IL_000e: castclass "System.Collections.IEnumerable" IL_0013: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0018: stloc.0 IL_0019: br.s IL_0030 IL_001b: ldloc.0 IL_001c: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0021: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0026: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_002b: call "Sub System.Console.WriteLine(Object)" IL_0030: ldloc.0 IL_0031: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0036: brtrue.s IL_001b IL_0038: leave.s IL_004e } finally { IL_003a: ldloc.0 IL_003b: isinst "System.IDisposable" IL_0040: brfalse.s IL_004d IL_0042: ldloc.0 IL_0043: isinst "System.IDisposable" IL_0048: callvirt "Sub System.IDisposable.Dispose()" IL_004d: endfinally } IL_004e: ret } ]]>) End Sub <Fact> Public Sub TestForEachGetEnumeratorStruct() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Structure Enumerable Public Function GetEnumerator() As IEnumerator Return New Integer() {1, 2, 3}.GetEnumerator() End Function End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 72 (0x48) .maxstack 1 .locals init (System.Collections.IEnumerator V_0, Enumerable V_1) .try { IL_0000: ldloca.s V_1 IL_0002: initobj "Enumerable" IL_0008: ldloc.1 IL_0009: stloc.1 IL_000a: ldloca.s V_1 IL_000c: call "Function Enumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0011: stloc.0 IL_0012: br.s IL_0029 IL_0014: ldloc.0 IL_0015: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_001a: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001f: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0024: call "Sub System.Console.WriteLine(Object)" IL_0029: ldloc.0 IL_002a: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_002f: brtrue.s IL_0014 IL_0031: leave.s IL_0047 } finally { IL_0033: ldloc.0 IL_0034: isinst "System.IDisposable" IL_0039: brfalse.s IL_0046 IL_003b: ldloc.0 IL_003c: isinst "System.IDisposable" IL_0041: callvirt "Sub System.IDisposable.Dispose()" IL_0046: endfinally } IL_0047: ret } ]]>) End Sub <Fact> Public Sub TestForEachDisposableSealed() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class NotInheritable Class Enumerator Implements System.IDisposable Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function Private Sub System_IDisposable_Dispose() Implements System.IDisposable.Dispose End Sub End Class Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 45 (0x2d) .maxstack 1 .locals init (Enumerator V_0) .try { IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0018 IL_000d: ldloc.0 IL_000e: callvirt "Function Enumerator.get_Current() As Integer" IL_0013: call "Sub System.Console.WriteLine(Integer)" IL_0018: ldloc.0 IL_0019: callvirt "Function Enumerator.MoveNext() As Boolean" IL_001e: brtrue.s IL_000d IL_0020: leave.s IL_002c } finally { IL_0022: ldloc.0 IL_0023: brfalse.s IL_002b IL_0025: ldloc.0 IL_0026: callvirt "Sub System.IDisposable.Dispose()" IL_002b: endfinally } IL_002c: ret } ]]>) End Sub <Fact> Public Sub TestForEachNonDisposableSealed() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class NotInheritable Class Enumerator Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 33 (0x21) .maxstack 1 .locals init (Enumerator V_0) IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0018 IL_000d: ldloc.0 IL_000e: callvirt "Function Enumerator.get_Current() As Integer" IL_0013: call "Sub System.Console.WriteLine(Integer)" IL_0018: ldloc.0 IL_0019: callvirt "Function Enumerator.MoveNext() As Boolean" IL_001e: brtrue.s IL_000d IL_0020: ret } ]]>) End Sub <Fact> Public Sub TestForEachNonDisposableAbstractClass() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable1() System.Console.WriteLine(x) Next For Each x In New Enumerable2() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable1 Public Function GetEnumerator() As AbstractEnumerator Return New DisposableEnumerator() End Function End Class Class Enumerable2 Public Function GetEnumerator() As AbstractEnumerator Return New NonDisposableEnumerator() End Function End Class MustInherit Class AbstractEnumerator Public MustOverride ReadOnly Property Current() As Integer Public MustOverride Function MoveNext() As Boolean End Class Class DisposableEnumerator Inherits AbstractEnumerator Implements System.IDisposable Private x As Integer Public Overrides ReadOnly Property Current() As Integer Get Return x End Get End Property Public Overrides Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function Private Sub System_IDisposable_Dispose() Implements System.IDisposable.Dispose System.Console.WriteLine("Done with DisposableEnumerator") End Sub End Class Class NonDisposableEnumerator Inherits AbstractEnumerator Private x As Integer Public Overrides ReadOnly Property Current() As Integer Get Return x End Get End Property Public Overrides Function MoveNext() As Boolean Return System.Threading.Interlocked.Decrement(x) &gt; -4 End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 -1 -2 -3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 65 (0x41) .maxstack 1 .locals init (AbstractEnumerator V_0, AbstractEnumerator V_1) IL_0000: newobj "Sub Enumerable1..ctor()" IL_0005: call "Function Enumerable1.GetEnumerator() As AbstractEnumerator" IL_000a: stloc.0 IL_000b: br.s IL_0018 IL_000d: ldloc.0 IL_000e: callvirt "Function AbstractEnumerator.get_Current() As Integer" IL_0013: call "Sub System.Console.WriteLine(Integer)" IL_0018: ldloc.0 IL_0019: callvirt "Function AbstractEnumerator.MoveNext() As Boolean" IL_001e: brtrue.s IL_000d IL_0020: newobj "Sub Enumerable2..ctor()" IL_0025: call "Function Enumerable2.GetEnumerator() As AbstractEnumerator" IL_002a: stloc.1 IL_002b: br.s IL_0038 IL_002d: ldloc.1 IL_002e: callvirt "Function AbstractEnumerator.get_Current() As Integer" IL_0033: call "Sub System.Console.WriteLine(Integer)" IL_0038: ldloc.1 IL_0039: callvirt "Function AbstractEnumerator.MoveNext() As Boolean" IL_003e: brtrue.s IL_002d IL_0040: ret } ]]>) End Sub <WorkItem(528679, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528679")> <Fact> Public Sub TestForEachNested() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer on Class C Public Shared Sub Main() For Each x In New Enumerable() For Each y In New Enumerable() System.Console.WriteLine("({0}, {1})", x, y) Next Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class Class Enumerator Private x As Integer = 0 Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ (1, 1) (1, 2) (1, 3) (2, 1) (2, 2) (2, 3) (3, 1) (3, 2) (3, 3) ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 79 (0x4f) .maxstack 3 .locals init (Enumerator V_0, Integer V_1, //x Enumerator V_2, Integer V_3) //y IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0046 IL_000d: ldloc.0 IL_000e: callvirt "Function Enumerator.get_Current() As Integer" IL_0013: stloc.1 IL_0014: newobj "Sub Enumerable..ctor()" IL_0019: call "Function Enumerable.GetEnumerator() As Enumerator" IL_001e: stloc.2 IL_001f: br.s IL_003e IL_0021: ldloc.2 IL_0022: callvirt "Function Enumerator.get_Current() As Integer" IL_0027: stloc.3 IL_0028: ldstr "({0}, {1})" IL_002d: ldloc.1 IL_002e: box "Integer" IL_0033: ldloc.3 IL_0034: box "Integer" IL_0039: call "Sub System.Console.WriteLine(String, Object, Object)" IL_003e: ldloc.2 IL_003f: callvirt "Function Enumerator.MoveNext() As Boolean" IL_0044: brtrue.s IL_0021 IL_0046: ldloc.0 IL_0047: callvirt "Function Enumerator.MoveNext() As Boolean" IL_004c: brtrue.s IL_000d IL_004e: ret } ]]>) End Sub <WorkItem(542075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542075")> <Fact> Public Sub TestGetEnumeratorWithParams() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections.Generic Imports System Class C public Shared Sub Main() For Each x In New B() Console.WriteLine(x.ToLower()) Next End Sub End Class Class A Public Function GetEnumerator() As List(Of String).Enumerator Dim s = New List(Of String)() s.Add("A") s.Add("B") s.Add("C") Return s.GetEnumerator() End Function End Class Class B Inherits A Public Overloads Function GetEnumerator(ParamArray x As Integer()) As List(Of Integer).Enumerator Return nothing End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ a b c ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 56 (0x38) .maxstack 1 .locals init (System.Collections.Generic.List(Of String).Enumerator V_0) .try { IL_0000: newobj "Sub B..ctor()" IL_0005: call "Function A.GetEnumerator() As System.Collections.Generic.List(Of String).Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_001e IL_000d: ldloca.s V_0 IL_000f: call "Function System.Collections.Generic.List(Of String).Enumerator.get_Current() As String" IL_0014: callvirt "Function String.ToLower() As String" IL_0019: call "Sub System.Console.WriteLine(String)" IL_001e: ldloca.s V_0 IL_0020: call "Function System.Collections.Generic.List(Of String).Enumerator.MoveNext() As Boolean" IL_0025: brtrue.s IL_000d IL_0027: leave.s IL_0037 } finally { IL_0029: ldloca.s V_0 IL_002b: constrained. "System.Collections.Generic.List(Of String).Enumerator" IL_0031: callvirt "Sub System.IDisposable.Dispose()" IL_0036: endfinally } IL_0037: ret } ]]>) End Sub <Fact> Public Sub TestMoveNextWithNonBoolDeclaredReturnType() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections Class Program Public Shared Sub Main() Goo(sub(x) For Each y In x Next end sub ) End Sub Public Shared Sub Goo(a As System.Action(Of IEnumerable)) System.Console.WriteLine(1) End Sub End Class Class A Public Function GetEnumerator() As E(Of Boolean) Return New E(Of Boolean)() End Function End Class Class E(Of T) Public Function MoveNext() As T Return Nothing End Function Public Property Current() As Integer Get Return m_Current End Get Set(value As Integer) m_Current = Value End Set End Property Private m_Current As Integer End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 ]]>) End Sub <Fact()> Public Sub TestNonConstantNullInForeach() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class Program Public Shared Sub Main() Try Const s As String = Nothing For Each y In TryCast(s, String) Next Catch generatedExceptionName As System.NullReferenceException System.Console.WriteLine(1) End Try End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 ]]>) End Sub <WorkItem(542079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542079")> <Fact> Public Sub TestForEachStructEnumerable() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections Class C public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Structure Enumerable Implements IEnumerable Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return New Integer() {1, 2, 3}.GetEnumerator() End Function End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 79 (0x4f) .maxstack 1 .locals init (System.Collections.IEnumerator V_0, Enumerable V_1) .try { IL_0000: ldloca.s V_1 IL_0002: initobj "Enumerable" IL_0008: ldloc.1 IL_0009: box "Enumerable" IL_000e: castclass "System.Collections.IEnumerable" IL_0013: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0018: stloc.0 IL_0019: br.s IL_0030 IL_001b: ldloc.0 IL_001c: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0021: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0026: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_002b: call "Sub System.Console.WriteLine(Object)" IL_0030: ldloc.0 IL_0031: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0036: brtrue.s IL_001b IL_0038: leave.s IL_004e } finally { IL_003a: ldloc.0 IL_003b: isinst "System.IDisposable" IL_0040: brfalse.s IL_004d IL_0042: ldloc.0 IL_0043: isinst "System.IDisposable" IL_0048: callvirt "Sub System.IDisposable.Dispose()" IL_004d: endfinally } IL_004e: ret } ]]>) End Sub <Fact> Public Sub TestForEachMutableStructEnumerablePattern() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() Dim e As New Enumerable() System.Console.WriteLine(e.i) For Each x In e Next System.Console.WriteLine(e.i) End Sub End Class Structure Enumerable Public i As Integer Public Function GetEnumerator() As Enumerator i = i + 1 Return New Enumerator() End Function End Structure Structure Enumerator Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 0 1 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 58 (0x3a) .maxstack 1 .locals init (Enumerable V_0, //e Enumerator V_1) IL_0000: ldloca.s V_0 IL_0002: initobj "Enumerable" IL_0008: ldloc.0 IL_0009: ldfld "Enumerable.i As Integer" IL_000e: call "Sub System.Console.WriteLine(Integer)" IL_0013: ldloca.s V_0 IL_0015: call "Function Enumerable.GetEnumerator() As Enumerator" IL_001a: stloc.1 IL_001b: br.s IL_0025 IL_001d: ldloca.s V_1 IL_001f: call "Function Enumerator.get_Current() As Integer" IL_0024: pop IL_0025: ldloca.s V_1 IL_0027: call "Function Enumerator.MoveNext() As Boolean" IL_002c: brtrue.s IL_001d IL_002e: ldloc.0 IL_002f: ldfld "Enumerable.i As Integer" IL_0034: call "Sub System.Console.WriteLine(Integer)" IL_0039: ret } ]]>) End Sub <WorkItem(542079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542079")> <Fact> Public Sub TestForEachMutableStructEnumerableInterface() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections Class C Public Shared Sub Main() Dim e As New Enumerable() System.Console.WriteLine(e.i) For Each x In e Next System.Console.WriteLine(e.i) End Sub End Class Structure Enumerable Implements IEnumerable Public i As Integer Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator i = i + 1 Return New Enumerator() End Function End Structure Structure Enumerator Implements IEnumerator Private x As Integer Public ReadOnly Property Current() As Object Implements IEnumerator.Current Get Return x End Get End Property Public Function MoveNext() As Boolean Implements IEnumerator.MoveNext Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function Public Sub Reset() Implements IEnumerator.Reset x = 0 End Sub End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 0 0 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 92 (0x5c) .maxstack 1 .locals init (Enumerable V_0, //e System.Collections.IEnumerator V_1) IL_0000: ldloca.s V_0 IL_0002: initobj "Enumerable" IL_0008: ldloc.0 IL_0009: ldfld "Enumerable.i As Integer" IL_000e: call "Sub System.Console.WriteLine(Integer)" .try { IL_0013: ldloc.0 IL_0014: box "Enumerable" IL_0019: castclass "System.Collections.IEnumerable" IL_001e: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0023: stloc.1 IL_0024: br.s IL_0032 IL_0026: ldloc.1 IL_0027: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_002c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0031: pop IL_0032: ldloc.1 IL_0033: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0038: brtrue.s IL_0026 IL_003a: leave.s IL_0050 } finally { IL_003c: ldloc.1 IL_003d: isinst "System.IDisposable" IL_0042: brfalse.s IL_004f IL_0044: ldloc.1 IL_0045: isinst "System.IDisposable" IL_004a: callvirt "Sub System.IDisposable.Dispose()" IL_004f: endfinally } IL_0050: ldloc.0 IL_0051: ldfld "Enumerable.i As Integer" IL_0056: call "Sub System.Console.WriteLine(Integer)" IL_005b: ret } ]]>) End Sub <Fact()> Public Sub TypeParameterAsEnumeratorTypeCanBeReferenceType() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports System.Collections Public Class Custom(Of S As {IEnumerator, IDisposable}) Public Function GetEnumerator() As S Return Nothing End Function End Class Class C1(Of S As {IEnumerator, IDisposable}) Public Sub DoStuff() Dim myCustomCollection As Custom(Of S) = nothing For Each element In myCustomCollection Console.WriteLine("goo") Next End Sub End Class Class C2 Public Shared Sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C1(Of S).DoStuff", <![CDATA[ { // Code size 80 (0x50) .maxstack 1 .locals init (Custom(Of S) V_0, //myCustomCollection S V_1) IL_0000: ldnull IL_0001: stloc.0 .try { IL_0002: ldloc.0 IL_0003: callvirt "Function Custom(Of S).GetEnumerator() As S" IL_0008: stloc.1 IL_0009: br.s IL_0028 IL_000b: ldloca.s V_1 IL_000d: constrained. "S" IL_0013: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0018: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001d: pop IL_001e: ldstr "goo" IL_0023: call "Sub System.Console.WriteLine(String)" IL_0028: ldloca.s V_1 IL_002a: constrained. "S" IL_0030: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0035: brtrue.s IL_000b IL_0037: leave.s IL_004f } finally { IL_0039: ldloc.1 IL_003a: box "S" IL_003f: brfalse.s IL_004e IL_0041: ldloca.s V_1 IL_0043: constrained. "S" IL_0049: callvirt "Sub System.IDisposable.Dispose()" IL_004e: endfinally } IL_004f: ret } ]]>) End Sub <Fact()> Public Sub TypeParameterAsEnumeratorTypeHasValueConstraint() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports System.Collections Public Class Custom(Of S As {IEnumerator, IDisposable, Structure}) Public Function GetEnumerator() As S Return Nothing End Function End Class Class C1(Of S As {IEnumerator, IDisposable, Structure}) Public Sub DoStuff() Dim myCustomCollection As Custom(Of S) = nothing For Each element In myCustomCollection Console.WriteLine("goo") Next End Sub End Class Class C2 Public Shared Sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C1(Of S).DoStuff", <![CDATA[ { // Code size 72 (0x48) .maxstack 1 .locals init (Custom(Of S) V_0, //myCustomCollection S V_1) IL_0000: ldnull IL_0001: stloc.0 .try { IL_0002: ldloc.0 IL_0003: callvirt "Function Custom(Of S).GetEnumerator() As S" IL_0008: stloc.1 IL_0009: br.s IL_0028 IL_000b: ldloca.s V_1 IL_000d: constrained. "S" IL_0013: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0018: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001d: pop IL_001e: ldstr "goo" IL_0023: call "Sub System.Console.WriteLine(String)" IL_0028: ldloca.s V_1 IL_002a: constrained. "S" IL_0030: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0035: brtrue.s IL_000b IL_0037: leave.s IL_0047 } finally { IL_0039: ldloca.s V_1 IL_003b: constrained. "S" IL_0041: callvirt "Sub System.IDisposable.Dispose()" IL_0046: endfinally } IL_0047: ret } ]]>) End Sub <Fact> Public Sub NoObjectCopyForGetCurrent() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System Imports System.Collections.Generic Class C2 Public Structure S1 Public Field as Integer Public Sub New(x as integer) Field = x End Sub End Structure Public Shared Sub Main() dim coll = New List(Of S1) coll.add(new S1(23)) coll.add(new S1(42)) DoStuff(coll) End Sub Public Shared Sub DoStuff(coll as System.Collections.IEnumerable) for each x as Object in coll Console.WriteLine(Directcast(x,S1).Field) next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 23 42 ]]>).VerifyIL("C2.DoStuff", <![CDATA[ { // Code size 66 (0x42) .maxstack 1 .locals init (System.Collections.IEnumerator V_0) .try { IL_0000: ldarg.0 IL_0001: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0006: stloc.0 IL_0007: br.s IL_0023 IL_0009: ldloc.0 IL_000a: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_000f: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0014: unbox "C2.S1" IL_0019: ldfld "C2.S1.Field As Integer" IL_001e: call "Sub System.Console.WriteLine(Integer)" IL_0023: ldloc.0 IL_0024: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0029: brtrue.s IL_0009 IL_002b: leave.s IL_0041 } finally { IL_002d: ldloc.0 IL_002e: isinst "System.IDisposable" IL_0033: brfalse.s IL_0040 IL_0035: ldloc.0 IL_0036: isinst "System.IDisposable" IL_003b: callvirt "Sub System.IDisposable.Dispose()" IL_0040: endfinally } IL_0041: ret } ]]>) ' there should be a check for null before calling Dispose End Sub <WorkItem(542185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542185")> <Fact> Public Sub CustomDefinedType() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections.Generic Class C Public Shared Sub Main() Dim x = New B() End Sub End Class Class A Public Function GetEnumerator() As List(Of String).Enumerator Dim s = New List(Of String)() s.Add("A") s.Add("B") s.Add("C") Return s.GetEnumerator() End Function End Class Class B Inherits A Public Overloads Function GetEnumerator(ParamArray x As Integer()) As List(Of Integer).Enumerator Return New List(Of Integer).Enumerator() End Function End Class </file> </compilation>) End Sub <Fact> Public Sub ForEachQuery() CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Linq Module Program Sub Main(args As String()) Dim ii As Integer() = New Integer() {1, 2, 3} For Each iii In ii.Where(Function(jj) jj >= ii(0)).Select(Function(jj) jj) System.Console.Write(iii) Next End Sub End Module </file> </compilation>, references:={LinqAssemblyRef}, expectedOutput:="123") End Sub <WorkItem(544311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544311")> <Fact()> Public Sub ForEachWithMultipleDimArray() CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Module Program Sub Main() Dim k(,) = {{1}, {1}} For Each [Custom] In k Console.Write(VerifyStaticType([Custom], GetType(Integer))) Console.Write(VerifyStaticType([Custom], GetType(Object))) Exit For Next End Sub Function VerifyStaticType(Of T)(ByVal x As T, ByVal y As System.Type) As Boolean Return GetType(T) Is y End Function End Module </file> </compilation>, expectedOutput:="TrueFalse") End Sub <WorkItem(545519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545519")> <Fact()> Public Sub NewForEachScopeDev11() Dim source = <compilation> <file name="a.vb"> imports system imports system.collections.generic Module m1 Sub Main() Dim actions = New List(Of Action)() Dim values = New List(Of Integer) From {1, 2, 3} ' test lifting of control variable in loop body when collection is array For Each i As Integer In values actions.Add(Sub() Console.WriteLine(i)) Next For Each a In actions a() Next End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("m1.Main", <![CDATA[ { // Code size 154 (0x9a) .maxstack 3 .locals init (System.Collections.Generic.List(Of System.Action) V_0, //actions System.Collections.Generic.List(Of Integer) V_1, //values System.Collections.Generic.List(Of Integer).Enumerator V_2, m1._Closure$__0-0 V_3, //$VB$Closure_0 System.Collections.Generic.List(Of System.Action).Enumerator V_4) IL_0000: newobj "Sub System.Collections.Generic.List(Of System.Action)..ctor()" IL_0005: stloc.0 IL_0006: newobj "Sub System.Collections.Generic.List(Of Integer)..ctor()" IL_000b: dup IL_000c: ldc.i4.1 IL_000d: callvirt "Sub System.Collections.Generic.List(Of Integer).Add(Integer)" IL_0012: dup IL_0013: ldc.i4.2 IL_0014: callvirt "Sub System.Collections.Generic.List(Of Integer).Add(Integer)" IL_0019: dup IL_001a: ldc.i4.3 IL_001b: callvirt "Sub System.Collections.Generic.List(Of Integer).Add(Integer)" IL_0020: stloc.1 .try { IL_0021: ldloc.1 IL_0022: callvirt "Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator" IL_0027: stloc.2 IL_0028: br.s IL_0050 IL_002a: ldloc.3 IL_002b: newobj "Sub m1._Closure$__0-0..ctor(m1._Closure$__0-0)" IL_0030: stloc.3 IL_0031: ldloc.3 IL_0032: ldloca.s V_2 IL_0034: call "Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer" IL_0039: stfld "m1._Closure$__0-0.$VB$Local_i As Integer" IL_003e: ldloc.0 IL_003f: ldloc.3 IL_0040: ldftn "Sub m1._Closure$__0-0._Lambda$__0()" IL_0046: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_004b: callvirt "Sub System.Collections.Generic.List(Of System.Action).Add(System.Action)" IL_0050: ldloca.s V_2 IL_0052: call "Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean" IL_0057: brtrue.s IL_002a IL_0059: leave.s IL_0069 } finally { IL_005b: ldloca.s V_2 IL_005d: constrained. "System.Collections.Generic.List(Of Integer).Enumerator" IL_0063: callvirt "Sub System.IDisposable.Dispose()" IL_0068: endfinally } IL_0069: nop .try { IL_006a: ldloc.0 IL_006b: callvirt "Function System.Collections.Generic.List(Of System.Action).GetEnumerator() As System.Collections.Generic.List(Of System.Action).Enumerator" IL_0070: stloc.s V_4 IL_0072: br.s IL_0080 IL_0074: ldloca.s V_4 IL_0076: call "Function System.Collections.Generic.List(Of System.Action).Enumerator.get_Current() As System.Action" IL_007b: callvirt "Sub System.Action.Invoke()" IL_0080: ldloca.s V_4 IL_0082: call "Function System.Collections.Generic.List(Of System.Action).Enumerator.MoveNext() As Boolean" IL_0087: brtrue.s IL_0074 IL_0089: leave.s IL_0099 } finally { IL_008b: ldloca.s V_4 IL_008d: constrained. "System.Collections.Generic.List(Of System.Action).Enumerator" IL_0093: callvirt "Sub System.IDisposable.Dispose()" IL_0098: endfinally } IL_0099: ret } ]]>) End Sub <WorkItem(545519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545519")> <Fact()> Public Sub NewForEachScopeDev11_2() Dim source = <compilation> <file name="a.vb"> imports system imports system.collections.generic Module m1 Sub Main() ' Test Array Dim x(10) as action ' test lifting of control variable in loop body and lifting of control variable when used ' in the collection expression itself. For Each i As Integer In (function() {i + 1, i + 2, i + 3})() x(i) = Sub() console.writeline(i.toString) Next for i = 1 to 3 x(i).invoke() next End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("m1.Main", <![CDATA[ { // Code size 93 (0x5d) .maxstack 4 .locals init (System.Action() V_0, //x Integer() V_1, Integer V_2, m1._Closure$__0-1 V_3, //$VB$Closure_0 Integer V_4) //i IL_0000: ldc.i4.s 11 IL_0002: newarr "System.Action" IL_0007: stloc.0 IL_0008: newobj "Sub m1._Closure$__0-0..ctor()" IL_000d: callvirt "Function m1._Closure$__0-0._Lambda$__0() As Integer()" IL_0012: stloc.1 IL_0013: ldc.i4.0 IL_0014: stloc.2 IL_0015: br.s IL_003f IL_0017: ldloc.3 IL_0018: newobj "Sub m1._Closure$__0-1..ctor(m1._Closure$__0-1)" IL_001d: stloc.3 IL_001e: ldloc.3 IL_001f: ldloc.1 IL_0020: ldloc.2 IL_0021: ldelem.i4 IL_0022: stfld "m1._Closure$__0-1.$VB$Local_i As Integer" IL_0027: ldloc.0 IL_0028: ldloc.3 IL_0029: ldfld "m1._Closure$__0-1.$VB$Local_i As Integer" IL_002e: ldloc.3 IL_002f: ldftn "Sub m1._Closure$__0-1._Lambda$__1()" IL_0035: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_003a: stelem.ref IL_003b: ldloc.2 IL_003c: ldc.i4.1 IL_003d: add.ovf IL_003e: stloc.2 IL_003f: ldloc.2 IL_0040: ldloc.1 IL_0041: ldlen IL_0042: conv.i4 IL_0043: blt.s IL_0017 IL_0045: ldc.i4.1 IL_0046: stloc.s V_4 IL_0048: ldloc.0 IL_0049: ldloc.s V_4 IL_004b: ldelem.ref IL_004c: callvirt "Sub System.Action.Invoke()" IL_0051: ldloc.s V_4 IL_0053: ldc.i4.1 IL_0054: add.ovf IL_0055: stloc.s V_4 IL_0057: ldloc.s V_4 IL_0059: ldc.i4.3 IL_005a: ble.s IL_0048 IL_005c: ret } ]]>) End Sub <WorkItem(545519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545519")> <Fact()> Public Sub NewForEachScopeDev11_3() Dim source = <compilation> <file name="a.vb"> imports system imports system.collections.generic Module m1 Sub Main() ' Test Array Dim x(10) as action for j = 0 to 2 ' test lifting of control variable in loop body and lifting of control variable when used ' in the collection expression itself. for each i as integer in (function(a) goo())(i) x(i) = sub() console.write(i.toString &amp; " ") next for i = 1 to 3 x(i).invoke() next Console.Writeline() next j End Sub function goo() as IEnumerable(of Integer) return new list(of integer) from {1, 2, 3} end function End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[1 2 3 1 2 3 1 2 3 ]]>).VerifyIL("m1.Main", <![CDATA[ { // Code size 170 (0xaa) .maxstack 4 .locals init (System.Action() V_0, //x Integer V_1, //j Integer V_2, System.Collections.Generic.IEnumerator(Of Integer) V_3, m1._Closure$__0-0 V_4, //$VB$Closure_0 Integer V_5) //i IL_0000: ldc.i4.s 11 IL_0002: newarr "System.Action" IL_0007: stloc.0 IL_0008: ldc.i4.0 IL_0009: stloc.1 IL_000a: nop .try { IL_000b: ldsfld "m1._Closure$__.$I0-0 As <generated method>" IL_0010: brfalse.s IL_0019 IL_0012: ldsfld "m1._Closure$__.$I0-0 As <generated method>" IL_0017: br.s IL_002f IL_0019: ldsfld "m1._Closure$__.$I As m1._Closure$__" IL_001e: ldftn "Function m1._Closure$__._Lambda$__0-0(Object) As System.Collections.Generic.IEnumerable(Of Integer)" IL_0024: newobj "Sub VB$AnonymousDelegate_0(Of Object, System.Collections.Generic.IEnumerable(Of Integer))..ctor(Object, System.IntPtr)" IL_0029: dup IL_002a: stsfld "m1._Closure$__.$I0-0 As <generated method>" IL_002f: ldloc.2 IL_0030: box "Integer" IL_0035: callvirt "Function VB$AnonymousDelegate_0(Of Object, System.Collections.Generic.IEnumerable(Of Integer)).Invoke(Object) As System.Collections.Generic.IEnumerable(Of Integer)" IL_003a: callvirt "Function System.Collections.Generic.IEnumerable(Of Integer).GetEnumerator() As System.Collections.Generic.IEnumerator(Of Integer)" IL_003f: stloc.3 IL_0040: br.s IL_006e IL_0042: ldloc.s V_4 IL_0044: newobj "Sub m1._Closure$__0-0..ctor(m1._Closure$__0-0)" IL_0049: stloc.s V_4 IL_004b: ldloc.s V_4 IL_004d: ldloc.3 IL_004e: callvirt "Function System.Collections.Generic.IEnumerator(Of Integer).get_Current() As Integer" IL_0053: stfld "m1._Closure$__0-0.$VB$Local_i As Integer" IL_0058: ldloc.0 IL_0059: ldloc.s V_4 IL_005b: ldfld "m1._Closure$__0-0.$VB$Local_i As Integer" IL_0060: ldloc.s V_4 IL_0062: ldftn "Sub m1._Closure$__0-0._Lambda$__1()" IL_0068: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_006d: stelem.ref IL_006e: ldloc.3 IL_006f: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0074: brtrue.s IL_0042 IL_0076: leave.s IL_0082 } finally { IL_0078: ldloc.3 IL_0079: brfalse.s IL_0081 IL_007b: ldloc.3 IL_007c: callvirt "Sub System.IDisposable.Dispose()" IL_0081: endfinally } IL_0082: ldc.i4.1 IL_0083: stloc.s V_5 IL_0085: ldloc.0 IL_0086: ldloc.s V_5 IL_0088: ldelem.ref IL_0089: callvirt "Sub System.Action.Invoke()" IL_008e: ldloc.s V_5 IL_0090: ldc.i4.1 IL_0091: add.ovf IL_0092: stloc.s V_5 IL_0094: ldloc.s V_5 IL_0096: ldc.i4.3 IL_0097: ble.s IL_0085 IL_0099: call "Sub System.Console.WriteLine()" IL_009e: ldloc.1 IL_009f: ldc.i4.1 IL_00a0: add.ovf IL_00a1: stloc.1 IL_00a2: ldloc.1 IL_00a3: ldc.i4.2 IL_00a4: ble IL_000a IL_00a9: ret } ]]>) End Sub <WorkItem(545519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545519")> <Fact()> Public Sub NewForEachScopeDev11_4() Dim source = <compilation> <file name="a.vb"> imports system imports system.collections.generic Module m1 Sub Main() ' Test Array Dim lambdas As New List(Of Action) 'Expected 0,1,2, 0,1,2, 0,1,2 lambdas.clear For y = 1 To 3 ' test lifting of control variable in loop body and lifting of control variable when used ' in the collection expression itself. The for each itself is nested in a for loop. For Each x as integer In (function(a) x = x + 1 return {a, x, 2} end function)(x) lambdas.add( Sub() Console.Write(x.ToString + "," ) ) Next lambdas.add(sub() Console.WriteLine()) Next For Each lambda In lambdas lambda() Next End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ 0,1,2, 0,1,2, 0,1,2, ]]>).VerifyIL("m1.Main", <![CDATA[ { // Code size 195 (0xc3) .maxstack 3 .locals init (System.Collections.Generic.List(Of System.Action) V_0, //lambdas Integer V_1, //y Object() V_2, Integer V_3, m1._Closure$__0-1 V_4, //$VB$Closure_0 System.Collections.Generic.List(Of System.Action).Enumerator V_5) IL_0000: newobj "Sub System.Collections.Generic.List(Of System.Action)..ctor()" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: callvirt "Sub System.Collections.Generic.List(Of System.Action).Clear()" IL_000c: ldc.i4.1 IL_000d: stloc.1 IL_000e: newobj "Sub m1._Closure$__0-0..ctor()" IL_0013: dup IL_0014: ldfld "m1._Closure$__0-0.$VB$NonLocal_2 As Integer" IL_0019: box "Integer" IL_001e: callvirt "Function m1._Closure$__0-0._Lambda$__0(Object) As Object()" IL_0023: stloc.2 IL_0024: ldc.i4.0 IL_0025: stloc.3 IL_0026: br.s IL_0057 IL_0028: ldloc.s V_4 IL_002a: newobj "Sub m1._Closure$__0-1..ctor(m1._Closure$__0-1)" IL_002f: stloc.s V_4 IL_0031: ldloc.s V_4 IL_0033: ldloc.2 IL_0034: ldloc.3 IL_0035: ldelem.ref IL_0036: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_003b: stfld "m1._Closure$__0-1.$VB$Local_x As Integer" IL_0040: ldloc.0 IL_0041: ldloc.s V_4 IL_0043: ldftn "Sub m1._Closure$__0-1._Lambda$__1()" IL_0049: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_004e: callvirt "Sub System.Collections.Generic.List(Of System.Action).Add(System.Action)" IL_0053: ldloc.3 IL_0054: ldc.i4.1 IL_0055: add.ovf IL_0056: stloc.3 IL_0057: ldloc.3 IL_0058: ldloc.2 IL_0059: ldlen IL_005a: conv.i4 IL_005b: blt.s IL_0028 IL_005d: ldloc.0 IL_005e: ldsfld "m1._Closure$__.$I0-2 As System.Action" IL_0063: brfalse.s IL_006c IL_0065: ldsfld "m1._Closure$__.$I0-2 As System.Action" IL_006a: br.s IL_0082 IL_006c: ldsfld "m1._Closure$__.$I As m1._Closure$__" IL_0071: ldftn "Sub m1._Closure$__._Lambda$__0-2()" IL_0077: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_007c: dup IL_007d: stsfld "m1._Closure$__.$I0-2 As System.Action" IL_0082: callvirt "Sub System.Collections.Generic.List(Of System.Action).Add(System.Action)" IL_0087: ldloc.1 IL_0088: ldc.i4.1 IL_0089: add.ovf IL_008a: stloc.1 IL_008b: ldloc.1 IL_008c: ldc.i4.3 IL_008d: ble IL_000e IL_0092: nop .try { IL_0093: ldloc.0 IL_0094: callvirt "Function System.Collections.Generic.List(Of System.Action).GetEnumerator() As System.Collections.Generic.List(Of System.Action).Enumerator" IL_0099: stloc.s V_5 IL_009b: br.s IL_00a9 IL_009d: ldloca.s V_5 IL_009f: call "Function System.Collections.Generic.List(Of System.Action).Enumerator.get_Current() As System.Action" IL_00a4: callvirt "Sub System.Action.Invoke()" IL_00a9: ldloca.s V_5 IL_00ab: call "Function System.Collections.Generic.List(Of System.Action).Enumerator.MoveNext() As Boolean" IL_00b0: brtrue.s IL_009d IL_00b2: leave.s IL_00c2 } finally { IL_00b4: ldloca.s V_5 IL_00b6: constrained. "System.Collections.Generic.List(Of System.Action).Enumerator" IL_00bc: callvirt "Sub System.IDisposable.Dispose()" IL_00c1: endfinally } IL_00c2: ret } ]]>) End Sub <Fact> Public Sub ForEachLateBinding() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict Off imports system Class C Shared Sub Main() Dim o As Object = {1, 2, 3} For Each x In o console.writeline(x) Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithModuleName("MODULE"), expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 84 (0x54) .maxstack 3 .locals init (Object V_0, //o System.Collections.IEnumerator V_1) IL_0000: ldc.i4.3 IL_0001: newarr "Integer" IL_0006: dup IL_0007: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D" IL_000c: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)" IL_0011: stloc.0 .try { IL_0012: ldloc.0 IL_0013: castclass "System.Collections.IEnumerable" IL_0018: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_001d: stloc.1 IL_001e: br.s IL_0035 IL_0020: ldloc.1 IL_0021: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0026: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_002b: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0030: call "Sub System.Console.WriteLine(Object)" IL_0035: ldloc.1 IL_0036: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_003b: brtrue.s IL_0020 IL_003d: leave.s IL_0053 } finally { IL_003f: ldloc.1 IL_0040: isinst "System.IDisposable" IL_0045: brfalse.s IL_0052 IL_0047: ldloc.1 IL_0048: isinst "System.IDisposable" IL_004d: callvirt "Sub System.IDisposable.Dispose()" IL_0052: endfinally } IL_0053: ret } ]]>).Compilation End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenForeach Inherits BasicTestBase ' The loop object must be an array or an object collection <Fact> Public Sub SimpleForeachTest() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C Shared Sub Main() Dim arr As String() = New String(1) {} arr(0) = "one" arr(1) = "two" For Each s As String In arr Console.WriteLine(s) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ one two ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 46 (0x2e) .maxstack 4 .locals init (String() V_0, Integer V_1) IL_0000: ldc.i4.2 IL_0001: newarr "String" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldstr "one" IL_000d: stelem.ref IL_000e: dup IL_000f: ldc.i4.1 IL_0010: ldstr "two" IL_0015: stelem.ref IL_0016: stloc.0 IL_0017: ldc.i4.0 IL_0018: stloc.1 IL_0019: br.s IL_0027 IL_001b: ldloc.0 IL_001c: ldloc.1 IL_001d: ldelem.ref IL_001e: call "Sub System.Console.WriteLine(String)" IL_0023: ldloc.1 IL_0024: ldc.i4.1 IL_0025: add.ovf IL_0026: stloc.1 IL_0027: ldloc.1 IL_0028: ldloc.0 IL_0029: ldlen IL_002a: conv.i4 IL_002b: blt.s IL_001b IL_002d: ret } ]]>).Compilation End Sub ' Type is not required in a foreach statement <Fact> Public Sub TypeIsNotRequiredTest() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System Class C Shared Sub Main() Dim myarray As Integer() = New Integer(2) {1, 2, 3} For Each item In myarray Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithModuleName("MODULE")).VerifyIL("C.Main", <![CDATA[ { // Code size 37 (0x25) .maxstack 3 .locals init (Integer() V_0, Integer V_1) IL_0000: ldc.i4.3 IL_0001: newarr "Integer" IL_0006: dup IL_0007: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D" IL_000c: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)" IL_0011: stloc.0 IL_0012: ldc.i4.0 IL_0013: stloc.1 IL_0014: br.s IL_001e IL_0016: ldloc.0 IL_0017: ldloc.1 IL_0018: ldelem.i4 IL_0019: pop IL_001a: ldloc.1 IL_001b: ldc.i4.1 IL_001c: add.ovf IL_001d: stloc.1 IL_001e: ldloc.1 IL_001f: ldloc.0 IL_0020: ldlen IL_0021: conv.i4 IL_0022: blt.s IL_0016 IL_0024: ret } ]]>) End Sub ' Narrowing conversions from the elements in group to element are evaluated and performed at run time <Fact> Public Sub NarrowConversions() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Class C Shared Sub Main() For Each number As Integer In New Long() {45, 3} Console.WriteLine(number) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 45 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 42 (0x2a) .maxstack 4 .locals init (Long() V_0, Integer V_1) IL_0000: ldc.i4.2 IL_0001: newarr "Long" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 45 IL_000a: conv.i8 IL_000b: stelem.i8 IL_000c: dup IL_000d: ldc.i4.1 IL_000e: ldc.i4.3 IL_000f: conv.i8 IL_0010: stelem.i8 IL_0011: stloc.0 IL_0012: ldc.i4.0 IL_0013: stloc.1 IL_0014: br.s IL_0023 IL_0016: ldloc.0 IL_0017: ldloc.1 IL_0018: ldelem.i8 IL_0019: conv.ovf.i4 IL_001a: call "Sub System.Console.WriteLine(Integer)" IL_001f: ldloc.1 IL_0020: ldc.i4.1 IL_0021: add.ovf IL_0022: stloc.1 IL_0023: ldloc.1 IL_0024: ldloc.0 IL_0025: ldlen IL_0026: conv.i4 IL_0027: blt.s IL_0016 IL_0029: ret } ]]>) End Sub ' Narrowing conversions from the elements in group to element are evaluated and performed at run time <Fact> Public Sub NarrowConversions_2() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Class C Shared Sub Main() For Each number As Integer In New Long() {9876543210} Console.WriteLine(number) Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 43 (0x2b) .maxstack 4 .locals init (Long() V_0, Integer V_1) IL_0000: ldc.i4.1 IL_0001: newarr "Long" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i8 0x24cb016ea IL_0011: stelem.i8 IL_0012: stloc.0 IL_0013: ldc.i4.0 IL_0014: stloc.1 IL_0015: br.s IL_0024 IL_0017: ldloc.0 IL_0018: ldloc.1 IL_0019: ldelem.i8 IL_001a: conv.ovf.i4 IL_001b: call "Sub System.Console.WriteLine(Integer)" IL_0020: ldloc.1 IL_0021: ldc.i4.1 IL_0022: add.ovf IL_0023: stloc.1 IL_0024: ldloc.1 IL_0025: ldloc.0 IL_0026: ldlen IL_0027: conv.i4 IL_0028: blt.s IL_0017 IL_002a: ret } ]]>) End Sub ' Multiline <Fact> Public Sub Multiline() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Class C Shared Public Sub Main() Dim a() As Integer = New Integer() {7} For Each x As Integer In a : System.Console.WriteLine(x) : Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 34 (0x22) .maxstack 4 .locals init (Integer() V_0, Integer V_1) IL_0000: ldc.i4.1 IL_0001: newarr "Integer" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.7 IL_0009: stelem.i4 IL_000a: stloc.0 IL_000b: ldc.i4.0 IL_000c: stloc.1 IL_000d: br.s IL_001b IL_000f: ldloc.0 IL_0010: ldloc.1 IL_0011: ldelem.i4 IL_0012: call "Sub System.Console.WriteLine(Integer)" IL_0017: ldloc.1 IL_0018: ldc.i4.1 IL_0019: add.ovf IL_001a: stloc.1 IL_001b: ldloc.1 IL_001c: ldloc.0 IL_001d: ldlen IL_001e: conv.i4 IL_001f: blt.s IL_000f IL_0021: ret } ]]>) End Sub ' Line continuations <Fact> Public Sub LineContinuations() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Class C Public Shared Sub Main() Dim a() As Integer = New Integer() {7} For _ Each _ x _ As _ Integer _ In _ a _ _ : Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 30 (0x1e) .maxstack 4 .locals init (Integer() V_0, Integer V_1) IL_0000: ldc.i4.1 IL_0001: newarr "Integer" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.7 IL_0009: stelem.i4 IL_000a: stloc.0 IL_000b: ldc.i4.0 IL_000c: stloc.1 IL_000d: br.s IL_0017 IL_000f: ldloc.0 IL_0010: ldloc.1 IL_0011: ldelem.i4 IL_0012: pop IL_0013: ldloc.1 IL_0014: ldc.i4.1 IL_0015: add.ovf IL_0016: stloc.1 IL_0017: ldloc.1 IL_0018: ldloc.0 IL_0019: ldlen IL_001a: conv.i4 IL_001b: blt.s IL_000f IL_001d: ret } ]]>) End Sub <Fact(), WorkItem(9151, "DevDiv_Projects/Roslyn"), WorkItem(546096, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546096")> Public Sub IterationVarInConditionalExpression() CompileAndVerify( <compilation> <file name="a.vb"> Option Strict Off Class C Shared Sub Main() For Each x As S In If(True, x, 1) Next End Sub End Class Public Structure S End Structure </file> </compilation>).VerifyIL("C.Main", <![CDATA[ { // Code size 77 (0x4d) .maxstack 2 .locals init (S V_0, System.Collections.IEnumerator V_1, S V_2) .try { IL_0000: ldloc.0 IL_0001: box "S" IL_0006: castclass "System.Collections.IEnumerable" IL_000b: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0010: stloc.1 IL_0011: br.s IL_002e IL_0013: ldloc.1 IL_0014: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0019: dup IL_001a: brtrue.s IL_0028 IL_001c: pop IL_001d: ldloca.s V_2 IL_001f: initobj "S" IL_0025: ldloc.2 IL_0026: br.s IL_002d IL_0028: unbox.any "S" IL_002d: pop IL_002e: ldloc.1 IL_002f: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0034: brtrue.s IL_0013 IL_0036: leave.s IL_004c } finally { IL_0038: ldloc.1 IL_0039: isinst "System.IDisposable" IL_003e: brfalse.s IL_004b IL_0040: ldloc.1 IL_0041: isinst "System.IDisposable" IL_0046: callvirt "Sub System.IDisposable.Dispose()" IL_004b: endfinally } IL_004c: ret } ]]>) End Sub ' Use the declared variable to initialize collection <Fact> Public Sub IterationVarInCollectionExpression_1() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() For Each x As Integer In New Integer() {x + 5, x + 6, x + 7} System.Console.WriteLine(x) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 5 6 7 ]]>) End Sub <Fact(), WorkItem(9151, "DevDiv_Projects/Roslyn"), WorkItem(546096, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546096")> Public Sub TraversingNothing() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict Off Class C Shared Sub Main() For Each item In Nothing Next End Sub End Class </file> </compilation>).VerifyIL("C.Main", <![CDATA[ { // Code size 52 (0x34) .maxstack 1 .locals init (System.Collections.IEnumerator V_0) .try { IL_0000: ldnull IL_0001: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0006: stloc.0 IL_0007: br.s IL_0015 IL_0009: ldloc.0 IL_000a: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_000f: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0014: pop IL_0015: ldloc.0 IL_0016: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_001b: brtrue.s IL_0009 IL_001d: leave.s IL_0033 } finally { IL_001f: ldloc.0 IL_0020: isinst "System.IDisposable" IL_0025: brfalse.s IL_0032 IL_0027: ldloc.0 IL_0028: isinst "System.IDisposable" IL_002d: callvirt "Sub System.IDisposable.Dispose()" IL_0032: endfinally } IL_0033: ret } ]]>) End Sub ' Nested ForEach can use a var declared in the outer ForEach <Fact> Public Sub NestedForeach() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim c(3)() As Integer For Each x As Integer() In c ReDim x(3) For i As Integer = 0 To 3 x(i) = i Next For Each y As Integer In x System .Console .WriteLine (y) Next Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 ]]>) End Sub ' Inner foreach loop referencing the outer foreach loop iteration variable <Fact> Public Sub NestedForeach_1() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim S As String() = New String() {"ABC", "XYZ"} For Each x As String In S For Each y As Char In x System.Console.WriteLine(y) Next Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ A B C X Y Z ]]>) End Sub ' Foreach value can't be modified in a loop <Fact> Public Sub ModifyIterationValueInLoop() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Collections Class C Shared Sub Main() Dim list As New ArrayList() list.Add("One") list.Add("Two") For Each s As String In list s = "a" Next For Each s As String In list System.Console.WriteLine(s) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ One Two ]]>) End Sub ' Pass fields as a ref argument for 'foreach iteration variable' <Fact()> Public Sub PassFieldsAsRefArgument() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim sa As S() = New S(2) {New S With {.I = 1}, New S With {.I = 2}, New S With {.I = 3}} For Each s As S In sa f(s.i) Next For Each s As S In sa System.Console.WriteLine(s.i) Next End Sub Private Shared Sub f(ByRef iref As Integer) iref = 1 End Sub End Class Structure S Public I As integer End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>) End Sub ' With multidimensional arrays, you can use one loop to iterate through the elements <Fact> Public Sub TraversingMultidimensionalArray() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim numbers2D(,) As Integer = New Integer (2,1) {} numbers2D(0,0) = 9 numbers2D(0,1) = 99 numbers2D(1,0) = 3 numbers2D(1,1) = 33 numbers2D(2,0) = 5 numbers2D(2,1) = 55 For Each i As Integer In numbers2D System.Console.WriteLine(i) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 9 99 3 33 5 55 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 98 (0x62) .maxstack 5 .locals init (System.Collections.IEnumerator V_0) IL_0000: ldc.i4.3 IL_0001: ldc.i4.2 IL_0002: newobj "Integer(*,*)..ctor" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.0 IL_000a: ldc.i4.s 9 IL_000c: call "Integer(*,*).Set" IL_0011: dup IL_0012: ldc.i4.0 IL_0013: ldc.i4.1 IL_0014: ldc.i4.s 99 IL_0016: call "Integer(*,*).Set" IL_001b: dup IL_001c: ldc.i4.1 IL_001d: ldc.i4.0 IL_001e: ldc.i4.3 IL_001f: call "Integer(*,*).Set" IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.1 IL_0027: ldc.i4.s 33 IL_0029: call "Integer(*,*).Set" IL_002e: dup IL_002f: ldc.i4.2 IL_0030: ldc.i4.0 IL_0031: ldc.i4.5 IL_0032: call "Integer(*,*).Set" IL_0037: dup IL_0038: ldc.i4.2 IL_0039: ldc.i4.1 IL_003a: ldc.i4.s 55 IL_003c: call "Integer(*,*).Set" IL_0041: callvirt "Function System.Array.GetEnumerator() As System.Collections.IEnumerator" IL_0046: stloc.0 IL_0047: br.s IL_0059 IL_0049: ldloc.0 IL_004a: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_004f: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_0054: call "Sub System.Console.WriteLine(Integer)" IL_0059: ldloc.0 IL_005a: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_005f: brtrue.s IL_0049 IL_0061: ret } ]]>) End Sub ' Traversing jagged arrays <Fact> Public Sub TraversingJaggedArray() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim numbers2D As Integer()() = New Integer()() {New Integer() {1, 2}, New Integer() {4, 5, 6}} For Each x As Integer() In numbers2D For Each y As Integer In x System.Console.WriteLine(y) Next Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 4 5 6 ]]>) End Sub ' Optimization to foreach (char c in String) by treating String as a char array <Fact()> Public Sub TraversingString() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() Dim str As String = "ABC" For Each x In str System.Console.WriteLine(x) Next For Each var In "goo" If Not var.[GetType]().Equals(GetType(Char)) Then System.Console.WriteLine("False") End If Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ A B C ]]>) End Sub ' Traversing items in Dictionary <Fact> Public Sub TraversingDictionary() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections.Generic Class C Public Shared Sub Main() Dim s As New Dictionary(Of Integer, Integer)() s.Add(1, 2) s.Add(2, 3) s.Add(3, 4) For Each pair In s System .Console .WriteLine (pair.Key) Next For Each pair As KeyValuePair(Of Integer, Integer) In s System .Console .WriteLine (pair.Value ) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 2 3 4 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 141 (0x8d) .maxstack 3 .locals init (System.Collections.Generic.Dictionary(Of Integer, Integer) V_0, //s System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator V_1, System.Collections.Generic.KeyValuePair(Of Integer, Integer) V_2, //pair System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator V_3, System.Collections.Generic.KeyValuePair(Of Integer, Integer) V_4) //pair IL_0000: newobj "Sub System.Collections.Generic.Dictionary(Of Integer, Integer)..ctor()" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: ldc.i4.2 IL_0009: callvirt "Sub System.Collections.Generic.Dictionary(Of Integer, Integer).Add(Integer, Integer)" IL_000e: ldloc.0 IL_000f: ldc.i4.2 IL_0010: ldc.i4.3 IL_0011: callvirt "Sub System.Collections.Generic.Dictionary(Of Integer, Integer).Add(Integer, Integer)" IL_0016: ldloc.0 IL_0017: ldc.i4.3 IL_0018: ldc.i4.4 IL_0019: callvirt "Sub System.Collections.Generic.Dictionary(Of Integer, Integer).Add(Integer, Integer)" .try { IL_001e: ldloc.0 IL_001f: callvirt "Function System.Collections.Generic.Dictionary(Of Integer, Integer).GetEnumerator() As System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator" IL_0024: stloc.1 IL_0025: br.s IL_003b IL_0027: ldloca.s V_1 IL_0029: call "Function System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator.get_Current() As System.Collections.Generic.KeyValuePair(Of Integer, Integer)" IL_002e: stloc.2 IL_002f: ldloca.s V_2 IL_0031: call "Function System.Collections.Generic.KeyValuePair(Of Integer, Integer).get_Key() As Integer" IL_0036: call "Sub System.Console.WriteLine(Integer)" IL_003b: ldloca.s V_1 IL_003d: call "Function System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator.MoveNext() As Boolean" IL_0042: brtrue.s IL_0027 IL_0044: leave.s IL_0054 } finally { IL_0046: ldloca.s V_1 IL_0048: constrained. "System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator" IL_004e: callvirt "Sub System.IDisposable.Dispose()" IL_0053: endfinally } IL_0054: nop .try { IL_0055: ldloc.0 IL_0056: callvirt "Function System.Collections.Generic.Dictionary(Of Integer, Integer).GetEnumerator() As System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator" IL_005b: stloc.3 IL_005c: br.s IL_0073 IL_005e: ldloca.s V_3 IL_0060: call "Function System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator.get_Current() As System.Collections.Generic.KeyValuePair(Of Integer, Integer)" IL_0065: stloc.s V_4 IL_0067: ldloca.s V_4 IL_0069: call "Function System.Collections.Generic.KeyValuePair(Of Integer, Integer).get_Value() As Integer" IL_006e: call "Sub System.Console.WriteLine(Integer)" IL_0073: ldloca.s V_3 IL_0075: call "Function System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator.MoveNext() As Boolean" IL_007a: brtrue.s IL_005e IL_007c: leave.s IL_008c } finally { IL_007e: ldloca.s V_3 IL_0080: constrained. "System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator" IL_0086: callvirt "Sub System.IDisposable.Dispose()" IL_008b: endfinally } IL_008c: ret } ]]>) End Sub ' Breaking from nested Loops <Fact> Public Sub BreakFromForeach() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim S As String() = New String() {"ABC", "XYZ"} For Each x As String In S For Each y As Char In x If y = "B"c Then Exit For Else System.Console.WriteLine(y) End If Next Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ A X Y Z ]]>) End Sub ' Continuing for nested Loops <Fact> Public Sub ContinueInForeach() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim S As String() = New String() {"ABC", "XYZ"} For Each x As String In S For Each y As Char In x If y = "B"c Then Continue For End If System.Console.WriteLine(y) Next y, x End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ A C X Y Z ]]>) End Sub ' Query expression works in foreach <Fact()> Public Sub QueryExpressionInForeach() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict Off Option Infer On Imports System Imports System.Collections Imports System.Linq Class C Public Shared Sub Main() For Each x In From w In New Integer() {1, 2, 3} Select z = w.ToString() System.Console.WriteLine(x.ToLower()) Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithModuleName("MODULE"), references:={LinqAssemblyRef}, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 103 (0x67) .maxstack 3 .locals init (System.Collections.Generic.IEnumerator(Of String) V_0) .try { IL_0000: ldc.i4.3 IL_0001: newarr "Integer" IL_0006: dup IL_0007: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D" IL_000c: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)" IL_0011: ldsfld "C._Closure$__.$I1-0 As System.Func(Of Integer, String)" IL_0016: brfalse.s IL_001f IL_0018: ldsfld "C._Closure$__.$I1-0 As System.Func(Of Integer, String)" IL_001d: br.s IL_0035 IL_001f: ldsfld "C._Closure$__.$I As C._Closure$__" IL_0024: ldftn "Function C._Closure$__._Lambda$__1-0(Integer) As String" IL_002a: newobj "Sub System.Func(Of Integer, String)..ctor(Object, System.IntPtr)" IL_002f: dup IL_0030: stsfld "C._Closure$__.$I1-0 As System.Func(Of Integer, String)" IL_0035: call "Function System.Linq.Enumerable.Select(Of Integer, String)(System.Collections.Generic.IEnumerable(Of Integer), System.Func(Of Integer, String)) As System.Collections.Generic.IEnumerable(Of String)" IL_003a: callvirt "Function System.Collections.Generic.IEnumerable(Of String).GetEnumerator() As System.Collections.Generic.IEnumerator(Of String)" IL_003f: stloc.0 IL_0040: br.s IL_0052 IL_0042: ldloc.0 IL_0043: callvirt "Function System.Collections.Generic.IEnumerator(Of String).get_Current() As String" IL_0048: callvirt "Function String.ToLower() As String" IL_004d: call "Sub System.Console.WriteLine(String)" IL_0052: ldloc.0 IL_0053: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0058: brtrue.s IL_0042 IL_005a: leave.s IL_0066 } finally { IL_005c: ldloc.0 IL_005d: brfalse.s IL_0065 IL_005f: ldloc.0 IL_0060: callvirt "Sub System.IDisposable.Dispose()" IL_0065: endfinally } IL_0066: ret } ]]>) End Sub ' No confusion in a foreach statement when from is a value type <Fact> Public Sub ReDimFrom() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() Dim src = New System.Collections.ArrayList() src.Add(new from(1)) For Each x As from In src System.Console.WriteLine(x.X) Next End Sub End Class Public Structure from Dim X As Integer Public Sub New(p as integer) x = p End Sub End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 ]]>) End Sub ' Foreach on generic type that implements the Collection Pattern <Fact> Public Sub GenericTypeImplementsCollection() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections.Generic Class C Public Shared Sub Main() For Each j In New Gen(Of Integer)() Next End Sub End Class Public Class Gen(Of T As New) Public Function GetEnumerator() As IEnumerator(Of T) Return Nothing End Function End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 41 (0x29) .maxstack 1 .locals init (System.Collections.Generic.IEnumerator(Of Integer) V_0) .try { IL_0000: newobj "Sub Gen(Of Integer)..ctor()" IL_0005: call "Function Gen(Of Integer).GetEnumerator() As System.Collections.Generic.IEnumerator(Of Integer)" IL_000a: stloc.0 IL_000b: br.s IL_0014 IL_000d: ldloc.0 IL_000e: callvirt "Function System.Collections.Generic.IEnumerator(Of Integer).get_Current() As Integer" IL_0013: pop IL_0014: ldloc.0 IL_0015: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_001a: brtrue.s IL_000d IL_001c: leave.s IL_0028 } finally { IL_001e: ldloc.0 IL_001f: brfalse.s IL_0027 IL_0021: ldloc.0 IL_0022: callvirt "Sub System.IDisposable.Dispose()" IL_0027: endfinally } IL_0028: ret } ]]>) End Sub ' Customer defined type of collection to support 'foreach' <Fact> Public Sub CustomerDefinedCollections() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C Public Shared Sub Main() Dim col As New MyCollection() For Each i As Integer In col Console.WriteLine(i) Next End Sub End Class Public Class MyCollection Private items As Integer() Public Sub New() items = New Integer(4) {1, 4, 3, 2, 5} End Sub Public Function GetEnumerator() As MyEnumerator Return New MyEnumerator(Me) End Function Public Class MyEnumerator Private nIndex As Integer Private collection As MyCollection Public Sub New(coll As MyCollection) collection = coll nIndex = nIndex - 1 End Sub Public Function MoveNext() As Boolean nIndex = nIndex + 1 Return (nIndex &lt; collection.items.GetLength(0)) End Function Public ReadOnly Property Current() As Integer Get Return (collection.items(nIndex)) End Get End Property End Class End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 4 3 2 5 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 33 (0x21) .maxstack 1 .locals init (MyCollection.MyEnumerator V_0) IL_0000: newobj "Sub MyCollection..ctor()" IL_0005: callvirt "Function MyCollection.GetEnumerator() As MyCollection.MyEnumerator" IL_000a: stloc.0 IL_000b: br.s IL_0018 IL_000d: ldloc.0 IL_000e: callvirt "Function MyCollection.MyEnumerator.get_Current() As Integer" IL_0013: call "Sub System.Console.WriteLine(Integer)" IL_0018: ldloc.0 IL_0019: callvirt "Function MyCollection.MyEnumerator.MoveNext() As Boolean" IL_001e: brtrue.s IL_000d IL_0020: ret } ]]>) End Sub <Fact> Public Sub TestForEachPattern() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class Class Enumerator Private x As Integer = 0 Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 33 (0x21) .maxstack 1 .locals init (Enumerator V_0) IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0018 IL_000d: ldloc.0 IL_000e: callvirt "Function Enumerator.get_Current() As Integer" IL_0013: call "Sub System.Console.WriteLine(Integer)" IL_0018: ldloc.0 IL_0019: callvirt "Function Enumerator.MoveNext() As Boolean" IL_001e: brtrue.s IL_000d IL_0020: ret } ]]>) End Sub <Fact> Public Sub TestForEachInterface() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Implements System.Collections.IEnumerable ' Explicit implementation won't match pattern. Private Function System_Collections_IEnumerable_GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Dim list As New System.Collections.Generic.List(Of Integer)() list.Add(3) list.Add(2) list.Add(1) Return list.GetEnumerator() End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ 3 2 1 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 65 (0x41) .maxstack 1 .locals init (System.Collections.IEnumerator V_0) .try { IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_000a: stloc.0 IL_000b: br.s IL_0022 IL_000d: ldloc.0 IL_000e: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0013: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0018: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001d: call "Sub System.Console.WriteLine(Object)" IL_0022: ldloc.0 IL_0023: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0028: brtrue.s IL_000d IL_002a: leave.s IL_0040 } finally { IL_002c: ldloc.0 IL_002d: isinst "System.IDisposable" IL_0032: brfalse.s IL_003f IL_0034: ldloc.0 IL_0035: isinst "System.IDisposable" IL_003a: callvirt "Sub System.IDisposable.Dispose()" IL_003f: endfinally } IL_0040: ret } ]]>) End Sub <Fact> Public Sub TestForEachExplicitlyDisposableStruct() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class Structure Enumerator Implements System.IDisposable Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function Private Sub System_IDisposable_Dispose() Implements System.IDisposable.Dispose End Sub End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 51 (0x33) .maxstack 1 .locals init (Enumerator V_0) .try { IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0019 IL_000d: ldloca.s V_0 IL_000f: call "Function Enumerator.get_Current() As Integer" IL_0014: call "Sub System.Console.WriteLine(Integer)" IL_0019: ldloca.s V_0 IL_001b: call "Function Enumerator.MoveNext() As Boolean" IL_0020: brtrue.s IL_000d IL_0022: leave.s IL_0032 } finally { IL_0024: ldloca.s V_0 IL_0026: constrained. "Enumerator" IL_002c: callvirt "Sub System.IDisposable.Dispose()" IL_0031: endfinally } IL_0032: ret } ]]>) End Sub <Fact> Public Sub TestForEachDisposeStruct() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class Structure Enumerator Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function Public Sub Dispose() End Sub End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 35 (0x23) .maxstack 1 .locals init (Enumerator V_0) IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0019 IL_000d: ldloca.s V_0 IL_000f: call "Function Enumerator.get_Current() As Integer" IL_0014: call "Sub System.Console.WriteLine(Integer)" IL_0019: ldloca.s V_0 IL_001b: call "Function Enumerator.MoveNext() As Boolean" IL_0020: brtrue.s IL_000d IL_0022: ret } ]]>) End Sub <Fact> Public Sub TestForEachNonDisposableStruct() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class Structure Enumerator Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 35 (0x23) .maxstack 1 .locals init (Enumerator V_0) IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0019 IL_000d: ldloca.s V_0 IL_000f: call "Function Enumerator.get_Current() As Integer" IL_0014: call "Sub System.Console.WriteLine(Integer)" IL_0019: ldloca.s V_0 IL_001b: call "Function Enumerator.MoveNext() As Boolean" IL_0020: brtrue.s IL_000d IL_0022: ret } ]]>) End Sub <Fact> Public Sub TestForEachExplicitlyGetEnumeratorStruct() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Structure Enumerable Implements IEnumerable Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return New Integer() {1, 2, 3}.GetEnumerator() End Function End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 79 (0x4f) .maxstack 1 .locals init (System.Collections.IEnumerator V_0, Enumerable V_1) .try { IL_0000: ldloca.s V_1 IL_0002: initobj "Enumerable" IL_0008: ldloc.1 IL_0009: box "Enumerable" IL_000e: castclass "System.Collections.IEnumerable" IL_0013: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0018: stloc.0 IL_0019: br.s IL_0030 IL_001b: ldloc.0 IL_001c: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0021: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0026: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_002b: call "Sub System.Console.WriteLine(Object)" IL_0030: ldloc.0 IL_0031: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0036: brtrue.s IL_001b IL_0038: leave.s IL_004e } finally { IL_003a: ldloc.0 IL_003b: isinst "System.IDisposable" IL_0040: brfalse.s IL_004d IL_0042: ldloc.0 IL_0043: isinst "System.IDisposable" IL_0048: callvirt "Sub System.IDisposable.Dispose()" IL_004d: endfinally } IL_004e: ret } ]]>) End Sub <Fact> Public Sub TestForEachGetEnumeratorStruct() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Structure Enumerable Public Function GetEnumerator() As IEnumerator Return New Integer() {1, 2, 3}.GetEnumerator() End Function End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 72 (0x48) .maxstack 1 .locals init (System.Collections.IEnumerator V_0, Enumerable V_1) .try { IL_0000: ldloca.s V_1 IL_0002: initobj "Enumerable" IL_0008: ldloc.1 IL_0009: stloc.1 IL_000a: ldloca.s V_1 IL_000c: call "Function Enumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0011: stloc.0 IL_0012: br.s IL_0029 IL_0014: ldloc.0 IL_0015: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_001a: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001f: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0024: call "Sub System.Console.WriteLine(Object)" IL_0029: ldloc.0 IL_002a: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_002f: brtrue.s IL_0014 IL_0031: leave.s IL_0047 } finally { IL_0033: ldloc.0 IL_0034: isinst "System.IDisposable" IL_0039: brfalse.s IL_0046 IL_003b: ldloc.0 IL_003c: isinst "System.IDisposable" IL_0041: callvirt "Sub System.IDisposable.Dispose()" IL_0046: endfinally } IL_0047: ret } ]]>) End Sub <Fact> Public Sub TestForEachDisposableSealed() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class NotInheritable Class Enumerator Implements System.IDisposable Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function Private Sub System_IDisposable_Dispose() Implements System.IDisposable.Dispose End Sub End Class Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 45 (0x2d) .maxstack 1 .locals init (Enumerator V_0) .try { IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0018 IL_000d: ldloc.0 IL_000e: callvirt "Function Enumerator.get_Current() As Integer" IL_0013: call "Sub System.Console.WriteLine(Integer)" IL_0018: ldloc.0 IL_0019: callvirt "Function Enumerator.MoveNext() As Boolean" IL_001e: brtrue.s IL_000d IL_0020: leave.s IL_002c } finally { IL_0022: ldloc.0 IL_0023: brfalse.s IL_002b IL_0025: ldloc.0 IL_0026: callvirt "Sub System.IDisposable.Dispose()" IL_002b: endfinally } IL_002c: ret } ]]>) End Sub <Fact> Public Sub TestForEachNonDisposableSealed() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class NotInheritable Class Enumerator Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 33 (0x21) .maxstack 1 .locals init (Enumerator V_0) IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0018 IL_000d: ldloc.0 IL_000e: callvirt "Function Enumerator.get_Current() As Integer" IL_0013: call "Sub System.Console.WriteLine(Integer)" IL_0018: ldloc.0 IL_0019: callvirt "Function Enumerator.MoveNext() As Boolean" IL_001e: brtrue.s IL_000d IL_0020: ret } ]]>) End Sub <Fact> Public Sub TestForEachNonDisposableAbstractClass() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable1() System.Console.WriteLine(x) Next For Each x In New Enumerable2() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable1 Public Function GetEnumerator() As AbstractEnumerator Return New DisposableEnumerator() End Function End Class Class Enumerable2 Public Function GetEnumerator() As AbstractEnumerator Return New NonDisposableEnumerator() End Function End Class MustInherit Class AbstractEnumerator Public MustOverride ReadOnly Property Current() As Integer Public MustOverride Function MoveNext() As Boolean End Class Class DisposableEnumerator Inherits AbstractEnumerator Implements System.IDisposable Private x As Integer Public Overrides ReadOnly Property Current() As Integer Get Return x End Get End Property Public Overrides Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function Private Sub System_IDisposable_Dispose() Implements System.IDisposable.Dispose System.Console.WriteLine("Done with DisposableEnumerator") End Sub End Class Class NonDisposableEnumerator Inherits AbstractEnumerator Private x As Integer Public Overrides ReadOnly Property Current() As Integer Get Return x End Get End Property Public Overrides Function MoveNext() As Boolean Return System.Threading.Interlocked.Decrement(x) &gt; -4 End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 -1 -2 -3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 65 (0x41) .maxstack 1 .locals init (AbstractEnumerator V_0, AbstractEnumerator V_1) IL_0000: newobj "Sub Enumerable1..ctor()" IL_0005: call "Function Enumerable1.GetEnumerator() As AbstractEnumerator" IL_000a: stloc.0 IL_000b: br.s IL_0018 IL_000d: ldloc.0 IL_000e: callvirt "Function AbstractEnumerator.get_Current() As Integer" IL_0013: call "Sub System.Console.WriteLine(Integer)" IL_0018: ldloc.0 IL_0019: callvirt "Function AbstractEnumerator.MoveNext() As Boolean" IL_001e: brtrue.s IL_000d IL_0020: newobj "Sub Enumerable2..ctor()" IL_0025: call "Function Enumerable2.GetEnumerator() As AbstractEnumerator" IL_002a: stloc.1 IL_002b: br.s IL_0038 IL_002d: ldloc.1 IL_002e: callvirt "Function AbstractEnumerator.get_Current() As Integer" IL_0033: call "Sub System.Console.WriteLine(Integer)" IL_0038: ldloc.1 IL_0039: callvirt "Function AbstractEnumerator.MoveNext() As Boolean" IL_003e: brtrue.s IL_002d IL_0040: ret } ]]>) End Sub <WorkItem(528679, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528679")> <Fact> Public Sub TestForEachNested() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer on Class C Public Shared Sub Main() For Each x In New Enumerable() For Each y In New Enumerable() System.Console.WriteLine("({0}, {1})", x, y) Next Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class Class Enumerator Private x As Integer = 0 Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ (1, 1) (1, 2) (1, 3) (2, 1) (2, 2) (2, 3) (3, 1) (3, 2) (3, 3) ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 79 (0x4f) .maxstack 3 .locals init (Enumerator V_0, Integer V_1, //x Enumerator V_2, Integer V_3) //y IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0046 IL_000d: ldloc.0 IL_000e: callvirt "Function Enumerator.get_Current() As Integer" IL_0013: stloc.1 IL_0014: newobj "Sub Enumerable..ctor()" IL_0019: call "Function Enumerable.GetEnumerator() As Enumerator" IL_001e: stloc.2 IL_001f: br.s IL_003e IL_0021: ldloc.2 IL_0022: callvirt "Function Enumerator.get_Current() As Integer" IL_0027: stloc.3 IL_0028: ldstr "({0}, {1})" IL_002d: ldloc.1 IL_002e: box "Integer" IL_0033: ldloc.3 IL_0034: box "Integer" IL_0039: call "Sub System.Console.WriteLine(String, Object, Object)" IL_003e: ldloc.2 IL_003f: callvirt "Function Enumerator.MoveNext() As Boolean" IL_0044: brtrue.s IL_0021 IL_0046: ldloc.0 IL_0047: callvirt "Function Enumerator.MoveNext() As Boolean" IL_004c: brtrue.s IL_000d IL_004e: ret } ]]>) End Sub <WorkItem(542075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542075")> <Fact> Public Sub TestGetEnumeratorWithParams() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections.Generic Imports System Class C public Shared Sub Main() For Each x In New B() Console.WriteLine(x.ToLower()) Next End Sub End Class Class A Public Function GetEnumerator() As List(Of String).Enumerator Dim s = New List(Of String)() s.Add("A") s.Add("B") s.Add("C") Return s.GetEnumerator() End Function End Class Class B Inherits A Public Overloads Function GetEnumerator(ParamArray x As Integer()) As List(Of Integer).Enumerator Return nothing End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ a b c ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 56 (0x38) .maxstack 1 .locals init (System.Collections.Generic.List(Of String).Enumerator V_0) .try { IL_0000: newobj "Sub B..ctor()" IL_0005: call "Function A.GetEnumerator() As System.Collections.Generic.List(Of String).Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_001e IL_000d: ldloca.s V_0 IL_000f: call "Function System.Collections.Generic.List(Of String).Enumerator.get_Current() As String" IL_0014: callvirt "Function String.ToLower() As String" IL_0019: call "Sub System.Console.WriteLine(String)" IL_001e: ldloca.s V_0 IL_0020: call "Function System.Collections.Generic.List(Of String).Enumerator.MoveNext() As Boolean" IL_0025: brtrue.s IL_000d IL_0027: leave.s IL_0037 } finally { IL_0029: ldloca.s V_0 IL_002b: constrained. "System.Collections.Generic.List(Of String).Enumerator" IL_0031: callvirt "Sub System.IDisposable.Dispose()" IL_0036: endfinally } IL_0037: ret } ]]>) End Sub <Fact> Public Sub TestMoveNextWithNonBoolDeclaredReturnType() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections Class Program Public Shared Sub Main() Goo(sub(x) For Each y In x Next end sub ) End Sub Public Shared Sub Goo(a As System.Action(Of IEnumerable)) System.Console.WriteLine(1) End Sub End Class Class A Public Function GetEnumerator() As E(Of Boolean) Return New E(Of Boolean)() End Function End Class Class E(Of T) Public Function MoveNext() As T Return Nothing End Function Public Property Current() As Integer Get Return m_Current End Get Set(value As Integer) m_Current = Value End Set End Property Private m_Current As Integer End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 ]]>) End Sub <Fact()> Public Sub TestNonConstantNullInForeach() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class Program Public Shared Sub Main() Try Const s As String = Nothing For Each y In TryCast(s, String) Next Catch generatedExceptionName As System.NullReferenceException System.Console.WriteLine(1) End Try End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 ]]>) End Sub <WorkItem(542079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542079")> <Fact> Public Sub TestForEachStructEnumerable() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections Class C public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Structure Enumerable Implements IEnumerable Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return New Integer() {1, 2, 3}.GetEnumerator() End Function End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 79 (0x4f) .maxstack 1 .locals init (System.Collections.IEnumerator V_0, Enumerable V_1) .try { IL_0000: ldloca.s V_1 IL_0002: initobj "Enumerable" IL_0008: ldloc.1 IL_0009: box "Enumerable" IL_000e: castclass "System.Collections.IEnumerable" IL_0013: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0018: stloc.0 IL_0019: br.s IL_0030 IL_001b: ldloc.0 IL_001c: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0021: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0026: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_002b: call "Sub System.Console.WriteLine(Object)" IL_0030: ldloc.0 IL_0031: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0036: brtrue.s IL_001b IL_0038: leave.s IL_004e } finally { IL_003a: ldloc.0 IL_003b: isinst "System.IDisposable" IL_0040: brfalse.s IL_004d IL_0042: ldloc.0 IL_0043: isinst "System.IDisposable" IL_0048: callvirt "Sub System.IDisposable.Dispose()" IL_004d: endfinally } IL_004e: ret } ]]>) End Sub <Fact> Public Sub TestForEachMutableStructEnumerablePattern() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() Dim e As New Enumerable() System.Console.WriteLine(e.i) For Each x In e Next System.Console.WriteLine(e.i) End Sub End Class Structure Enumerable Public i As Integer Public Function GetEnumerator() As Enumerator i = i + 1 Return New Enumerator() End Function End Structure Structure Enumerator Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 0 1 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 58 (0x3a) .maxstack 1 .locals init (Enumerable V_0, //e Enumerator V_1) IL_0000: ldloca.s V_0 IL_0002: initobj "Enumerable" IL_0008: ldloc.0 IL_0009: ldfld "Enumerable.i As Integer" IL_000e: call "Sub System.Console.WriteLine(Integer)" IL_0013: ldloca.s V_0 IL_0015: call "Function Enumerable.GetEnumerator() As Enumerator" IL_001a: stloc.1 IL_001b: br.s IL_0025 IL_001d: ldloca.s V_1 IL_001f: call "Function Enumerator.get_Current() As Integer" IL_0024: pop IL_0025: ldloca.s V_1 IL_0027: call "Function Enumerator.MoveNext() As Boolean" IL_002c: brtrue.s IL_001d IL_002e: ldloc.0 IL_002f: ldfld "Enumerable.i As Integer" IL_0034: call "Sub System.Console.WriteLine(Integer)" IL_0039: ret } ]]>) End Sub <WorkItem(542079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542079")> <Fact> Public Sub TestForEachMutableStructEnumerableInterface() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections Class C Public Shared Sub Main() Dim e As New Enumerable() System.Console.WriteLine(e.i) For Each x In e Next System.Console.WriteLine(e.i) End Sub End Class Structure Enumerable Implements IEnumerable Public i As Integer Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator i = i + 1 Return New Enumerator() End Function End Structure Structure Enumerator Implements IEnumerator Private x As Integer Public ReadOnly Property Current() As Object Implements IEnumerator.Current Get Return x End Get End Property Public Function MoveNext() As Boolean Implements IEnumerator.MoveNext Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function Public Sub Reset() Implements IEnumerator.Reset x = 0 End Sub End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 0 0 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 92 (0x5c) .maxstack 1 .locals init (Enumerable V_0, //e System.Collections.IEnumerator V_1) IL_0000: ldloca.s V_0 IL_0002: initobj "Enumerable" IL_0008: ldloc.0 IL_0009: ldfld "Enumerable.i As Integer" IL_000e: call "Sub System.Console.WriteLine(Integer)" .try { IL_0013: ldloc.0 IL_0014: box "Enumerable" IL_0019: castclass "System.Collections.IEnumerable" IL_001e: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0023: stloc.1 IL_0024: br.s IL_0032 IL_0026: ldloc.1 IL_0027: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_002c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0031: pop IL_0032: ldloc.1 IL_0033: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0038: brtrue.s IL_0026 IL_003a: leave.s IL_0050 } finally { IL_003c: ldloc.1 IL_003d: isinst "System.IDisposable" IL_0042: brfalse.s IL_004f IL_0044: ldloc.1 IL_0045: isinst "System.IDisposable" IL_004a: callvirt "Sub System.IDisposable.Dispose()" IL_004f: endfinally } IL_0050: ldloc.0 IL_0051: ldfld "Enumerable.i As Integer" IL_0056: call "Sub System.Console.WriteLine(Integer)" IL_005b: ret } ]]>) End Sub <Fact()> Public Sub TypeParameterAsEnumeratorTypeCanBeReferenceType() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports System.Collections Public Class Custom(Of S As {IEnumerator, IDisposable}) Public Function GetEnumerator() As S Return Nothing End Function End Class Class C1(Of S As {IEnumerator, IDisposable}) Public Sub DoStuff() Dim myCustomCollection As Custom(Of S) = nothing For Each element In myCustomCollection Console.WriteLine("goo") Next End Sub End Class Class C2 Public Shared Sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C1(Of S).DoStuff", <![CDATA[ { // Code size 80 (0x50) .maxstack 1 .locals init (Custom(Of S) V_0, //myCustomCollection S V_1) IL_0000: ldnull IL_0001: stloc.0 .try { IL_0002: ldloc.0 IL_0003: callvirt "Function Custom(Of S).GetEnumerator() As S" IL_0008: stloc.1 IL_0009: br.s IL_0028 IL_000b: ldloca.s V_1 IL_000d: constrained. "S" IL_0013: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0018: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001d: pop IL_001e: ldstr "goo" IL_0023: call "Sub System.Console.WriteLine(String)" IL_0028: ldloca.s V_1 IL_002a: constrained. "S" IL_0030: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0035: brtrue.s IL_000b IL_0037: leave.s IL_004f } finally { IL_0039: ldloc.1 IL_003a: box "S" IL_003f: brfalse.s IL_004e IL_0041: ldloca.s V_1 IL_0043: constrained. "S" IL_0049: callvirt "Sub System.IDisposable.Dispose()" IL_004e: endfinally } IL_004f: ret } ]]>) End Sub <Fact()> Public Sub TypeParameterAsEnumeratorTypeHasValueConstraint() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports System.Collections Public Class Custom(Of S As {IEnumerator, IDisposable, Structure}) Public Function GetEnumerator() As S Return Nothing End Function End Class Class C1(Of S As {IEnumerator, IDisposable, Structure}) Public Sub DoStuff() Dim myCustomCollection As Custom(Of S) = nothing For Each element In myCustomCollection Console.WriteLine("goo") Next End Sub End Class Class C2 Public Shared Sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C1(Of S).DoStuff", <![CDATA[ { // Code size 72 (0x48) .maxstack 1 .locals init (Custom(Of S) V_0, //myCustomCollection S V_1) IL_0000: ldnull IL_0001: stloc.0 .try { IL_0002: ldloc.0 IL_0003: callvirt "Function Custom(Of S).GetEnumerator() As S" IL_0008: stloc.1 IL_0009: br.s IL_0028 IL_000b: ldloca.s V_1 IL_000d: constrained. "S" IL_0013: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0018: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001d: pop IL_001e: ldstr "goo" IL_0023: call "Sub System.Console.WriteLine(String)" IL_0028: ldloca.s V_1 IL_002a: constrained. "S" IL_0030: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0035: brtrue.s IL_000b IL_0037: leave.s IL_0047 } finally { IL_0039: ldloca.s V_1 IL_003b: constrained. "S" IL_0041: callvirt "Sub System.IDisposable.Dispose()" IL_0046: endfinally } IL_0047: ret } ]]>) End Sub <Fact> Public Sub NoObjectCopyForGetCurrent() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System Imports System.Collections.Generic Class C2 Public Structure S1 Public Field as Integer Public Sub New(x as integer) Field = x End Sub End Structure Public Shared Sub Main() dim coll = New List(Of S1) coll.add(new S1(23)) coll.add(new S1(42)) DoStuff(coll) End Sub Public Shared Sub DoStuff(coll as System.Collections.IEnumerable) for each x as Object in coll Console.WriteLine(Directcast(x,S1).Field) next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 23 42 ]]>).VerifyIL("C2.DoStuff", <![CDATA[ { // Code size 66 (0x42) .maxstack 1 .locals init (System.Collections.IEnumerator V_0) .try { IL_0000: ldarg.0 IL_0001: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0006: stloc.0 IL_0007: br.s IL_0023 IL_0009: ldloc.0 IL_000a: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_000f: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0014: unbox "C2.S1" IL_0019: ldfld "C2.S1.Field As Integer" IL_001e: call "Sub System.Console.WriteLine(Integer)" IL_0023: ldloc.0 IL_0024: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0029: brtrue.s IL_0009 IL_002b: leave.s IL_0041 } finally { IL_002d: ldloc.0 IL_002e: isinst "System.IDisposable" IL_0033: brfalse.s IL_0040 IL_0035: ldloc.0 IL_0036: isinst "System.IDisposable" IL_003b: callvirt "Sub System.IDisposable.Dispose()" IL_0040: endfinally } IL_0041: ret } ]]>) ' there should be a check for null before calling Dispose End Sub <WorkItem(542185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542185")> <Fact> Public Sub CustomDefinedType() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections.Generic Class C Public Shared Sub Main() Dim x = New B() End Sub End Class Class A Public Function GetEnumerator() As List(Of String).Enumerator Dim s = New List(Of String)() s.Add("A") s.Add("B") s.Add("C") Return s.GetEnumerator() End Function End Class Class B Inherits A Public Overloads Function GetEnumerator(ParamArray x As Integer()) As List(Of Integer).Enumerator Return New List(Of Integer).Enumerator() End Function End Class </file> </compilation>) End Sub <Fact> Public Sub ForEachQuery() CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Linq Module Program Sub Main(args As String()) Dim ii As Integer() = New Integer() {1, 2, 3} For Each iii In ii.Where(Function(jj) jj >= ii(0)).Select(Function(jj) jj) System.Console.Write(iii) Next End Sub End Module </file> </compilation>, references:={LinqAssemblyRef}, expectedOutput:="123") End Sub <WorkItem(544311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544311")> <Fact()> Public Sub ForEachWithMultipleDimArray() CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Module Program Sub Main() Dim k(,) = {{1}, {1}} For Each [Custom] In k Console.Write(VerifyStaticType([Custom], GetType(Integer))) Console.Write(VerifyStaticType([Custom], GetType(Object))) Exit For Next End Sub Function VerifyStaticType(Of T)(ByVal x As T, ByVal y As System.Type) As Boolean Return GetType(T) Is y End Function End Module </file> </compilation>, expectedOutput:="TrueFalse") End Sub <WorkItem(545519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545519")> <Fact()> Public Sub NewForEachScopeDev11() Dim source = <compilation> <file name="a.vb"> imports system imports system.collections.generic Module m1 Sub Main() Dim actions = New List(Of Action)() Dim values = New List(Of Integer) From {1, 2, 3} ' test lifting of control variable in loop body when collection is array For Each i As Integer In values actions.Add(Sub() Console.WriteLine(i)) Next For Each a In actions a() Next End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("m1.Main", <![CDATA[ { // Code size 154 (0x9a) .maxstack 3 .locals init (System.Collections.Generic.List(Of System.Action) V_0, //actions System.Collections.Generic.List(Of Integer) V_1, //values System.Collections.Generic.List(Of Integer).Enumerator V_2, m1._Closure$__0-0 V_3, //$VB$Closure_0 System.Collections.Generic.List(Of System.Action).Enumerator V_4) IL_0000: newobj "Sub System.Collections.Generic.List(Of System.Action)..ctor()" IL_0005: stloc.0 IL_0006: newobj "Sub System.Collections.Generic.List(Of Integer)..ctor()" IL_000b: dup IL_000c: ldc.i4.1 IL_000d: callvirt "Sub System.Collections.Generic.List(Of Integer).Add(Integer)" IL_0012: dup IL_0013: ldc.i4.2 IL_0014: callvirt "Sub System.Collections.Generic.List(Of Integer).Add(Integer)" IL_0019: dup IL_001a: ldc.i4.3 IL_001b: callvirt "Sub System.Collections.Generic.List(Of Integer).Add(Integer)" IL_0020: stloc.1 .try { IL_0021: ldloc.1 IL_0022: callvirt "Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator" IL_0027: stloc.2 IL_0028: br.s IL_0050 IL_002a: ldloc.3 IL_002b: newobj "Sub m1._Closure$__0-0..ctor(m1._Closure$__0-0)" IL_0030: stloc.3 IL_0031: ldloc.3 IL_0032: ldloca.s V_2 IL_0034: call "Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer" IL_0039: stfld "m1._Closure$__0-0.$VB$Local_i As Integer" IL_003e: ldloc.0 IL_003f: ldloc.3 IL_0040: ldftn "Sub m1._Closure$__0-0._Lambda$__0()" IL_0046: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_004b: callvirt "Sub System.Collections.Generic.List(Of System.Action).Add(System.Action)" IL_0050: ldloca.s V_2 IL_0052: call "Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean" IL_0057: brtrue.s IL_002a IL_0059: leave.s IL_0069 } finally { IL_005b: ldloca.s V_2 IL_005d: constrained. "System.Collections.Generic.List(Of Integer).Enumerator" IL_0063: callvirt "Sub System.IDisposable.Dispose()" IL_0068: endfinally } IL_0069: nop .try { IL_006a: ldloc.0 IL_006b: callvirt "Function System.Collections.Generic.List(Of System.Action).GetEnumerator() As System.Collections.Generic.List(Of System.Action).Enumerator" IL_0070: stloc.s V_4 IL_0072: br.s IL_0080 IL_0074: ldloca.s V_4 IL_0076: call "Function System.Collections.Generic.List(Of System.Action).Enumerator.get_Current() As System.Action" IL_007b: callvirt "Sub System.Action.Invoke()" IL_0080: ldloca.s V_4 IL_0082: call "Function System.Collections.Generic.List(Of System.Action).Enumerator.MoveNext() As Boolean" IL_0087: brtrue.s IL_0074 IL_0089: leave.s IL_0099 } finally { IL_008b: ldloca.s V_4 IL_008d: constrained. "System.Collections.Generic.List(Of System.Action).Enumerator" IL_0093: callvirt "Sub System.IDisposable.Dispose()" IL_0098: endfinally } IL_0099: ret } ]]>) End Sub <WorkItem(545519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545519")> <Fact()> Public Sub NewForEachScopeDev11_2() Dim source = <compilation> <file name="a.vb"> imports system imports system.collections.generic Module m1 Sub Main() ' Test Array Dim x(10) as action ' test lifting of control variable in loop body and lifting of control variable when used ' in the collection expression itself. For Each i As Integer In (function() {i + 1, i + 2, i + 3})() x(i) = Sub() console.writeline(i.toString) Next for i = 1 to 3 x(i).invoke() next End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("m1.Main", <![CDATA[ { // Code size 93 (0x5d) .maxstack 4 .locals init (System.Action() V_0, //x Integer() V_1, Integer V_2, m1._Closure$__0-1 V_3, //$VB$Closure_0 Integer V_4) //i IL_0000: ldc.i4.s 11 IL_0002: newarr "System.Action" IL_0007: stloc.0 IL_0008: newobj "Sub m1._Closure$__0-0..ctor()" IL_000d: callvirt "Function m1._Closure$__0-0._Lambda$__0() As Integer()" IL_0012: stloc.1 IL_0013: ldc.i4.0 IL_0014: stloc.2 IL_0015: br.s IL_003f IL_0017: ldloc.3 IL_0018: newobj "Sub m1._Closure$__0-1..ctor(m1._Closure$__0-1)" IL_001d: stloc.3 IL_001e: ldloc.3 IL_001f: ldloc.1 IL_0020: ldloc.2 IL_0021: ldelem.i4 IL_0022: stfld "m1._Closure$__0-1.$VB$Local_i As Integer" IL_0027: ldloc.0 IL_0028: ldloc.3 IL_0029: ldfld "m1._Closure$__0-1.$VB$Local_i As Integer" IL_002e: ldloc.3 IL_002f: ldftn "Sub m1._Closure$__0-1._Lambda$__1()" IL_0035: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_003a: stelem.ref IL_003b: ldloc.2 IL_003c: ldc.i4.1 IL_003d: add.ovf IL_003e: stloc.2 IL_003f: ldloc.2 IL_0040: ldloc.1 IL_0041: ldlen IL_0042: conv.i4 IL_0043: blt.s IL_0017 IL_0045: ldc.i4.1 IL_0046: stloc.s V_4 IL_0048: ldloc.0 IL_0049: ldloc.s V_4 IL_004b: ldelem.ref IL_004c: callvirt "Sub System.Action.Invoke()" IL_0051: ldloc.s V_4 IL_0053: ldc.i4.1 IL_0054: add.ovf IL_0055: stloc.s V_4 IL_0057: ldloc.s V_4 IL_0059: ldc.i4.3 IL_005a: ble.s IL_0048 IL_005c: ret } ]]>) End Sub <WorkItem(545519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545519")> <Fact()> Public Sub NewForEachScopeDev11_3() Dim source = <compilation> <file name="a.vb"> imports system imports system.collections.generic Module m1 Sub Main() ' Test Array Dim x(10) as action for j = 0 to 2 ' test lifting of control variable in loop body and lifting of control variable when used ' in the collection expression itself. for each i as integer in (function(a) goo())(i) x(i) = sub() console.write(i.toString &amp; " ") next for i = 1 to 3 x(i).invoke() next Console.Writeline() next j End Sub function goo() as IEnumerable(of Integer) return new list(of integer) from {1, 2, 3} end function End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[1 2 3 1 2 3 1 2 3 ]]>).VerifyIL("m1.Main", <![CDATA[ { // Code size 170 (0xaa) .maxstack 4 .locals init (System.Action() V_0, //x Integer V_1, //j Integer V_2, System.Collections.Generic.IEnumerator(Of Integer) V_3, m1._Closure$__0-0 V_4, //$VB$Closure_0 Integer V_5) //i IL_0000: ldc.i4.s 11 IL_0002: newarr "System.Action" IL_0007: stloc.0 IL_0008: ldc.i4.0 IL_0009: stloc.1 IL_000a: nop .try { IL_000b: ldsfld "m1._Closure$__.$I0-0 As <generated method>" IL_0010: brfalse.s IL_0019 IL_0012: ldsfld "m1._Closure$__.$I0-0 As <generated method>" IL_0017: br.s IL_002f IL_0019: ldsfld "m1._Closure$__.$I As m1._Closure$__" IL_001e: ldftn "Function m1._Closure$__._Lambda$__0-0(Object) As System.Collections.Generic.IEnumerable(Of Integer)" IL_0024: newobj "Sub VB$AnonymousDelegate_0(Of Object, System.Collections.Generic.IEnumerable(Of Integer))..ctor(Object, System.IntPtr)" IL_0029: dup IL_002a: stsfld "m1._Closure$__.$I0-0 As <generated method>" IL_002f: ldloc.2 IL_0030: box "Integer" IL_0035: callvirt "Function VB$AnonymousDelegate_0(Of Object, System.Collections.Generic.IEnumerable(Of Integer)).Invoke(Object) As System.Collections.Generic.IEnumerable(Of Integer)" IL_003a: callvirt "Function System.Collections.Generic.IEnumerable(Of Integer).GetEnumerator() As System.Collections.Generic.IEnumerator(Of Integer)" IL_003f: stloc.3 IL_0040: br.s IL_006e IL_0042: ldloc.s V_4 IL_0044: newobj "Sub m1._Closure$__0-0..ctor(m1._Closure$__0-0)" IL_0049: stloc.s V_4 IL_004b: ldloc.s V_4 IL_004d: ldloc.3 IL_004e: callvirt "Function System.Collections.Generic.IEnumerator(Of Integer).get_Current() As Integer" IL_0053: stfld "m1._Closure$__0-0.$VB$Local_i As Integer" IL_0058: ldloc.0 IL_0059: ldloc.s V_4 IL_005b: ldfld "m1._Closure$__0-0.$VB$Local_i As Integer" IL_0060: ldloc.s V_4 IL_0062: ldftn "Sub m1._Closure$__0-0._Lambda$__1()" IL_0068: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_006d: stelem.ref IL_006e: ldloc.3 IL_006f: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0074: brtrue.s IL_0042 IL_0076: leave.s IL_0082 } finally { IL_0078: ldloc.3 IL_0079: brfalse.s IL_0081 IL_007b: ldloc.3 IL_007c: callvirt "Sub System.IDisposable.Dispose()" IL_0081: endfinally } IL_0082: ldc.i4.1 IL_0083: stloc.s V_5 IL_0085: ldloc.0 IL_0086: ldloc.s V_5 IL_0088: ldelem.ref IL_0089: callvirt "Sub System.Action.Invoke()" IL_008e: ldloc.s V_5 IL_0090: ldc.i4.1 IL_0091: add.ovf IL_0092: stloc.s V_5 IL_0094: ldloc.s V_5 IL_0096: ldc.i4.3 IL_0097: ble.s IL_0085 IL_0099: call "Sub System.Console.WriteLine()" IL_009e: ldloc.1 IL_009f: ldc.i4.1 IL_00a0: add.ovf IL_00a1: stloc.1 IL_00a2: ldloc.1 IL_00a3: ldc.i4.2 IL_00a4: ble IL_000a IL_00a9: ret } ]]>) End Sub <WorkItem(545519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545519")> <Fact()> Public Sub NewForEachScopeDev11_4() Dim source = <compilation> <file name="a.vb"> imports system imports system.collections.generic Module m1 Sub Main() ' Test Array Dim lambdas As New List(Of Action) 'Expected 0,1,2, 0,1,2, 0,1,2 lambdas.clear For y = 1 To 3 ' test lifting of control variable in loop body and lifting of control variable when used ' in the collection expression itself. The for each itself is nested in a for loop. For Each x as integer In (function(a) x = x + 1 return {a, x, 2} end function)(x) lambdas.add( Sub() Console.Write(x.ToString + "," ) ) Next lambdas.add(sub() Console.WriteLine()) Next For Each lambda In lambdas lambda() Next End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ 0,1,2, 0,1,2, 0,1,2, ]]>).VerifyIL("m1.Main", <![CDATA[ { // Code size 195 (0xc3) .maxstack 3 .locals init (System.Collections.Generic.List(Of System.Action) V_0, //lambdas Integer V_1, //y Object() V_2, Integer V_3, m1._Closure$__0-1 V_4, //$VB$Closure_0 System.Collections.Generic.List(Of System.Action).Enumerator V_5) IL_0000: newobj "Sub System.Collections.Generic.List(Of System.Action)..ctor()" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: callvirt "Sub System.Collections.Generic.List(Of System.Action).Clear()" IL_000c: ldc.i4.1 IL_000d: stloc.1 IL_000e: newobj "Sub m1._Closure$__0-0..ctor()" IL_0013: dup IL_0014: ldfld "m1._Closure$__0-0.$VB$NonLocal_2 As Integer" IL_0019: box "Integer" IL_001e: callvirt "Function m1._Closure$__0-0._Lambda$__0(Object) As Object()" IL_0023: stloc.2 IL_0024: ldc.i4.0 IL_0025: stloc.3 IL_0026: br.s IL_0057 IL_0028: ldloc.s V_4 IL_002a: newobj "Sub m1._Closure$__0-1..ctor(m1._Closure$__0-1)" IL_002f: stloc.s V_4 IL_0031: ldloc.s V_4 IL_0033: ldloc.2 IL_0034: ldloc.3 IL_0035: ldelem.ref IL_0036: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_003b: stfld "m1._Closure$__0-1.$VB$Local_x As Integer" IL_0040: ldloc.0 IL_0041: ldloc.s V_4 IL_0043: ldftn "Sub m1._Closure$__0-1._Lambda$__1()" IL_0049: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_004e: callvirt "Sub System.Collections.Generic.List(Of System.Action).Add(System.Action)" IL_0053: ldloc.3 IL_0054: ldc.i4.1 IL_0055: add.ovf IL_0056: stloc.3 IL_0057: ldloc.3 IL_0058: ldloc.2 IL_0059: ldlen IL_005a: conv.i4 IL_005b: blt.s IL_0028 IL_005d: ldloc.0 IL_005e: ldsfld "m1._Closure$__.$I0-2 As System.Action" IL_0063: brfalse.s IL_006c IL_0065: ldsfld "m1._Closure$__.$I0-2 As System.Action" IL_006a: br.s IL_0082 IL_006c: ldsfld "m1._Closure$__.$I As m1._Closure$__" IL_0071: ldftn "Sub m1._Closure$__._Lambda$__0-2()" IL_0077: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_007c: dup IL_007d: stsfld "m1._Closure$__.$I0-2 As System.Action" IL_0082: callvirt "Sub System.Collections.Generic.List(Of System.Action).Add(System.Action)" IL_0087: ldloc.1 IL_0088: ldc.i4.1 IL_0089: add.ovf IL_008a: stloc.1 IL_008b: ldloc.1 IL_008c: ldc.i4.3 IL_008d: ble IL_000e IL_0092: nop .try { IL_0093: ldloc.0 IL_0094: callvirt "Function System.Collections.Generic.List(Of System.Action).GetEnumerator() As System.Collections.Generic.List(Of System.Action).Enumerator" IL_0099: stloc.s V_5 IL_009b: br.s IL_00a9 IL_009d: ldloca.s V_5 IL_009f: call "Function System.Collections.Generic.List(Of System.Action).Enumerator.get_Current() As System.Action" IL_00a4: callvirt "Sub System.Action.Invoke()" IL_00a9: ldloca.s V_5 IL_00ab: call "Function System.Collections.Generic.List(Of System.Action).Enumerator.MoveNext() As Boolean" IL_00b0: brtrue.s IL_009d IL_00b2: leave.s IL_00c2 } finally { IL_00b4: ldloca.s V_5 IL_00b6: constrained. "System.Collections.Generic.List(Of System.Action).Enumerator" IL_00bc: callvirt "Sub System.IDisposable.Dispose()" IL_00c1: endfinally } IL_00c2: ret } ]]>) End Sub <Fact> Public Sub ForEachLateBinding() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict Off imports system Class C Shared Sub Main() Dim o As Object = {1, 2, 3} For Each x In o console.writeline(x) Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithModuleName("MODULE"), expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 84 (0x54) .maxstack 3 .locals init (Object V_0, //o System.Collections.IEnumerator V_1) IL_0000: ldc.i4.3 IL_0001: newarr "Integer" IL_0006: dup IL_0007: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D" IL_000c: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)" IL_0011: stloc.0 .try { IL_0012: ldloc.0 IL_0013: castclass "System.Collections.IEnumerable" IL_0018: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_001d: stloc.1 IL_001e: br.s IL_0035 IL_0020: ldloc.1 IL_0021: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0026: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_002b: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0030: call "Sub System.Console.WriteLine(Object)" IL_0035: ldloc.1 IL_0036: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_003b: brtrue.s IL_0020 IL_003d: leave.s IL_0053 } finally { IL_003f: ldloc.1 IL_0040: isinst "System.IDisposable" IL_0045: brfalse.s IL_0052 IL_0047: ldloc.1 IL_0048: isinst "System.IDisposable" IL_004d: callvirt "Sub System.IDisposable.Dispose()" IL_0052: endfinally } IL_0053: ret } ]]>).Compilation End Sub End Class End Namespace
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Workspaces/Remote/ServiceHub/Services/ServiceBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Roslyn.Utilities; #pragma warning disable CS0618 // Type or member is obsolete - this should become error once we provide infra for migrating to ISB (https://github.com/dotnet/roslyn/issues/44326) namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Base type with servicehub helper methods. this is not tied to how Roslyn OOP works. /// /// any type that derived from this type is supposed to be an entry point for servicehub services. /// name of the type should match one appears in GenerateServiceHubConfigurationFiles.targets /// and signature of either its constructor or static CreateAsync must follow the convension /// ctor(Stream stream, IServiceProvider serviceProvider). /// /// see servicehub detail from VSIDE onenote /// https://microsoft.sharepoint.com/teams/DD_VSIDE /// </summary> internal abstract class ServiceBase : IDisposable { private static int s_instanceId; protected readonly RemoteEndPoint EndPoint; protected readonly int InstanceId; protected readonly TraceSource Logger; protected readonly RemoteWorkspaceManager WorkspaceManager; // test data are only available when running tests: internal readonly RemoteHostTestData? TestData; static ServiceBase() { WatsonReporter.InitializeFatalErrorHandlers(); } protected ServiceBase(IServiceProvider serviceProvider, Stream stream, IEnumerable<JsonConverter>? jsonConverters = null) { InstanceId = Interlocked.Add(ref s_instanceId, 1); TestData = (RemoteHostTestData?)serviceProvider.GetService(typeof(RemoteHostTestData)); WorkspaceManager = TestData?.WorkspaceManager ?? RemoteWorkspaceManager.Default; Logger = (TraceSource)serviceProvider.GetService(typeof(TraceSource)); Log(TraceEventType.Information, "Service instance created"); // invoke all calls incoming over the stream on this service instance: EndPoint = new RemoteEndPoint(stream, Logger, incomingCallTarget: this, jsonConverters); } public void Dispose() { if (EndPoint.IsDisposed) { // guard us from double disposing. this can happen in unit test // due to how we create test mock service hub stream that tied to // remote host service return; } EndPoint.Dispose(); Log(TraceEventType.Information, "Service instance disposed"); } protected void StartService() { EndPoint.StartListening(); } protected string DebugInstanceString => $"{GetType()} ({InstanceId})"; protected void Log(TraceEventType errorType, string message) => Logger.TraceEvent(errorType, 0, $"{DebugInstanceString}: {message}"); public RemoteWorkspace GetWorkspace() => WorkspaceManager.GetWorkspace(); protected Task<Solution> GetSolutionAsync(PinnedSolutionInfo solutionInfo, CancellationToken cancellationToken) { var workspace = GetWorkspace(); var assetProvider = workspace.CreateAssetProvider(solutionInfo, WorkspaceManager.SolutionAssetCache, WorkspaceManager.GetAssetSource()); return workspace.GetSolutionAsync(assetProvider, solutionInfo.SolutionChecksum, solutionInfo.FromPrimaryBranch, solutionInfo.WorkspaceVersion, solutionInfo.ProjectId, cancellationToken).AsTask(); } internal Task<Solution> GetSolutionImplAsync(JObject solutionInfo, CancellationToken cancellationToken) { var reader = solutionInfo.CreateReader(); var serializer = JsonSerializer.Create(new JsonSerializerSettings() { Converters = new[] { AggregateJsonConverter.Instance }, DateParseHandling = DateParseHandling.None }); var pinnedSolutionInfo = serializer.Deserialize<PinnedSolutionInfo>(reader); return GetSolutionAsync(pinnedSolutionInfo, cancellationToken); } protected async Task<T> RunServiceAsync<T>(Func<Task<T>> callAsync, CancellationToken cancellationToken) { WorkspaceManager.SolutionAssetCache.UpdateLastActivityTime(); try { return await callAsync().ConfigureAwait(false); } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } protected async Task RunServiceAsync(Func<Task> callAsync, CancellationToken cancellationToken) { WorkspaceManager.SolutionAssetCache.UpdateLastActivityTime(); try { await callAsync().ConfigureAwait(false); } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } protected T RunService<T>(Func<T> call, CancellationToken cancellationToken) { WorkspaceManager.SolutionAssetCache.UpdateLastActivityTime(); try { return call(); } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } protected void RunService(Action call, CancellationToken cancellationToken) { WorkspaceManager.SolutionAssetCache.UpdateLastActivityTime(); try { call(); } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Roslyn.Utilities; #pragma warning disable CS0618 // Type or member is obsolete - this should become error once we provide infra for migrating to ISB (https://github.com/dotnet/roslyn/issues/44326) namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Base type with servicehub helper methods. this is not tied to how Roslyn OOP works. /// /// any type that derived from this type is supposed to be an entry point for servicehub services. /// name of the type should match one appears in GenerateServiceHubConfigurationFiles.targets /// and signature of either its constructor or static CreateAsync must follow the convension /// ctor(Stream stream, IServiceProvider serviceProvider). /// /// see servicehub detail from VSIDE onenote /// https://microsoft.sharepoint.com/teams/DD_VSIDE /// </summary> internal abstract class ServiceBase : IDisposable { private static int s_instanceId; protected readonly RemoteEndPoint EndPoint; protected readonly int InstanceId; protected readonly TraceSource Logger; protected readonly RemoteWorkspaceManager WorkspaceManager; // test data are only available when running tests: internal readonly RemoteHostTestData? TestData; static ServiceBase() { WatsonReporter.InitializeFatalErrorHandlers(); } protected ServiceBase(IServiceProvider serviceProvider, Stream stream, IEnumerable<JsonConverter>? jsonConverters = null) { InstanceId = Interlocked.Add(ref s_instanceId, 1); TestData = (RemoteHostTestData?)serviceProvider.GetService(typeof(RemoteHostTestData)); WorkspaceManager = TestData?.WorkspaceManager ?? RemoteWorkspaceManager.Default; Logger = (TraceSource)serviceProvider.GetService(typeof(TraceSource)); Log(TraceEventType.Information, "Service instance created"); // invoke all calls incoming over the stream on this service instance: EndPoint = new RemoteEndPoint(stream, Logger, incomingCallTarget: this, jsonConverters); } public void Dispose() { if (EndPoint.IsDisposed) { // guard us from double disposing. this can happen in unit test // due to how we create test mock service hub stream that tied to // remote host service return; } EndPoint.Dispose(); Log(TraceEventType.Information, "Service instance disposed"); } protected void StartService() { EndPoint.StartListening(); } protected string DebugInstanceString => $"{GetType()} ({InstanceId})"; protected void Log(TraceEventType errorType, string message) => Logger.TraceEvent(errorType, 0, $"{DebugInstanceString}: {message}"); public RemoteWorkspace GetWorkspace() => WorkspaceManager.GetWorkspace(); protected Task<Solution> GetSolutionAsync(PinnedSolutionInfo solutionInfo, CancellationToken cancellationToken) { var workspace = GetWorkspace(); var assetProvider = workspace.CreateAssetProvider(solutionInfo, WorkspaceManager.SolutionAssetCache, WorkspaceManager.GetAssetSource()); return workspace.GetSolutionAsync(assetProvider, solutionInfo.SolutionChecksum, solutionInfo.FromPrimaryBranch, solutionInfo.WorkspaceVersion, solutionInfo.ProjectId, cancellationToken).AsTask(); } internal Task<Solution> GetSolutionImplAsync(JObject solutionInfo, CancellationToken cancellationToken) { var reader = solutionInfo.CreateReader(); var serializer = JsonSerializer.Create(new JsonSerializerSettings() { Converters = new[] { AggregateJsonConverter.Instance }, DateParseHandling = DateParseHandling.None }); var pinnedSolutionInfo = serializer.Deserialize<PinnedSolutionInfo>(reader); return GetSolutionAsync(pinnedSolutionInfo, cancellationToken); } protected async Task<T> RunServiceAsync<T>(Func<Task<T>> callAsync, CancellationToken cancellationToken) { WorkspaceManager.SolutionAssetCache.UpdateLastActivityTime(); try { return await callAsync().ConfigureAwait(false); } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } protected async Task RunServiceAsync(Func<Task> callAsync, CancellationToken cancellationToken) { WorkspaceManager.SolutionAssetCache.UpdateLastActivityTime(); try { await callAsync().ConfigureAwait(false); } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } protected T RunService<T>(Func<T> call, CancellationToken cancellationToken) { WorkspaceManager.SolutionAssetCache.UpdateLastActivityTime(); try { return call(); } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } protected void RunService(Action call, CancellationToken cancellationToken) { WorkspaceManager.SolutionAssetCache.UpdateLastActivityTime(); try { call(); } catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/Test/Utilities/CSharp/DiagnosticExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal static class DiagnosticExtensions { public static void Verify(this IEnumerable<DiagnosticInfo> actual, params DiagnosticDescription[] expected) { actual.Select(info => new CSDiagnostic(info, NoLocation.Singleton)).Verify(expected); } public static void Verify(this ImmutableArray<DiagnosticInfo> actual, params DiagnosticDescription[] expected) { actual.Select(info => new CSDiagnostic(info, NoLocation.Singleton)).Verify(expected); } public static string ToLocalizedString(this MessageID id) { return new LocalizableErrorArgument(id).ToString(null, null); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal static class DiagnosticExtensions { public static void Verify(this IEnumerable<DiagnosticInfo> actual, params DiagnosticDescription[] expected) { actual.Select(info => new CSDiagnostic(info, NoLocation.Singleton)).Verify(expected); } public static void Verify(this ImmutableArray<DiagnosticInfo> actual, params DiagnosticDescription[] expected) { actual.Select(info => new CSDiagnostic(info, NoLocation.Singleton)).Verify(expected); } public static string ToLocalizedString(this MessageID id) { return new LocalizableErrorArgument(id).ToString(null, null); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Workspaces/Core/Portable/CodeFixes/CodeFixContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeFixes { /// <summary> /// Context for code fixes provided by a <see cref="CodeFixProvider"/>. /// </summary> public struct CodeFixContext : ITypeScriptCodeFixContext { private readonly Document _document; private readonly Project _project; private readonly TextSpan _span; private readonly ImmutableArray<Diagnostic> _diagnostics; private readonly CancellationToken _cancellationToken; private readonly Action<CodeAction, ImmutableArray<Diagnostic>> _registerCodeFix; /// <summary> /// Document corresponding to the <see cref="CodeFixContext.Span"/> to fix. /// </summary> public Document Document => _document; /// <summary> /// Project corresponding to the diagnostics to fix. /// </summary> internal Project Project => _project; /// <summary> /// Text span within the <see cref="CodeFixContext.Document"/> to fix. /// </summary> public TextSpan Span => _span; /// <summary> /// Diagnostics to fix. /// NOTE: All the diagnostics in this collection have the same <see cref="CodeFixContext.Span"/>. /// </summary> public ImmutableArray<Diagnostic> Diagnostics => _diagnostics; /// <summary> /// CancellationToken. /// </summary> public CancellationToken CancellationToken => _cancellationToken; private readonly bool _isBlocking; bool ITypeScriptCodeFixContext.IsBlocking => _isBlocking; /// <summary> /// Creates a code fix context to be passed into <see cref="CodeFixProvider.RegisterCodeFixesAsync(CodeFixContext)"/> method. /// </summary> /// <param name="document">Document to fix.</param> /// <param name="span">Text span within the <paramref name="document"/> to fix.</param> /// <param name="diagnostics"> /// Diagnostics to fix. /// All the diagnostics must have the same <paramref name="span"/>. /// Additionally, the <see cref="Diagnostic.Id"/> of each diagnostic must be in the set of the <see cref="CodeFixProvider.FixableDiagnosticIds"/> of the associated <see cref="CodeFixProvider"/>. /// </param> /// <param name="registerCodeFix">Delegate to register a <see cref="CodeAction"/> fixing a subset of diagnostics.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <exception cref="ArgumentNullException">Throws this exception if any of the arguments is null.</exception> /// <exception cref="ArgumentException"> /// Throws this exception if the given <paramref name="diagnostics"/> is empty, /// has a null element or has an element whose span is not equal to <paramref name="span"/>. /// </exception> public CodeFixContext( Document document, TextSpan span, ImmutableArray<Diagnostic> diagnostics, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, CancellationToken cancellationToken) : this(document, span, diagnostics, registerCodeFix, verifyArguments: true, cancellationToken: cancellationToken) { } /// <summary> /// Creates a code fix context to be passed into <see cref="CodeFixProvider.RegisterCodeFixesAsync(CodeFixContext)"/> method. /// </summary> /// <param name="document">Document to fix.</param> /// <param name="diagnostic"> /// Diagnostic to fix. /// The <see cref="Diagnostic.Id"/> of this diagnostic must be in the set of the <see cref="CodeFixProvider.FixableDiagnosticIds"/> of the associated <see cref="CodeFixProvider"/>. /// </param> /// <param name="registerCodeFix">Delegate to register a <see cref="CodeAction"/> fixing a subset of diagnostics.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <exception cref="ArgumentNullException">Throws this exception if any of the arguments is null.</exception> public CodeFixContext( Document document, Diagnostic diagnostic, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, CancellationToken cancellationToken) : this(document, diagnostic.Location.SourceSpan, ImmutableArray.Create(diagnostic), registerCodeFix, verifyArguments: true, cancellationToken: cancellationToken) { } internal CodeFixContext( Document document, TextSpan span, ImmutableArray<Diagnostic> diagnostics, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, bool verifyArguments, CancellationToken cancellationToken) : this(document, document.Project, span, diagnostics, registerCodeFix, verifyArguments, isBlocking: false, cancellationToken) { } internal CodeFixContext( Document document, TextSpan span, ImmutableArray<Diagnostic> diagnostics, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, bool verifyArguments, bool isBlocking, CancellationToken cancellationToken) : this(document, document.Project, span, diagnostics, registerCodeFix, verifyArguments, isBlocking, cancellationToken) { } private CodeFixContext( Document document, Project project, TextSpan span, ImmutableArray<Diagnostic> diagnostics, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, bool verifyArguments, bool isBlocking, CancellationToken cancellationToken) { if (verifyArguments) { if (document == null) { throw new ArgumentNullException(nameof(document)); } if (registerCodeFix == null) { throw new ArgumentNullException(nameof(registerCodeFix)); } VerifyDiagnosticsArgument(diagnostics, span); } _document = document; _project = project; _span = span; _diagnostics = diagnostics; _registerCodeFix = registerCodeFix; _cancellationToken = cancellationToken; _isBlocking = isBlocking; } internal CodeFixContext( Document document, Diagnostic diagnostic, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, bool verifyArguments, CancellationToken cancellationToken) : this(document, diagnostic.Location.SourceSpan, ImmutableArray.Create(diagnostic), registerCodeFix, verifyArguments, cancellationToken) { } /// <summary> /// Add supplied <paramref name="action"/> to the list of fixes that will be offered to the user. /// </summary> /// <param name="action">The <see cref="CodeAction"/> that will be invoked to apply the fix.</param> /// <param name="diagnostic">The subset of <see cref="Diagnostics"/> being addressed / fixed by the <paramref name="action"/>.</param> public void RegisterCodeFix(CodeAction action, Diagnostic diagnostic) { if (action == null) { throw new ArgumentNullException(nameof(action)); } if (diagnostic == null) { throw new ArgumentNullException(nameof(diagnostic)); } _registerCodeFix(action, ImmutableArray.Create(diagnostic)); } /// <summary> /// Add supplied <paramref name="action"/> to the list of fixes that will be offered to the user. /// </summary> /// <param name="action">The <see cref="CodeAction"/> that will be invoked to apply the fix.</param> /// <param name="diagnostics">The subset of <see cref="Diagnostics"/> being addressed / fixed by the <paramref name="action"/>.</param> public void RegisterCodeFix(CodeAction action, IEnumerable<Diagnostic> diagnostics) { if (diagnostics == null) { throw new ArgumentNullException(nameof(diagnostics)); } RegisterCodeFix(action, diagnostics.ToImmutableArray()); } /// <summary> /// Add supplied <paramref name="action"/> to the list of fixes that will be offered to the user. /// </summary> /// <param name="action">The <see cref="CodeAction"/> that will be invoked to apply the fix.</param> /// <param name="diagnostics">The subset of <see cref="Diagnostics"/> being addressed / fixed by the <paramref name="action"/>.</param> public void RegisterCodeFix(CodeAction action, ImmutableArray<Diagnostic> diagnostics) { if (action == null) { throw new ArgumentNullException(nameof(action)); } VerifyDiagnosticsArgument(diagnostics, _span); // TODO: // - Check that all diagnostics are unique (no duplicates). // - Check that supplied diagnostics form subset of diagnostics originally // passed to the provider via CodeFixContext.Diagnostics. _registerCodeFix(action, diagnostics); } private static void VerifyDiagnosticsArgument(ImmutableArray<Diagnostic> diagnostics, TextSpan span) { if (diagnostics.IsDefault) { throw new ArgumentException(nameof(diagnostics)); } if (diagnostics.Length == 0) { throw new ArgumentException(WorkspacesResources.At_least_one_diagnostic_must_be_supplied, nameof(diagnostics)); } if (diagnostics.Any(d => d == null)) { throw new ArgumentException(WorkspaceExtensionsResources.Supplied_diagnostic_cannot_be_null, nameof(diagnostics)); } if (diagnostics.Any(d => d.Location.SourceSpan != span)) { throw new ArgumentException(string.Format(WorkspacesResources.Diagnostic_must_have_span_0, span.ToString()), nameof(diagnostics)); } } } internal interface ITypeScriptCodeFixContext { bool IsBlocking { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeFixes { /// <summary> /// Context for code fixes provided by a <see cref="CodeFixProvider"/>. /// </summary> public struct CodeFixContext : ITypeScriptCodeFixContext { private readonly Document _document; private readonly Project _project; private readonly TextSpan _span; private readonly ImmutableArray<Diagnostic> _diagnostics; private readonly CancellationToken _cancellationToken; private readonly Action<CodeAction, ImmutableArray<Diagnostic>> _registerCodeFix; /// <summary> /// Document corresponding to the <see cref="CodeFixContext.Span"/> to fix. /// </summary> public Document Document => _document; /// <summary> /// Project corresponding to the diagnostics to fix. /// </summary> internal Project Project => _project; /// <summary> /// Text span within the <see cref="CodeFixContext.Document"/> to fix. /// </summary> public TextSpan Span => _span; /// <summary> /// Diagnostics to fix. /// NOTE: All the diagnostics in this collection have the same <see cref="CodeFixContext.Span"/>. /// </summary> public ImmutableArray<Diagnostic> Diagnostics => _diagnostics; /// <summary> /// CancellationToken. /// </summary> public CancellationToken CancellationToken => _cancellationToken; private readonly bool _isBlocking; bool ITypeScriptCodeFixContext.IsBlocking => _isBlocking; /// <summary> /// Creates a code fix context to be passed into <see cref="CodeFixProvider.RegisterCodeFixesAsync(CodeFixContext)"/> method. /// </summary> /// <param name="document">Document to fix.</param> /// <param name="span">Text span within the <paramref name="document"/> to fix.</param> /// <param name="diagnostics"> /// Diagnostics to fix. /// All the diagnostics must have the same <paramref name="span"/>. /// Additionally, the <see cref="Diagnostic.Id"/> of each diagnostic must be in the set of the <see cref="CodeFixProvider.FixableDiagnosticIds"/> of the associated <see cref="CodeFixProvider"/>. /// </param> /// <param name="registerCodeFix">Delegate to register a <see cref="CodeAction"/> fixing a subset of diagnostics.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <exception cref="ArgumentNullException">Throws this exception if any of the arguments is null.</exception> /// <exception cref="ArgumentException"> /// Throws this exception if the given <paramref name="diagnostics"/> is empty, /// has a null element or has an element whose span is not equal to <paramref name="span"/>. /// </exception> public CodeFixContext( Document document, TextSpan span, ImmutableArray<Diagnostic> diagnostics, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, CancellationToken cancellationToken) : this(document, span, diagnostics, registerCodeFix, verifyArguments: true, cancellationToken: cancellationToken) { } /// <summary> /// Creates a code fix context to be passed into <see cref="CodeFixProvider.RegisterCodeFixesAsync(CodeFixContext)"/> method. /// </summary> /// <param name="document">Document to fix.</param> /// <param name="diagnostic"> /// Diagnostic to fix. /// The <see cref="Diagnostic.Id"/> of this diagnostic must be in the set of the <see cref="CodeFixProvider.FixableDiagnosticIds"/> of the associated <see cref="CodeFixProvider"/>. /// </param> /// <param name="registerCodeFix">Delegate to register a <see cref="CodeAction"/> fixing a subset of diagnostics.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <exception cref="ArgumentNullException">Throws this exception if any of the arguments is null.</exception> public CodeFixContext( Document document, Diagnostic diagnostic, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, CancellationToken cancellationToken) : this(document, diagnostic.Location.SourceSpan, ImmutableArray.Create(diagnostic), registerCodeFix, verifyArguments: true, cancellationToken: cancellationToken) { } internal CodeFixContext( Document document, TextSpan span, ImmutableArray<Diagnostic> diagnostics, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, bool verifyArguments, CancellationToken cancellationToken) : this(document, document.Project, span, diagnostics, registerCodeFix, verifyArguments, isBlocking: false, cancellationToken) { } internal CodeFixContext( Document document, TextSpan span, ImmutableArray<Diagnostic> diagnostics, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, bool verifyArguments, bool isBlocking, CancellationToken cancellationToken) : this(document, document.Project, span, diagnostics, registerCodeFix, verifyArguments, isBlocking, cancellationToken) { } private CodeFixContext( Document document, Project project, TextSpan span, ImmutableArray<Diagnostic> diagnostics, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, bool verifyArguments, bool isBlocking, CancellationToken cancellationToken) { if (verifyArguments) { if (document == null) { throw new ArgumentNullException(nameof(document)); } if (registerCodeFix == null) { throw new ArgumentNullException(nameof(registerCodeFix)); } VerifyDiagnosticsArgument(diagnostics, span); } _document = document; _project = project; _span = span; _diagnostics = diagnostics; _registerCodeFix = registerCodeFix; _cancellationToken = cancellationToken; _isBlocking = isBlocking; } internal CodeFixContext( Document document, Diagnostic diagnostic, Action<CodeAction, ImmutableArray<Diagnostic>> registerCodeFix, bool verifyArguments, CancellationToken cancellationToken) : this(document, diagnostic.Location.SourceSpan, ImmutableArray.Create(diagnostic), registerCodeFix, verifyArguments, cancellationToken) { } /// <summary> /// Add supplied <paramref name="action"/> to the list of fixes that will be offered to the user. /// </summary> /// <param name="action">The <see cref="CodeAction"/> that will be invoked to apply the fix.</param> /// <param name="diagnostic">The subset of <see cref="Diagnostics"/> being addressed / fixed by the <paramref name="action"/>.</param> public void RegisterCodeFix(CodeAction action, Diagnostic diagnostic) { if (action == null) { throw new ArgumentNullException(nameof(action)); } if (diagnostic == null) { throw new ArgumentNullException(nameof(diagnostic)); } _registerCodeFix(action, ImmutableArray.Create(diagnostic)); } /// <summary> /// Add supplied <paramref name="action"/> to the list of fixes that will be offered to the user. /// </summary> /// <param name="action">The <see cref="CodeAction"/> that will be invoked to apply the fix.</param> /// <param name="diagnostics">The subset of <see cref="Diagnostics"/> being addressed / fixed by the <paramref name="action"/>.</param> public void RegisterCodeFix(CodeAction action, IEnumerable<Diagnostic> diagnostics) { if (diagnostics == null) { throw new ArgumentNullException(nameof(diagnostics)); } RegisterCodeFix(action, diagnostics.ToImmutableArray()); } /// <summary> /// Add supplied <paramref name="action"/> to the list of fixes that will be offered to the user. /// </summary> /// <param name="action">The <see cref="CodeAction"/> that will be invoked to apply the fix.</param> /// <param name="diagnostics">The subset of <see cref="Diagnostics"/> being addressed / fixed by the <paramref name="action"/>.</param> public void RegisterCodeFix(CodeAction action, ImmutableArray<Diagnostic> diagnostics) { if (action == null) { throw new ArgumentNullException(nameof(action)); } VerifyDiagnosticsArgument(diagnostics, _span); // TODO: // - Check that all diagnostics are unique (no duplicates). // - Check that supplied diagnostics form subset of diagnostics originally // passed to the provider via CodeFixContext.Diagnostics. _registerCodeFix(action, diagnostics); } private static void VerifyDiagnosticsArgument(ImmutableArray<Diagnostic> diagnostics, TextSpan span) { if (diagnostics.IsDefault) { throw new ArgumentException(nameof(diagnostics)); } if (diagnostics.Length == 0) { throw new ArgumentException(WorkspacesResources.At_least_one_diagnostic_must_be_supplied, nameof(diagnostics)); } if (diagnostics.Any(d => d == null)) { throw new ArgumentException(WorkspaceExtensionsResources.Supplied_diagnostic_cannot_be_null, nameof(diagnostics)); } if (diagnostics.Any(d => d.Location.SourceSpan != span)) { throw new ArgumentException(string.Format(WorkspacesResources.Diagnostic_must_have_span_0, span.ToString()), nameof(diagnostics)); } } } internal interface ITypeScriptCodeFixContext { bool IsBlocking { get; } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Tools/ExternalAccess/OmniSharp/Navigation/OmniSharpNavigableItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Navigation { internal readonly struct OmniSharpNavigableItem { public OmniSharpNavigableItem(ImmutableArray<TaggedText> displayTaggedParts, Document document, TextSpan sourceSpan) { DisplayTaggedParts = displayTaggedParts; Document = document; SourceSpan = sourceSpan; } public ImmutableArray<TaggedText> DisplayTaggedParts { get; } public Document Document { get; } public TextSpan SourceSpan { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Navigation { internal readonly struct OmniSharpNavigableItem { public OmniSharpNavigableItem(ImmutableArray<TaggedText> displayTaggedParts, Document document, TextSpan sourceSpan) { DisplayTaggedParts = displayTaggedParts; Document = document; SourceSpan = sourceSpan; } public ImmutableArray<TaggedText> DisplayTaggedParts { get; } public Document Document { get; } public TextSpan SourceSpan { get; } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/VisualBasic/Test/Semantic/Diagnostics/OperationAnalyzerTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics <CompilerTrait(CompilerFeature.IOperation)> Public Class OperationAnalyzerTests Inherits BasicTestBase <Fact> Public Sub EmptyArrayVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Sub M1() Dim arr1 As Integer() = New Integer(-1) { } ' yes Dim arr2 As Byte() = { } ' yes Dim arr3 As C() = New C(-1) { } ' yes Dim arr4 As String() = New String() { Nothing } ' no Dim arr5 As Double() = New Double(1) { } ' no Dim arr6 As Integer() = { -1 } ' no Dim arr7 as Integer()() = New Integer(-1)() { } ' yes Dim arr8 as Integer()()()() = New Integer( -1)()()() { } ' yes Dim arr9 as Integer(,) = New Integer(-1,-1) { } ' no Dim arr10 as Integer()(,) = New Integer(-1)(,) { } ' yes Dim arr11 as Integer()(,) = New Integer(1)(,) { } ' no Dim arr12 as Integer(,)() = New Integer(-1,-1)() { } ' no Dim arr13 as Integer() = New Integer(0) { } ' no End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New EmptyArrayAnalyzer}, Nothing, Nothing, Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New Integer(-1) { }").WithLocation(3, 33), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "{ }").WithLocation(4, 30), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New C(-1) { }").WithLocation(5, 27), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New Integer(-1)() { }").WithLocation(9, 35), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New Integer( -1)()()() { }").WithLocation(10, 39), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New Integer(-1)(,) { }").WithLocation(12, 37)) End Sub <Fact> Public Sub BoxingVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Function M1(p1 As Object, p2 As Object, p3 As Object) As Object Dim v1 As New S Dim v2 As S = v1 Dim v3 As S = v1.M1(v2) Dim v4 As Object = M1(3, Me, v1) Dim v5 As Object = v3 If p1 Is Nothing return 3 End If If p2 Is Nothing return v3 End If If p3 Is Nothing Return v4 End If Return v5 End Function End Class Structure S Public X As Integer Public Y As Integer Public Z As Object Public Function M1(p1 As S) As S p1.GetType() Z = Me Return p1 End Function End Structure ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New BoxingOperationAnalyzer}, Nothing, Nothing, Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "3").WithLocation(6, 32), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "v1").WithLocation(6, 39), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "v3").WithLocation(7, 29), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "3").WithLocation(9, 21), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "v3").WithLocation(12, 21), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "p1").WithLocation(27, 9), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "Me").WithLocation(28, 13)) End Sub <Fact> Public Sub BadStuffVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M1(z as Integer) Framitz() Dim x As Integer = Bexley() Dim y As Integer = 10 Dim d As Double() = Nothing M1(d) Goto End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyAnalyzerDiagnostics({New BadStuffTestAnalyzer}, Nothing, Nothing, Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Framitz()").WithLocation(3, 9), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Framitz()").WithLocation(3, 9), Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Framitz").WithLocation(3, 9), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Framitz").WithLocation(3, 9), Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Bexley()").WithLocation(4, 28), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Bexley()").WithLocation(4, 28), Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Bexley").WithLocation(4, 28), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Bexley").WithLocation(4, 28), Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "M1(d)").WithLocation(7, 9), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "M1(d)").WithLocation(7, 9), Diagnostic(BadStuffTestAnalyzer.InvalidStatementDescriptor.Id, "Goto").WithLocation(8, 9), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Goto").WithLocation(8, 9), Diagnostic(BadStuffTestAnalyzer.InvalidStatementDescriptor.Id, "").WithLocation(8, 13), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "").WithLocation(8, 13)) End Sub <Fact> Public Sub SwitchVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M1(x As Integer) Select Case x Case 1, 2 Exit Select Case = 10 Exit Select Case Else Exit Select End Select Select Case x Case 1 Exit Select Case = 1000 Exit Select Case Else Exit Select End Select Select Case x Case 10 To 500 Exit Select Case = 1000 Exit Select Case Else Exit Select End Select Select Case x Case 1, 980 To 985 Exit Select Case Else Exit Select End Select Select Case x Case 1 to 3, 980 To 985 Exit Select End Select Select Case x Case 1 Exit Select Case > 100000 Exit Select End Select Select Case x Case Else Exit Select End Select Select Case x End Select Select Case x Case 1 Exit Select Case Exit Select End Select Select Case x Case 1 Exit Select Case = Exit Select End Select Select Case x Case 1 Exit Select Case 2 to Exit Select End Select End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(60, 17), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(68, 1), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(74, 22)) comp.VerifyAnalyzerDiagnostics({New SwitchTestAnalyzer}, Nothing, Nothing, Diagnostic(SwitchTestAnalyzer.SparseSwitchDescriptor.Id, "x").WithLocation(12, 21), Diagnostic(SwitchTestAnalyzer.SparseSwitchDescriptor.Id, "x").WithLocation(30, 21), Diagnostic(SwitchTestAnalyzer.SparseSwitchDescriptor.Id, "x").WithLocation(37, 21), Diagnostic(SwitchTestAnalyzer.NoDefaultSwitchDescriptor.Id, "x").WithLocation(37, 21), Diagnostic(SwitchTestAnalyzer.NoDefaultSwitchDescriptor.Id, "x").WithLocation(42, 21), Diagnostic(SwitchTestAnalyzer.OnlyDefaultSwitchDescriptor.Id, "x").WithLocation(49, 21), Diagnostic(SwitchTestAnalyzer.SparseSwitchDescriptor.Id, "x").WithLocation(54, 21), Diagnostic(SwitchTestAnalyzer.NoDefaultSwitchDescriptor.Id, "x").WithLocation(54, 21)) End Sub <Fact> Public Sub InvocationVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(a As Integer, ParamArray b As Integer()) End Sub Public Sub M1(a As Integer, b As Integer, c As Integer, x As Integer, y As Integer, z As Integer) End Sub Public Sub M2() M1(1, 2, 3, 4, 5, 6) M1(a:=1, b:=2, c:=3, x:=4, y:=5, z:=6) M1(a:=1, c:=2, b:=3, x:=4, y:=5, z:=6) M1(z:=1, x:=2, y:=3, c:=4, a:=5, b:=6) M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13) M0(1) M0(1, 2, 4, 3) End Sub Public Sub M3(Optional a As Integer = Nothing, Optional b As Integer = 0) End Sub Public Sub M4() M3(Nothing, 0) M3(Nothing,) M3(,0) M3(,) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New InvocationTestAnalyzer}, Nothing, Nothing, Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3(Nothing,)").WithArguments("b").WithLocation(25, 9), Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3(,0)").WithArguments("a").WithLocation(26, 9), Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3(,)").WithArguments("a").WithLocation(27, 9), Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3(,)").WithArguments("b").WithLocation(27, 9), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "2").WithLocation(11, 21), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "4").WithLocation(12, 33), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "2").WithLocation(12, 21), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "1").WithLocation(12, 15), Diagnostic(InvocationTestAnalyzer.BigParamArrayArgumentsDescriptor.Id, "M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)").WithLocation(14, 9), Diagnostic(InvocationTestAnalyzer.BigParamArrayArgumentsDescriptor.Id, "M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)").WithLocation(15, 9), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "3").WithLocation(17, 21)) End Sub <Fact> Public Sub FieldCouldBeReadOnlyVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public F1 As Integer Public Const F2 As Integer = 2 Public ReadOnly F3 As Integer Public F4 As Integer Public F5 As Integer Public F6 As Integer = 6 Public F7 As Integer Public F9 As S Public F10 As New C1 Public Sub New() F1 = 1 F4 = 4 F5 = 5 End Sub Public Sub M0() Dim x As Integer = F1 x = F2 x = F3 x = F4 x = F5 x = F6 x = F7 F4 = 4 F7 = 7 M1(F1, F5) F9.A = 10 F9.B = 20 F10.A = F9.A F10.B = F9.B End Sub Public Sub M1(ByRef X As Integer, Y As Integer) x = 10 End Sub Structure S Public A As Integer Public B As Integer End Structure Class C1 Public A As Integer Public B As Integer End Class End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New FieldCouldBeReadOnlyAnalyzer}, Nothing, Nothing, Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F5").WithLocation(6, 12), Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F6").WithLocation(7, 12), Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F10").WithLocation(10, 12)) End Sub <Fact> Public Sub StaticFieldCouldBeReadOnlyVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Shared F1 As Integer Public Shared ReadOnly F2 As Integer = 2 Public Shared Readonly F3 As Integer Public Shared F4 As Integer Public Shared F5 As Integer Public Shared F6 As Integer = 6 Public Shared F7 As Integer Public Shared F9 As S Public Shared F10 As New C1 Shared Sub New() F1 = 1 F4 = 4 F5 = 5 End Sub Public Shared Sub M0() Dim x As Integer = F1 x = F2 x = F3 x = F4 x = F5 x = F6 x = F7 F4 = 4 F7 = 7 M1(F1, F5) F9.A = 10 F9.B = 20 F10.A = F9.A F10.B = F9.B End Sub Public Shared Sub M1(ByRef X As Integer, Y As Integer) x = 10 End Sub Structure S Public A As Integer Public B As Integer End Structure Class C1 Public A As Integer Public B As Integer End Class End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New FieldCouldBeReadOnlyAnalyzer}, Nothing, Nothing, Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F5").WithLocation(6, 19), Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F6").WithLocation(7, 19), Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F10").WithLocation(10, 19)) End Sub <Fact> Public Sub LocalCouldBeConstVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(p as Integer) Dim x As Integer = p Dim y As Integer = x Const z As Integer = 1 Dim a As Integer = 2 Dim b As Integer = 3 Dim c As Integer = 4 Dim d As Integer = 5 Dim e As Integer = 6 Dim s As String = "ZZZ" b = 3 c -= 12 d += e + b M1(y, z, a, s) Dim n As S n.A = 10 n.B = 20 Dim o As New C1 o.A = 10 o.B = 20 End Sub Public Sub M1(ByRef x As Integer, y As Integer, ByRef z as Integer, s as String) x = 10 End Sub End Class Structure S Public A As Integer Public B As Integer End Structure Class C1 Public A As Integer Public B As Integer End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New LocalCouldBeConstAnalyzer}, Nothing, Nothing, Diagnostic(LocalCouldBeConstAnalyzer.LocalCouldBeConstDescriptor.Id, "e").WithLocation(10, 13), Diagnostic(LocalCouldBeConstAnalyzer.LocalCouldBeConstDescriptor.Id, "s").WithLocation(11, 13)) End Sub <Fact> Public Sub SymbolCouldHaveMoreSpecificTypeVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0() Dim a As Object = New Middle() Dim b As Object = New Value(10) Dim c As Object = New Middle() c = New Base() Dim d As Base = New Derived() Dim e As Base = New Derived() e = New Middle() Dim f As Base = New Middle() f = New Base() Dim g As Object = New Derived() g = New Base() g = New Middle() Dim h As New Middle() h = New Derived() Dim i As Object = 3 Dim j As Object j = 10 j = 10.1 Dim k As Middle = New Derived() Dim l As Middle = New Derived() Dim o As Object = New Middle() MM(l, o) Dim ibase1 As IBase1 = Nothing Dim ibase2 As IBase2 = Nothing Dim imiddle As IMiddle = Nothing Dim iderived As IDerived = Nothing Dim ia As Object = imiddle Dim ic As Object = imiddle ic = ibase1 Dim id As IBase1 = iderived Dim ie As IBase1 = iderived ie = imiddle Dim iff As IBase1 = imiddle iff = ibase1 Dim ig As Object = iderived ig = ibase1 ig = imiddle Dim ih = imiddle ih = iderived Dim ik As IMiddle = iderived Dim il As IMiddle = iderived Dim io As Object = imiddle IMM(il, io) Dim im As IBase2 = iderived Dim isink As Object = ibase2 isink = 3 End Sub Private fa As Object = New Middle() Private fb As Object = New Value(10) Private fc As Object = New Middle() Private fd As Base = New Derived() Private fe As Base = New Derived() Private ff As Base = New Middle() Private fg As Object = New Derived() Private fh As New Middle() Private fi As Object = 3 Private fj As Object Private fk As Middle = New Derived() Private fl As Middle = New Derived() Private fo As Object = New Middle() Private Shared fibase1 As IBase1 = Nothing Private Shared fibase2 As IBase2 = Nothing Private Shared fimiddle As IMiddle= Nothing Private Shared fiderived As IDerived = Nothing Private fia As Object = fimiddle Private fic As Object = fimiddle Private fid As IBase1 = fiderived Private fie As IBase1 = fiderived Private fiff As IBase1 = fimiddle Private fig As Object = fiderived Private fih As IMiddle = fimiddle Private fik As IMiddle = fiderived Private fil As IMiddle = fiderived Private fio As Object = fimiddle Private fisink As Object = fibase2 Private fim As IBase2 = fiderived Sub M1() fc = New Base() fe = New Middle() ff = New Base() fg = New Base() fg = New Middle() fh = New Derived() fj = 10 fj = 10.1 MM(fl, fo) fic = fibase1 fie = fimiddle fiff = fibase1 fig = fibase1 fig = fimiddle fih = fiderived IMM(fil, fio) fisink = 3 End Sub Sub MM(ByRef p1 As Middle, ByRef p2 As Object) p1 = New Middle() p2 = Nothing End Sub Sub IMM(ByRef p1 As IMiddle, ByRef p2 As object) p1 = Nothing p2 = Nothing End Sub End Class Class Base End Class Class Middle Inherits Base End Class Class Derived Inherits Middle End Class Structure Value Public Sub New(a As Integer) X = a End Sub Public X As Integer End Structure Interface IBase1 End Interface Interface IBase2 End Interface Interface IMiddle Inherits IBase1 End Interface Interface IDerived Inherits IMiddle Inherits IBase2 End Interface ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New SymbolCouldHaveMoreSpecificTypeAnalyzer}, Nothing, Nothing, Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "a").WithArguments("a", "Middle").WithLocation(3, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "b").WithArguments("b", "Value").WithLocation(4, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "c").WithArguments("c", "Base").WithLocation(5, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "d").WithArguments("d", "Derived").WithLocation(7, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "e").WithArguments("e", "Middle").WithLocation(8, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "g").WithArguments("g", "Base").WithLocation(12, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "i").WithArguments("i", "Integer").WithLocation(17, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "k").WithArguments("k", "Derived").WithLocation(21, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ia").WithArguments("ia", "IMiddle").WithLocation(31, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ic").WithArguments("ic", "IBase1").WithLocation(32, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "id").WithArguments("id", "IDerived").WithLocation(34, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ie").WithArguments("ie", "IMiddle").WithLocation(35, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ig").WithArguments("ig", "IBase1").WithLocation(39, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ik").WithArguments("ik", "IDerived").WithLocation(44, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "im").WithArguments("im", "IDerived").WithLocation(48, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fa").WithArguments("Private fa As Object", "Middle").WithLocation(53, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fb").WithArguments("Private fb As Object", "Value").WithLocation(54, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fc").WithArguments("Private fc As Object", "Base").WithLocation(55, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fd").WithArguments("Private fd As Base", "Derived").WithLocation(56, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fe").WithArguments("Private fe As Base", "Middle").WithLocation(57, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fg").WithArguments("Private fg As Object", "Base").WithLocation(59, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fi").WithArguments("Private fi As Object", "Integer").WithLocation(61, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fk").WithArguments("Private fk As Middle", "Derived").WithLocation(63, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fia").WithArguments("Private fia As Object", "IMiddle").WithLocation(72, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fic").WithArguments("Private fic As Object", "IBase1").WithLocation(73, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fid").WithArguments("Private fid As IBase1", "IDerived").WithLocation(74, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fie").WithArguments("Private fie As IBase1", "IMiddle").WithLocation(75, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fig").WithArguments("Private fig As Object", "IBase1").WithLocation(77, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fik").WithArguments("Private fik As IMiddle", "IDerived").WithLocation(79, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fim").WithArguments("Private fim As IBase2", "IDerived").WithLocation(83, 13)) End Sub <Fact> Public Sub ValueContextsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(Optional a As Integer = 16, Optional b As Integer = 17, Optional c As Integer = 18) End Sub Public F1 As Integer = 16 Public F2 As Integer = 17 Public F3 As Integer = 18 Public Sub M1() M0(16, 17, 18) M0(f1, f2, f3) M0() End Sub End Class Enum E A = 16 B C = 17 D = 18 End Enum Class C1 Public Sub New (a As Integer, b As Integer, c As Integer) End Sub Public F1 As C1 = New C1(c:=16, a:=17, b:=18) Public F2 As New C1(16, 17, 18) Public F3(16) As Integer Public F4(17) As Integer ' The upper bound specification is not presently treated as a code block. This is suspect. Public F5(18) As Integer Public F6 As Integer() = New Integer(16) {} Public F7 As Integer() = New Integer(17) {} End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New SeventeenTestAnalyzer}, Nothing, Nothing, Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(2, 71), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(6, 28), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(10, 16), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(19, 9), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(27, 40), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(28, 29), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(33, 42), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "M0").WithLocation(12, 9)) ' The M0 diagnostic is an artifact of the VB compiler filling in default values in the high-level bound tree, and is questionable. End Sub <Fact> Public Sub NullArgumentVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class Goo Public Sub New(X As String) End Sub End Class Class C Public Sub M0(x As String, y As String) End Sub Public Sub M1() M0("""", """") M0(Nothing, """") M0("""", Nothing) M0(Nothing, Nothing) End Sub Public Sub M2() Dim f1 = New Goo("""") Dim f2 = New Goo(Nothing) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New NullArgumentTestAnalyzer}, Nothing, Nothing, Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "Nothing").WithLocation(13, 12), Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "Nothing").WithLocation(14, 18), Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "Nothing").WithLocation(15, 12), Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "Nothing").WithLocation(15, 21), Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "Nothing").WithLocation(20, 26)) End Sub <Fact> Public Sub MemberInitializerVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class Bar Public Field As Boolean End Class Class Goo Public Field As Integer Public Property Prop1 As String Public Property Prop2 As Bar End Class Class C Public Sub M1() Dim f1 = New Goo() Dim f2 = New Goo() With {.Field = 10} Dim f3 = New Goo With {.Prop1 = Nothing} Dim f4 = New Goo With {.Field = 10, .Prop1 = Nothing} Dim f5 = New Goo With {.Prop2 = New Bar() With {.Field = True}} Dim e1 = New Goo() With {.Prop1 = 10} Dim e2 = New Goo With {10} End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedQualifiedNameInInit, "").WithLocation(20, 32)) comp.VerifyAnalyzerDiagnostics({New MemberInitializerTestAnalyzer}, Nothing, Nothing, Diagnostic(MemberInitializerTestAnalyzer.DoNotUseFieldInitializerDescriptor.Id, "Field").WithLocation(14, 35), Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Prop1").WithLocation(15, 33), Diagnostic(MemberInitializerTestAnalyzer.DoNotUseFieldInitializerDescriptor.Id, "Field").WithLocation(16, 33), Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Prop1").WithLocation(16, 46), Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Prop2").WithLocation(17, 33), Diagnostic(MemberInitializerTestAnalyzer.DoNotUseFieldInitializerDescriptor.Id, "Field").WithLocation(17, 58), Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Prop1").WithLocation(19, 35)) End Sub <Fact> Public Sub AssignmentVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class Bar Public Field As Boolean End Class Class Goo Public Field As Integer Public Property Prop1 As String Public Property Prop2 As Bar End Class Class C Public Sub M1() Dim f1 = New Goo() Dim f2 = New Goo() With {.Field = 10} Dim f3 = New Goo With {.Prop1 = Nothing} Dim f4 = New Goo With {.Field = 10, .Prop1 = Nothing} Dim f5 = New Goo With {.Prop2 = New Bar() With {.Field = True}} End Sub Public Sub M2() Dim f1 = New Goo With {.Prop2 = New Bar() With {.Field = True}} f1.Field = 0 f1.Prop1 = Nothing Dim f2 = New Bar() f2.Field = True End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New AssignmentTestAnalyzer}, Nothing, Nothing, Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Prop2 = New Bar() With {.Field = True}").WithLocation(21, 32), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Field = 10").WithLocation(14, 34), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Prop1 = Nothing").WithLocation(15, 32), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Field = 10").WithLocation(16, 32), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Prop1 = Nothing").WithLocation(16, 45), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Prop2 = New Bar() With {.Field = True}").WithLocation(17, 32), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Field = True").WithLocation(17, 57), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Field = True").WithLocation(21, 57), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, "f1.Field = 0").WithLocation(22, 9), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, "f1.Prop1 = Nothing").WithLocation(23, 9), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, "f2.Field = True").WithLocation(26, 9)) End Sub <Fact> Public Sub ArrayInitializerVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M1() Dim arr1 = New Integer() {} Dim arr2 As Object = {} Dim arr3 = {} Dim arr4 = New Integer() {1, 2, 3} Dim arr5 = {1, 2, 3} Dim arr6 As C() = {Nothing, Nothing, Nothing} Dim arr7 = New Integer() {1, 2, 3, 4, 5, 6} ' LargeList Dim arr8 = {1, 2, 3, 4, 5, 6} ' LargeList Dim arr9 As C() = {Nothing, Nothing, Nothing, Nothing, Nothing, Nothing} ' LargeList Dim arr10 As Integer(,) = {{1, 2, 3, 4, 5, 6}} ' LargeList Dim arr11 = New Integer(,) {{1, 2, 3, 4, 5, 6}, ' LargeList {7, 8, 9, 10, 11, 12}} ' LargeList Dim arr12 As C(,) = {{Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}, ' LargeList {Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}} ' LargeList Dim arr13 = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}} ' jagged array Dim arr14 = {({1, 2, 3}), ({4, 5}), ({6}), ({7})} Dim arr15 = {({({1, 2, 3, 4, 5, 6})})} ' LargeList End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New ArrayInitializerTestAnalyzer()}, Nothing, Nothing, Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{1, 2, 3, 4, 5, 6}").WithLocation(11, 34), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{1, 2, 3, 4, 5, 6}").WithLocation(12, 20), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}").WithLocation(13, 27), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{1, 2, 3, 4, 5, 6}").WithLocation(15, 36), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{1, 2, 3, 4, 5, 6}").WithLocation(16, 37), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{7, 8, 9, 10, 11, 12}").WithLocation(17, 37), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}").WithLocation(18, 30), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}").WithLocation(19, 29), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{1, 2, 3, 4, 5, 6}").WithLocation(24, 25)) End Sub <Fact> Public Sub VariableDeclarationVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C #Disable Warning BC42024 Dim field1, field2, field3, field4 As Integer Public Sub M1() Dim a1 = 10 Dim b1 As New Integer, b2, b3, b4 As New Goo(1) 'too many Dim c1, c2 As Integer, c3, c4 As Goo 'too many Dim d1() As Goo Dim e1 As Integer = 10, e2 = {1, 2, 3}, e3, e4 As C 'too many Dim f1 = 10, f2 = 11, f3 As Integer Dim h1, h2, , h3 As Integer 'too many Dim i1, i2, i3, i4 As New UndefType 'too many Dim j1, j2, j3, j4 As UndefType 'too many Dim k1 As Integer, k2, k3, k4 As New Goo(1) 'too many End Sub #Enable Warning BC42024 End Class Class Goo Public Sub New(X As Integer) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_ExpectedIdentifier, "").WithLocation(11, 21), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(12, 35), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(12, 35), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(12, 35), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(12, 35), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(13, 31), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(13, 31), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(13, 31), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(13, 31)) comp.VerifyAnalyzerDiagnostics({New VariableDeclarationTestAnalyzer}, Nothing, Nothing, Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "a1").WithLocation(5, 13), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim b1 As New Integer, b2, b3, b4 As New Goo(1)").WithLocation(6, 9), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "b1").WithLocation(6, 13), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "b2").WithLocation(6, 32), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "b3").WithLocation(6, 36), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "b4").WithLocation(6, 40), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim c1, c2 As Integer, c3, c4 As Goo").WithLocation(7, 9), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim e1 As Integer = 10, e2 = {1, 2, 3}, e3, e4 As C").WithLocation(9, 9), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "e1").WithLocation(9, 13), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "e2").WithLocation(9, 33), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "f1").WithLocation(10, 13), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "f2").WithLocation(10, 22), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim h1, h2, , h3 As Integer").WithLocation(11, 9), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim i1, i2, i3, i4 As New UndefType").WithLocation(12, 9), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim j1, j2, j3, j4 As UndefType").WithLocation(13, 9), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim k1 As Integer, k2, k3, k4 As New Goo(1)").WithLocation(14, 9), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "k2").WithLocation(14, 28), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "k3").WithLocation(14, 32), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "k4").WithLocation(14, 36)) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29568")> Public Sub CaseVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M1(x As Integer) Select Case x Case 1, 2 Exit Select Case = 10 Exit Select Case Else Exit Select End Select Select Case x Case 1 Exit Select Case = 1000 Exit Select Case Else Exit Select End Select Select Case x Case 10 To 500 Exit Select Case = 1000 Exit Select Case Else Exit Select End Select Select Case x Case 1, 980 To 985 Exit Select Case Else Exit Select End Select Select Case x Case 1 to 3, 980 To 985 Exit Select End Select Select Case x Case 1 Exit Select Case > 100000 Exit Select End Select Select Case x Case Else Exit Select End Select Select Case x End Select Select Case x Case 1 Exit Select Case Exit Select End Select Select Case x Case 1 Exit Select Case = Exit Select End Select Select Case x Case 1 Exit Select Case 2 to Exit Select End Select End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(60, 17), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(68, 1), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(74, 22)) comp.VerifyAnalyzerDiagnostics({New CaseTestAnalyzer}, Nothing, Nothing, Diagnostic(CaseTestAnalyzer.MultipleCaseClausesDescriptor.Id, "Case 1, 2 Exit Select").WithLocation(4, 13), Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "Case Else").WithLocation(8, 13), Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "Case Else").WithLocation(17, 13), Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "Case Else").WithLocation(26, 13), Diagnostic(CaseTestAnalyzer.MultipleCaseClausesDescriptor.Id, "Case 1, 980 To 985 Exit Select").WithLocation(31, 13), Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "Case Else").WithLocation(33, 13), Diagnostic(CaseTestAnalyzer.MultipleCaseClausesDescriptor.Id, "Case 1 to 3, 980 To 985 Exit Select").WithLocation(38, 13), Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "Case Else").WithLocation(50, 13)) End Sub <Fact> Public Sub ExplicitVsImplicitInstancesVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Overridable Sub M1() Me.M1() M1() End Sub Public Sub M2() End Sub End Class Class D Inherits C Public Overrides Sub M1() MyBase.M1() M1() M2() End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New ExplicitVsImplicitInstanceAnalyzer}, Nothing, Nothing, Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ExplicitInstanceDescriptor.Id, "Me").WithLocation(3, 9), Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ImplicitInstanceDescriptor.Id, "M1").WithLocation(4, 9), Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ExplicitInstanceDescriptor.Id, "MyBase").WithLocation(13, 9), Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ImplicitInstanceDescriptor.Id, "M1").WithLocation(14, 9), Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ImplicitInstanceDescriptor.Id, "M2").WithLocation(15, 9)) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub EventAndMethodReferencesVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Delegate Sub MumbleEventHandler(sender As Object, args As System.EventArgs) Class C Public Event Mumble As MumbleEventHandler Public Sub OnMumble(args As System.EventArgs) AddHandler Mumble, New MumbleEventHandler(AddressOf Mumbler) AddHandler Mumble, New MumbleEventHandler(Sub(s As Object, a As System.EventArgs) End Sub) AddHandler Mumble, Sub(s As Object, a As System.EventArgs) End Sub RaiseEvent Mumble(Me, args) ' Dim o As object = AddressOf Mumble Dim d As MumbleEventHandler = AddressOf Mumbler Mumbler(Me, Nothing) RemoveHandler Mumble, AddressOf Mumbler End Sub Private Sub Mumbler(sender As Object, args As System.EventArgs) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New MemberReferenceAnalyzer}, Nothing, Nothing, Diagnostic(MemberReferenceAnalyzer.HandlerAddedDescriptor.Id, "AddHandler Mumble, New MumbleEventHandler(AddressOf Mumbler)").WithLocation(7, 9), ' Bug: we are missing diagnostics of "MethodBindingDescriptor" here. https://github.com/dotnet/roslyn/issues/20095 Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(7, 20), Diagnostic(MemberReferenceAnalyzer.MethodBindingDescriptor.Id, "AddressOf Mumbler").WithLocation(7, 51), Diagnostic(MemberReferenceAnalyzer.HandlerAddedDescriptor.Id, "AddHandler Mumble, New MumbleEventHandler(Sub(s As Object, a As System.EventArgs) End Sub)").WithLocation(8, 9), Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(8, 20), Diagnostic(MemberReferenceAnalyzer.HandlerAddedDescriptor.Id, "AddHandler Mumble, Sub(s As Object, a As System.EventArgs) End Sub").WithLocation(10, 9), Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(10, 20), Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(12, 20), Diagnostic(MemberReferenceAnalyzer.MethodBindingDescriptor.Id, "AddressOf Mumbler").WithLocation(14, 39), Diagnostic(MemberReferenceAnalyzer.HandlerRemovedDescriptor.Id, "RemoveHandler Mumble, AddressOf Mumbler").WithLocation(16, 9), Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(16, 23), Diagnostic(MemberReferenceAnalyzer.MethodBindingDescriptor.Id, "AddressOf Mumbler").WithLocation(16, 31) ) End Sub <Fact> Public Sub ParamArraysVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(a As Integer, ParamArray b As Integer()) End Sub Public Sub M1() M0(1) M0(1, 2) M0(1, 2, 3, 4) M0(1, 2, 3, 4, 5) M0(1, 2, 3, 4, 5, 6) M0(1, New Integer() { 2, 3, 4 }) M0(1, New Integer() { 2, 3, 4, 5 }) M0(1, New Integer() { 2, 3, 4, 5, 6 }) Dim local As D = new D(1, 2, 3, 4, 5) local = new D(1, New Integer() { 2, 3, 4, 5 }) local = new D(1, 2, 3, 4) local = new D(1, New Integer() { 2, 3, 4 }) End Sub End Class Class D Public Sub New(a As Integer, ParamArray b As Integer()) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New ParamsArrayTestAnalyzer}, Nothing, Nothing, Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "M0(1, 2, 3, 4, 5)").WithLocation(9, 9), Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "M0(1, 2, 3, 4, 5, 6)").WithLocation(10, 9), Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "New Integer() { 2, 3, 4, 5 }").WithLocation(12, 15), Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "New Integer() { 2, 3, 4, 5, 6 }").WithLocation(13, 15), Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "D").WithLocation(14, 30), Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "New Integer() { 2, 3, 4, 5 }").WithLocation(15, 26)) End Sub <Fact> Public Sub FieldInitializersVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public F1 As Integer = 44 Public F2 As String = "Hello" Public F3 As Integer = Goo() Public Shared Function Goo() Return 10 End Function Public Shared Function Bar(Optional P1 As Integer = 10, Optional F2 As Integer = 20) Return P1 + F2 End Function End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New EqualsValueTestAnalyzer}, Nothing, Nothing, Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= 44").WithLocation(2, 26), Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= ""Hello""").WithLocation(3, 25), Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= Goo()").WithLocation(4, 26), Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= 20").WithLocation(10, 84)) End Sub <Fact> Public Sub OwningSymbolVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub UnFunkyMethod() Dim x As Integer = 0 Dim y As Integer = x End Sub Public Sub FunkyMethod() Dim x As Integer = 0 Dim y As Integer = x End Sub Public FunkyField As Integer = 12 Public UnFunkyField As Integer = 12 End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New OwningSymbolTestAnalyzer}, Nothing, Nothing, Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "0").WithLocation(8, 28), Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "x").WithLocation(9, 28), Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "12").WithLocation(12, 36)) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29568")> Public Sub NoneOperationVisualBasic() ' BoundCaseStatement is OperationKind.None Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M1(x as Integer) Select Case x Case 1, 2 Exit Select Case = 10 Exit Select Case Else Exit Select End Select End Sub Public Property Fred As Integer Set(value As Integer) Exit Property End Set Get Return 12 End Get End Property Public Sub Barney Resume End Sub End Class ]]> </file> </compilation> ' We have 2 OperationKind.None operations in the operation tree: ' (1) BoundUnstructuredExceptionHandlingStatement for the method block with Resume statement ' (2) BoundResumeStatement for Resume statement Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New NoneOperationTestAnalyzer}, Nothing, Nothing, Diagnostic(NoneOperationTestAnalyzer.NoneOperationDescriptor.Id, <![CDATA[Public Sub Barney Resume End Sub]]>).WithLocation(22, 5), Diagnostic(NoneOperationTestAnalyzer.NoneOperationDescriptor.Id, "Resume").WithLocation(23, 9)) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29568")> Public Sub LambdaExpressionVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Imports System Class B Public Sub M1(x As Integer) Dim action1 As Action = Sub() End Sub Dim action2 As Action = Sub() Console.WriteLine(1) End Sub Dim func1 As Func(Of Integer, Integer) = Function(value As Integer) value = value + 1 value = value + 1 value = value + 1 Return value + 1 End Function End Sub End Class Delegate Sub MumbleEventHandler(sender As Object, args As EventArgs) Class C Public Event Mumble As MumbleEventHandler Public Sub OnMumble(args As EventArgs) AddHandler Mumble, New MumbleEventHandler(Sub(s As Object, a As EventArgs) End Sub) AddHandler Mumble, Sub(s As Object, a As EventArgs) Dim value = 1 value = value + 1 value = value + 1 value = value + 1 End Sub RaiseEvent Mumble(Me, args) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New LambdaTestAnalyzer}, Nothing, Nothing, Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "Sub() End Sub").WithLocation(5, 33), Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "Sub(s As Object, a As EventArgs) End Sub").WithLocation(25, 51), Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "Sub() Console.WriteLine(1) End Sub").WithLocation(7, 33), Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "Sub(s As Object, a As EventArgs) Dim value = 1 value = value + 1 value = value + 1 value = value + 1 End Sub").WithLocation(27, 28), Diagnostic(LambdaTestAnalyzer.TooManyStatementsInLambdaExpressionDescriptor.Id, "Sub(s As Object, a As EventArgs) Dim value = 1 value = value + 1 value = value + 1 value = value + 1 End Sub").WithLocation(27, 28), Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "Function(value As Integer) value = value + 1 value = value + 1 value = value + 1 Return value + 1 End Function").WithLocation(10, 50), Diagnostic(LambdaTestAnalyzer.TooManyStatementsInLambdaExpressionDescriptor.Id, "Function(value As Integer) value = value + 1 value = value + 1 value = value + 1 Return value + 1 End Function").WithLocation(10, 50)) End Sub <WorkItem(8385, "https://github.com/dotnet/roslyn/issues/8385")> <Fact(Skip:="https://github.com/dotnet/roslyn/issues/18839")> Public Sub StaticMemberReferenceVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class D Public Shared Event E() Public Shared Field As Integer Public Shared Property P As Integer Public Shared Sub Method() End Sub End Class Class C Public Shared Event E() Public Shared Sub Bar() End Sub Public Sub Goo() AddHandler C.E, AddressOf D.Method RaiseEvent E() ' Can't raise static event with type in VB C.Bar() AddHandler D.E, Sub() End Sub D.Field = 1 Dim x = D.P D.Method() End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New StaticMemberTestAnalyzer}, Nothing, Nothing, Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "AddHandler C.E, AddressOf D.Method").WithLocation(19, 9), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "AddressOf D.Method").WithLocation(19, 25), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "E").WithLocation(20, 20), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "C.Bar()").WithLocation(21, 9), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "AddHandler D.E, Sub() End Sub").WithLocation(23, 9), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "D.Field").WithLocation(25, 9), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "D.P").WithLocation(26, 17), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "D.Method()").WithLocation(27, 9)) End Sub <Fact> Public Sub LabelOperatorsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Public Class A Public Sub Fred() Wilma: GoTo Betty Betty: GoTo Wilma End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New LabelOperationsTestAnalyzer}, Nothing, Nothing, Diagnostic(LabelOperationsTestAnalyzer.LabelDescriptor.Id, "Wilma:").WithLocation(3, 9), Diagnostic(LabelOperationsTestAnalyzer.GotoDescriptor.Id, "GoTo Betty").WithLocation(4, 9), Diagnostic(LabelOperationsTestAnalyzer.LabelDescriptor.Id, "Betty:").WithLocation(5, 9), Diagnostic(LabelOperationsTestAnalyzer.GotoDescriptor.Id, "GoTo Wilma").WithLocation(6, 9)) End Sub <Fact> Public Sub UnaryBinaryOperatorsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Public Class A Private ReadOnly _value As Integer Public Sub New (value As Integer) _value = value End Sub Public Shared Operator +(x As A, Y As A) As A Return New A(x._value + y._value) End Operator Public Shared Operator *(x As A, y As A) As A Return New A(x._value * y._value) End Operator Public Shared Operator -(x As A) As A Return New A(-x._value) End Operator Public Shared operator +(x As A) As A Return New A(+x._value) End Operator End CLass Class C Public Shared Sub Main() Dim B As Boolean = False Dim d As Double = 100 Dim a1 As New A(0) Dim a2 As New A(100) b = Not b d = d * 100 a1 = a1 + a2 a1 = -a2 End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New UnaryAndBinaryOperationsTestAnalyzer}, Nothing, Nothing, Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.BooleanNotDescriptor.Id, "Not b").WithLocation(33, 13), Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.DoubleMultiplyDescriptor.Id, "d * 100").WithLocation(34, 13), Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.OperatorAddMethodDescriptor.Id, "a1 + a2").WithLocation(35, 14), Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.OperatorMinusMethodDescriptor.Id, "-a2").WithLocation(36, 14)) End Sub <Fact> Public Sub BinaryOperatorsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Public Class B2 Public Shared Operator +(x As B2, y As B2) As B2 System.Console.WriteLine("+") Return x End Operator Public Shared Operator -(x As B2, y As B2) As B2 System.Console.WriteLine("-") Return x End Operator Public Shared Operator *(x As B2, y As B2) As B2 System.Console.WriteLine("*") Return x End Operator Public Shared Operator /(x As B2, y As B2) As B2 System.Console.WriteLine("/") Return x End Operator Public Shared Operator \(x As B2, y As B2) As B2 System.Console.WriteLine("\") Return x End Operator Public Shared Operator Mod(x As B2, y As B2) As B2 System.Console.WriteLine("Mod") Return x End Operator Public Shared Operator ^(x As B2, y As B2) As B2 System.Console.WriteLine("^") Return x End Operator Public Shared Operator =(x As B2, y As B2) As B2 System.Console.WriteLine("=") Return x End Operator Public Shared Operator <>(x As B2, y As B2) As B2 System.Console.WriteLine("<>") Return x End Operator Public Shared Operator <(x As B2, y As B2) As B2 System.Console.WriteLine("<") Return x End Operator Public Shared Operator >(x As B2, y As B2) As B2 System.Console.WriteLine(">") Return x End Operator Public Shared Operator <=(x As B2, y As B2) As B2 System.Console.WriteLine("<=") Return x End Operator Public Shared Operator >=(x As B2, y As B2) As B2 System.Console.WriteLine(">=") Return x End Operator Public Shared Operator Like(x As B2, y As B2) As B2 System.Console.WriteLine("Like") Return x End Operator Public Shared Operator &(x As B2, y As B2) As B2 System.Console.WriteLine("&") Return x End Operator Public Shared Operator And(x As B2, y As B2) As B2 System.Console.WriteLine("And") Return x End Operator Public Shared Operator Or(x As B2, y As B2) As B2 System.Console.WriteLine("Or") Return x End Operator Public Shared Operator Xor(x As B2, y As B2) As B2 System.Console.WriteLine("Xor") Return x End Operator Public Shared Operator <<(x As B2, y As Integer) As B2 System.Console.WriteLine("<<") Return x End Operator Public Shared Operator >>(x As B2, y As Integer) As B2 System.Console.WriteLine(">>") Return x End Operator End Class Module Module1 Sub Main() Dim x, y As New B2() Dim r As B2 r = x + y r = x - y r = x * y r = x / y r = x \ y r = x Mod y r = x ^ y r = x = y r = x <> y r = x < y r = x > y r = x <= y r = x >= y r = x Like y r = x & y r = x And y r = x Or y r = x Xor y r = x << 2 r = x >> 3 End Sub End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New BinaryOperatorVBTestAnalyzer}, Nothing, Nothing, Diagnostic("BinaryUserDefinedOperator", "x + y").WithArguments("Add").WithLocation(109, 13), Diagnostic("BinaryUserDefinedOperator", "x - y").WithArguments("Subtract").WithLocation(110, 13), Diagnostic("BinaryUserDefinedOperator", "x * y").WithArguments("Multiply").WithLocation(111, 13), Diagnostic("BinaryUserDefinedOperator", "x / y").WithArguments("Divide").WithLocation(112, 13), Diagnostic("BinaryUserDefinedOperator", "x \ y").WithArguments("IntegerDivide").WithLocation(113, 13), Diagnostic("BinaryUserDefinedOperator", "x Mod y").WithArguments("Remainder").WithLocation(114, 13), Diagnostic("BinaryUserDefinedOperator", "x ^ y").WithArguments("Power").WithLocation(115, 13), Diagnostic("BinaryUserDefinedOperator", "x = y").WithArguments("Equals").WithLocation(116, 13), Diagnostic("BinaryUserDefinedOperator", "x <> y").WithArguments("NotEquals").WithLocation(117, 13), Diagnostic("BinaryUserDefinedOperator", "x < y").WithArguments("LessThan").WithLocation(118, 13), Diagnostic("BinaryUserDefinedOperator", "x > y").WithArguments("GreaterThan").WithLocation(119, 13), Diagnostic("BinaryUserDefinedOperator", "x <= y").WithArguments("LessThanOrEqual").WithLocation(120, 13), Diagnostic("BinaryUserDefinedOperator", "x >= y").WithArguments("GreaterThanOrEqual").WithLocation(121, 13), Diagnostic("BinaryUserDefinedOperator", "x Like y").WithArguments("Like").WithLocation(122, 13), Diagnostic("BinaryUserDefinedOperator", "x & y").WithArguments("Concatenate").WithLocation(123, 13), Diagnostic("BinaryUserDefinedOperator", "x And y").WithArguments("And").WithLocation(124, 13), Diagnostic("BinaryUserDefinedOperator", "x Or y").WithArguments("Or").WithLocation(125, 13), Diagnostic("BinaryUserDefinedOperator", "x Xor y").WithArguments("ExclusiveOr").WithLocation(126, 13), Diagnostic("BinaryUserDefinedOperator", "x << 2").WithArguments("LeftShift").WithLocation(127, 13), Diagnostic("BinaryUserDefinedOperator", "x >> 3").WithArguments("RightShift").WithLocation(128, 13)) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29568")> Public Sub InvalidOperatorsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Public Class B2 Public Shared Operator +(x As B2, y As B2) As B2 System.Console.WriteLine("+") Return x End Operator Public Shared Operator -(x As B2) As B2 System.Console.WriteLine("-") Return x End Operator Public Shared Operator -(x As B2) As B2 System.Console.WriteLine("-") Return x End Operator End Class Module Module1 Sub Main() Dim x, y As New B2() x = x + 10 x = x + y x = -x End Sub End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_DuplicateProcDef1, "-", New Object() {"Public Shared Operator -(x As B2) As B2"}).WithLocation(8, 28), Diagnostic(ERRID.ERR_TypeMismatch2, "10", New Object() {"Integer", "B2"}).WithLocation(23, 17), Diagnostic(ERRID.ERR_NoMostSpecificOverload2, "-x", New Object() {"-", Environment.NewLine & " 'Public Shared Operator -(x As B2) As B2': Not most specific." & vbCrLf & " 'Public Shared Operator -(x As B2) As B2': Not most specific."}).WithLocation(25, 13)) ' no diagnostic since nodes are invalid comp.VerifyAnalyzerDiagnostics({New OperatorPropertyPullerTestAnalyzer}) End Sub <Fact> Public Sub NullOperationSyntaxVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(ParamArray b As Integer()) End Sub Public Sub M1() M0() M0(1) M0(1, 2) M0(New Integer() { }) M0(New Integer() { 1 }) M0(New Integer() { 1, 2 }) End Sub End Class ]]> </file> </compilation> ' TODO: array should not be treated as ParamArray argument ' https://github.com/dotnet/roslyn/issues/8570 Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New NullOperationSyntaxTestAnalyzer}, Nothing, Nothing, Diagnostic(NullOperationSyntaxTestAnalyzer.ParamsArrayOperationDescriptor.Id, "M0()").WithLocation(6, 9), Diagnostic(NullOperationSyntaxTestAnalyzer.ParamsArrayOperationDescriptor.Id, "M0(1)").WithLocation(7, 9), Diagnostic(NullOperationSyntaxTestAnalyzer.ParamsArrayOperationDescriptor.Id, "M0(1, 2)").WithLocation(8, 9)) End Sub <WorkItem(8114, "https://github.com/dotnet/roslyn/issues/8114")> <Fact> Public Sub InvalidOperatorVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Function M1(a As Double, b as C) as Double Return b + c End Sub Public Function M2(s As C) As C Return -s End Function End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_EndFunctionExpected, "Public Function M1(a As Double, b as C) as Double").WithLocation(2, 5), Diagnostic(ERRID.ERR_InvalidEndSub, "End Sub").WithLocation(4, 5), Diagnostic(ERRID.ERR_InvInsideEndsProc, "Public Function M2(s As C) As C").WithLocation(6, 5), Diagnostic(ERRID.ERR_ClassNotExpression1, "c").WithArguments("C").WithLocation(3, 20), Diagnostic(ERRID.ERR_UnaryOperand2, "-s").WithArguments("-", "C").WithLocation(7, 16)) comp.VerifyAnalyzerDiagnostics({New InvalidOperatorExpressionTestAnalyzer}, Nothing, Nothing, Diagnostic(InvalidOperatorExpressionTestAnalyzer.InvalidBinaryDescriptor.Id, "b + c").WithLocation(3, 16), Diagnostic(InvalidOperatorExpressionTestAnalyzer.InvalidUnaryDescriptor.Id, "-s").WithLocation(7, 16)) End Sub <WorkItem(9014, "https://github.com/dotnet/roslyn/issues/9014")> <Fact> Public Sub InvalidConstructorVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Protected Structure S End Structure End Class Class D Shared Sub M(o) M(New C.S()) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30389: 'C.S' is not accessible in this context because it is 'Protected'. M(New C.S()) ~~~ ]]></errors>) ' Reuse ParamsArrayTestAnalyzer for this test. comp.VerifyAnalyzerDiagnostics({New ParamsArrayTestAnalyzer}, Nothing, Nothing, Diagnostic(ParamsArrayTestAnalyzer.InvalidConstructorDescriptor.Id, "New C.S()").WithLocation(7, 11)) Dim tree = comp.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of ObjectCreationExpressionSyntax)().Single() comp.VerifyOperationTree(node, expectedOperationTree:=<![CDATA[ IObjectCreationOperation (Constructor: <null>) (OperationKind.ObjectCreation, Type: C.S, IsInvalid) (Syntax: 'New C.S()') Arguments(0) Initializer: null ]]>.Value) End Sub <Fact> Public Sub ConditionalAccessOperationsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Property Prop As Integer Get Return 0 End Get Set End Set End Property Public Field As Integer Default Public Property Mumble(i As Integer) Get return Field End Get Set Field = Value End Set End Property Public Field1 As C = Nothing Public Sub M0(p As C) Dim x = p?.Prop x = p?.Field x = p?(0) p?.M0(Nothing) x = Field1?.Prop x = Field1?.Field x = Field1?(0) Field1?.M0(Nothing) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() ' https://github.com/dotnet/roslyn/issues/21294 comp.VerifyAnalyzerDiagnostics({New ConditionalAccessOperationTestAnalyzer}, Nothing, Nothing, Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?.Prop").WithLocation(24, 17), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(24, 17), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?.Field").WithLocation(25, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(25, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?(0)").WithLocation(26, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(26, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?.M0(Nothing)").WithLocation(27, 9), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(27, 9), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?.Prop").WithLocation(29, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(29, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?.Field").WithLocation(30, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(30, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?(0)").WithLocation(31, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(31, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?.M0(Nothing)").WithLocation(32, 9), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(32, 9)) End Sub <WorkItem(8955, "https://github.com/dotnet/roslyn/issues/8955")> <Fact> Public Sub ForToLoopConditionCrashVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Imports System Module M1 Class C1(Of t) Shared Widening Operator CType(ByVal p1 As C1(Of t)) As Integer Return 1 End Operator Shared Widening Operator CType(ByVal p1 As Integer) As C1(Of t) Return Nothing End Operator Shared Operator -(ByVal p1 As C1(Of t), ByVal p2 As C1(Of t)) As C1(Of Short) Return Nothing End Operator Shared Operator +(ByVal p1 As C1(Of t), ByVal p2 As C1(Of t)) As C1(Of Integer) Return Nothing End Operator End Class Sub goo() For i As C1(Of Integer) = 1 To 10 Next End Sub End Module Module M2 ReadOnly Property Moo As Integer Get Return 1 End Get End Property WriteOnly Property Boo As integer Set(value As integer) End Set End Property Sub Main() For Moo = 1 to Moo step Moo Next For Boo = 1 to Boo step Boo Next End Sub End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_LoopControlMustNotBeProperty, "Moo").WithLocation(38, 13), Diagnostic(ERRID.ERR_LoopControlMustNotBeProperty, "Boo").WithLocation(41, 13), Diagnostic(ERRID.ERR_NoGetProperty1, "Boo").WithArguments("Boo").WithLocation(41, 24), Diagnostic(ERRID.ERR_NoGetProperty1, "Boo").WithArguments("Boo").WithLocation(41, 33), Diagnostic(ERRID.ERR_UnacceptableForLoopOperator2, "For i As C1(Of Integer) = 1 To 10").WithArguments("Public Shared Operator -(p1 As M1.C1(Of Integer), p2 As M1.C1(Of Integer)) As M1.C1(Of Short)", "M1.C1(Of Integer)").WithLocation(19, 9), Diagnostic(ERRID.ERR_ForLoopOperatorRequired2, "For i As C1(Of Integer) = 1 To 10").WithArguments("M1.C1(Of Integer)", "<=").WithLocation(19, 9), Diagnostic(ERRID.ERR_ForLoopOperatorRequired2, "For i As C1(Of Integer) = 1 To 10").WithArguments("M1.C1(Of Integer)", ">=").WithLocation(19, 9), Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports System").WithLocation(1, 1)) comp.VerifyAnalyzerDiagnostics({New ForLoopConditionCrashVBTestAnalyzer}, Nothing, Nothing, Diagnostic(ForLoopConditionCrashVBTestAnalyzer.ForLoopConditionCrashDescriptor.Id, "Boo").WithLocation(41, 24), Diagnostic(ForLoopConditionCrashVBTestAnalyzer.ForLoopConditionCrashDescriptor.Id, "10").WithLocation(19, 40)) End Sub <WorkItem(9012, "https://github.com/dotnet/roslyn/issues/9012")> <Fact> Public Sub InvalidEventInstanceVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Imports System Imports System.Collections.Generic Module Program Sub Main(args As String()) AddHandler Function(ByVal x) x End Sub End Module Class TestClass Event TestEvent As Action Shared Sub Test(receiver As TestClass) AddHandler receiver?.TestEvent, AddressOf Main End Sub Shared Sub Main() End Sub End Class Module Module1 Sub Main() Dim x = {Iterator sub() yield, new object} Dim y = {Iterator sub() yield 1, Iterator sub() yield, new object} Dim z = {Sub() AddHandler, New Object} g0(Iterator sub() Yield) g1(Iterator Sub() Yield, 5) End Sub Sub g0(ByVal x As Func(Of IEnumerator)) End Sub Sub g1(ByVal x As Func(Of IEnumerator), ByVal y As Integer) End Sub Iterator Function f() As IEnumerator Yield End Function End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_ExpectedComma, "").WithLocation(6, 39), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(6, 39), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(24, 38), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(25, 62), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(26, 34), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(27, 32), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(28, 32), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(37, 14), Diagnostic(ERRID.ERR_TooFewGenericArguments1, "IEnumerator").WithArguments("System.Collections.Generic.IEnumerator(Of Out T)").WithLocation(31, 31), Diagnostic(ERRID.ERR_TooFewGenericArguments1, "IEnumerator").WithArguments("System.Collections.Generic.IEnumerator(Of Out T)").WithLocation(33, 31), Diagnostic(ERRID.ERR_TooFewGenericArguments1, "IEnumerator").WithArguments("System.Collections.Generic.IEnumerator(Of Out T)").WithLocation(36, 30), Diagnostic(ERRID.ERR_AddOrRemoveHandlerEvent, "receiver?.TestEvent").WithLocation(15, 20), Diagnostic(ERRID.ERR_AddOrRemoveHandlerEvent, "Function(ByVal x) x").WithLocation(6, 20), Diagnostic(ERRID.ERR_BadIteratorReturn, "sub").WithLocation(24, 27), Diagnostic(ERRID.ERR_BadIteratorReturn, "sub").WithLocation(25, 27), Diagnostic(ERRID.ERR_BadIteratorReturn, "sub").WithLocation(25, 51), Diagnostic(ERRID.ERR_BadIteratorReturn, "sub").WithLocation(27, 21), Diagnostic(ERRID.ERR_BadIteratorReturn, "Sub").WithLocation(28, 21), Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports System.Collections.Generic").WithLocation(2, 1)) comp.VerifyAnalyzerDiagnostics({New MemberReferenceAnalyzer}, Nothing, Nothing, Diagnostic("HandlerAdded", "AddHandler Function(ByVal x) x").WithLocation(6, 9), Diagnostic("InvalidEvent", "AddHandler Function(ByVal x) x").WithLocation(6, 9), Diagnostic("HandlerAdded", "AddHandler receiver?.TestEvent, AddressOf Main").WithLocation(15, 9), Diagnostic("InvalidEvent", "AddHandler receiver?.TestEvent, AddressOf Main").WithLocation(15, 9), Diagnostic("HandlerAdded", "AddHandler, New Object").WithLocation(26, 24), Diagnostic("InvalidEvent", "AddHandler, New Object").WithLocation(26, 24), Diagnostic("EventReference", ".TestEvent").WithLocation(15, 29)) End Sub <Fact, WorkItem(9127, "https://github.com/dotnet/roslyn/issues/9127")> Public Sub UnaryTrueFalseOperationVisualBasic() ' BoundCaseStatement is OperationKind.None Dim source = <compilation> <file name="c.vb"> <![CDATA[ Module Module1 Structure S8 Public Shared Narrowing Operator CType(x As S8) As Boolean System.Console.WriteLine("Narrowing Operator CType(x As S8) As Boolean") Return Nothing End Operator Public Shared Operator IsTrue(x As S8) As Boolean System.Console.WriteLine("IsTrue(x As S8) As Boolean") Return False End Operator Public Shared Operator IsFalse(x As S8) As Boolean System.Console.WriteLine("IsFalse(x As S8) As Boolean") Return False End Operator Public Shared Operator And(x As S8, y As S8) As S8 Return New S8() End Operator End Structure Sub Main() Dim x As New S8 Dim y As New S8 If x Then 'BIND1:"x" System.Console.WriteLine("If") Else System.Console.WriteLine("Else") End If If x AndAlso y Then End If End Sub End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New TrueFalseUnaryOperationTestAnalyzer}, Nothing, Nothing, Diagnostic(TrueFalseUnaryOperationTestAnalyzer.UnaryTrueDescriptor.Id, "x").WithLocation(27, 12), Diagnostic(TrueFalseUnaryOperationTestAnalyzer.UnaryTrueDescriptor.Id, "x AndAlso y").WithLocation(33, 12)) End Sub <Fact> Public Sub TestOperationBlockAnalyzer_EmptyMethodBody() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M() End Sub Public Sub M2(i as Integer) End Sub Public Sub M3(Optional i as Integer = 0) End Sub End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New OperationBlockAnalyzer}, Nothing, Nothing, Diagnostic("ID", "M").WithArguments("M", "Block").WithLocation(2, 16), Diagnostic("ID", "M2").WithArguments("M2", "Block").WithLocation(5, 16), Diagnostic("ID", "M3").WithArguments("M3", "ParameterInitializer").WithLocation(8, 16), Diagnostic("ID", "M3").WithArguments("M3", "Block").WithLocation(8, 16)) 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 Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics <CompilerTrait(CompilerFeature.IOperation)> Public Class OperationAnalyzerTests Inherits BasicTestBase <Fact> Public Sub EmptyArrayVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Sub M1() Dim arr1 As Integer() = New Integer(-1) { } ' yes Dim arr2 As Byte() = { } ' yes Dim arr3 As C() = New C(-1) { } ' yes Dim arr4 As String() = New String() { Nothing } ' no Dim arr5 As Double() = New Double(1) { } ' no Dim arr6 As Integer() = { -1 } ' no Dim arr7 as Integer()() = New Integer(-1)() { } ' yes Dim arr8 as Integer()()()() = New Integer( -1)()()() { } ' yes Dim arr9 as Integer(,) = New Integer(-1,-1) { } ' no Dim arr10 as Integer()(,) = New Integer(-1)(,) { } ' yes Dim arr11 as Integer()(,) = New Integer(1)(,) { } ' no Dim arr12 as Integer(,)() = New Integer(-1,-1)() { } ' no Dim arr13 as Integer() = New Integer(0) { } ' no End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New EmptyArrayAnalyzer}, Nothing, Nothing, Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New Integer(-1) { }").WithLocation(3, 33), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "{ }").WithLocation(4, 30), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New C(-1) { }").WithLocation(5, 27), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New Integer(-1)() { }").WithLocation(9, 35), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New Integer( -1)()()() { }").WithLocation(10, 39), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New Integer(-1)(,) { }").WithLocation(12, 37)) End Sub <Fact> Public Sub BoxingVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Function M1(p1 As Object, p2 As Object, p3 As Object) As Object Dim v1 As New S Dim v2 As S = v1 Dim v3 As S = v1.M1(v2) Dim v4 As Object = M1(3, Me, v1) Dim v5 As Object = v3 If p1 Is Nothing return 3 End If If p2 Is Nothing return v3 End If If p3 Is Nothing Return v4 End If Return v5 End Function End Class Structure S Public X As Integer Public Y As Integer Public Z As Object Public Function M1(p1 As S) As S p1.GetType() Z = Me Return p1 End Function End Structure ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New BoxingOperationAnalyzer}, Nothing, Nothing, Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "3").WithLocation(6, 32), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "v1").WithLocation(6, 39), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "v3").WithLocation(7, 29), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "3").WithLocation(9, 21), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "v3").WithLocation(12, 21), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "p1").WithLocation(27, 9), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "Me").WithLocation(28, 13)) End Sub <Fact> Public Sub BadStuffVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M1(z as Integer) Framitz() Dim x As Integer = Bexley() Dim y As Integer = 10 Dim d As Double() = Nothing M1(d) Goto End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyAnalyzerDiagnostics({New BadStuffTestAnalyzer}, Nothing, Nothing, Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Framitz()").WithLocation(3, 9), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Framitz()").WithLocation(3, 9), Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Framitz").WithLocation(3, 9), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Framitz").WithLocation(3, 9), Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Bexley()").WithLocation(4, 28), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Bexley()").WithLocation(4, 28), Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Bexley").WithLocation(4, 28), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Bexley").WithLocation(4, 28), Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "M1(d)").WithLocation(7, 9), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "M1(d)").WithLocation(7, 9), Diagnostic(BadStuffTestAnalyzer.InvalidStatementDescriptor.Id, "Goto").WithLocation(8, 9), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Goto").WithLocation(8, 9), Diagnostic(BadStuffTestAnalyzer.InvalidStatementDescriptor.Id, "").WithLocation(8, 13), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "").WithLocation(8, 13)) End Sub <Fact> Public Sub SwitchVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M1(x As Integer) Select Case x Case 1, 2 Exit Select Case = 10 Exit Select Case Else Exit Select End Select Select Case x Case 1 Exit Select Case = 1000 Exit Select Case Else Exit Select End Select Select Case x Case 10 To 500 Exit Select Case = 1000 Exit Select Case Else Exit Select End Select Select Case x Case 1, 980 To 985 Exit Select Case Else Exit Select End Select Select Case x Case 1 to 3, 980 To 985 Exit Select End Select Select Case x Case 1 Exit Select Case > 100000 Exit Select End Select Select Case x Case Else Exit Select End Select Select Case x End Select Select Case x Case 1 Exit Select Case Exit Select End Select Select Case x Case 1 Exit Select Case = Exit Select End Select Select Case x Case 1 Exit Select Case 2 to Exit Select End Select End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(60, 17), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(68, 1), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(74, 22)) comp.VerifyAnalyzerDiagnostics({New SwitchTestAnalyzer}, Nothing, Nothing, Diagnostic(SwitchTestAnalyzer.SparseSwitchDescriptor.Id, "x").WithLocation(12, 21), Diagnostic(SwitchTestAnalyzer.SparseSwitchDescriptor.Id, "x").WithLocation(30, 21), Diagnostic(SwitchTestAnalyzer.SparseSwitchDescriptor.Id, "x").WithLocation(37, 21), Diagnostic(SwitchTestAnalyzer.NoDefaultSwitchDescriptor.Id, "x").WithLocation(37, 21), Diagnostic(SwitchTestAnalyzer.NoDefaultSwitchDescriptor.Id, "x").WithLocation(42, 21), Diagnostic(SwitchTestAnalyzer.OnlyDefaultSwitchDescriptor.Id, "x").WithLocation(49, 21), Diagnostic(SwitchTestAnalyzer.SparseSwitchDescriptor.Id, "x").WithLocation(54, 21), Diagnostic(SwitchTestAnalyzer.NoDefaultSwitchDescriptor.Id, "x").WithLocation(54, 21)) End Sub <Fact> Public Sub InvocationVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(a As Integer, ParamArray b As Integer()) End Sub Public Sub M1(a As Integer, b As Integer, c As Integer, x As Integer, y As Integer, z As Integer) End Sub Public Sub M2() M1(1, 2, 3, 4, 5, 6) M1(a:=1, b:=2, c:=3, x:=4, y:=5, z:=6) M1(a:=1, c:=2, b:=3, x:=4, y:=5, z:=6) M1(z:=1, x:=2, y:=3, c:=4, a:=5, b:=6) M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13) M0(1) M0(1, 2, 4, 3) End Sub Public Sub M3(Optional a As Integer = Nothing, Optional b As Integer = 0) End Sub Public Sub M4() M3(Nothing, 0) M3(Nothing,) M3(,0) M3(,) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New InvocationTestAnalyzer}, Nothing, Nothing, Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3(Nothing,)").WithArguments("b").WithLocation(25, 9), Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3(,0)").WithArguments("a").WithLocation(26, 9), Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3(,)").WithArguments("a").WithLocation(27, 9), Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3(,)").WithArguments("b").WithLocation(27, 9), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "2").WithLocation(11, 21), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "4").WithLocation(12, 33), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "2").WithLocation(12, 21), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "1").WithLocation(12, 15), Diagnostic(InvocationTestAnalyzer.BigParamArrayArgumentsDescriptor.Id, "M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)").WithLocation(14, 9), Diagnostic(InvocationTestAnalyzer.BigParamArrayArgumentsDescriptor.Id, "M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)").WithLocation(15, 9), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "3").WithLocation(17, 21)) End Sub <Fact> Public Sub FieldCouldBeReadOnlyVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public F1 As Integer Public Const F2 As Integer = 2 Public ReadOnly F3 As Integer Public F4 As Integer Public F5 As Integer Public F6 As Integer = 6 Public F7 As Integer Public F9 As S Public F10 As New C1 Public Sub New() F1 = 1 F4 = 4 F5 = 5 End Sub Public Sub M0() Dim x As Integer = F1 x = F2 x = F3 x = F4 x = F5 x = F6 x = F7 F4 = 4 F7 = 7 M1(F1, F5) F9.A = 10 F9.B = 20 F10.A = F9.A F10.B = F9.B End Sub Public Sub M1(ByRef X As Integer, Y As Integer) x = 10 End Sub Structure S Public A As Integer Public B As Integer End Structure Class C1 Public A As Integer Public B As Integer End Class End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New FieldCouldBeReadOnlyAnalyzer}, Nothing, Nothing, Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F5").WithLocation(6, 12), Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F6").WithLocation(7, 12), Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F10").WithLocation(10, 12)) End Sub <Fact> Public Sub StaticFieldCouldBeReadOnlyVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Shared F1 As Integer Public Shared ReadOnly F2 As Integer = 2 Public Shared Readonly F3 As Integer Public Shared F4 As Integer Public Shared F5 As Integer Public Shared F6 As Integer = 6 Public Shared F7 As Integer Public Shared F9 As S Public Shared F10 As New C1 Shared Sub New() F1 = 1 F4 = 4 F5 = 5 End Sub Public Shared Sub M0() Dim x As Integer = F1 x = F2 x = F3 x = F4 x = F5 x = F6 x = F7 F4 = 4 F7 = 7 M1(F1, F5) F9.A = 10 F9.B = 20 F10.A = F9.A F10.B = F9.B End Sub Public Shared Sub M1(ByRef X As Integer, Y As Integer) x = 10 End Sub Structure S Public A As Integer Public B As Integer End Structure Class C1 Public A As Integer Public B As Integer End Class End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New FieldCouldBeReadOnlyAnalyzer}, Nothing, Nothing, Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F5").WithLocation(6, 19), Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F6").WithLocation(7, 19), Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F10").WithLocation(10, 19)) End Sub <Fact> Public Sub LocalCouldBeConstVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(p as Integer) Dim x As Integer = p Dim y As Integer = x Const z As Integer = 1 Dim a As Integer = 2 Dim b As Integer = 3 Dim c As Integer = 4 Dim d As Integer = 5 Dim e As Integer = 6 Dim s As String = "ZZZ" b = 3 c -= 12 d += e + b M1(y, z, a, s) Dim n As S n.A = 10 n.B = 20 Dim o As New C1 o.A = 10 o.B = 20 End Sub Public Sub M1(ByRef x As Integer, y As Integer, ByRef z as Integer, s as String) x = 10 End Sub End Class Structure S Public A As Integer Public B As Integer End Structure Class C1 Public A As Integer Public B As Integer End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New LocalCouldBeConstAnalyzer}, Nothing, Nothing, Diagnostic(LocalCouldBeConstAnalyzer.LocalCouldBeConstDescriptor.Id, "e").WithLocation(10, 13), Diagnostic(LocalCouldBeConstAnalyzer.LocalCouldBeConstDescriptor.Id, "s").WithLocation(11, 13)) End Sub <Fact> Public Sub SymbolCouldHaveMoreSpecificTypeVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0() Dim a As Object = New Middle() Dim b As Object = New Value(10) Dim c As Object = New Middle() c = New Base() Dim d As Base = New Derived() Dim e As Base = New Derived() e = New Middle() Dim f As Base = New Middle() f = New Base() Dim g As Object = New Derived() g = New Base() g = New Middle() Dim h As New Middle() h = New Derived() Dim i As Object = 3 Dim j As Object j = 10 j = 10.1 Dim k As Middle = New Derived() Dim l As Middle = New Derived() Dim o As Object = New Middle() MM(l, o) Dim ibase1 As IBase1 = Nothing Dim ibase2 As IBase2 = Nothing Dim imiddle As IMiddle = Nothing Dim iderived As IDerived = Nothing Dim ia As Object = imiddle Dim ic As Object = imiddle ic = ibase1 Dim id As IBase1 = iderived Dim ie As IBase1 = iderived ie = imiddle Dim iff As IBase1 = imiddle iff = ibase1 Dim ig As Object = iderived ig = ibase1 ig = imiddle Dim ih = imiddle ih = iderived Dim ik As IMiddle = iderived Dim il As IMiddle = iderived Dim io As Object = imiddle IMM(il, io) Dim im As IBase2 = iderived Dim isink As Object = ibase2 isink = 3 End Sub Private fa As Object = New Middle() Private fb As Object = New Value(10) Private fc As Object = New Middle() Private fd As Base = New Derived() Private fe As Base = New Derived() Private ff As Base = New Middle() Private fg As Object = New Derived() Private fh As New Middle() Private fi As Object = 3 Private fj As Object Private fk As Middle = New Derived() Private fl As Middle = New Derived() Private fo As Object = New Middle() Private Shared fibase1 As IBase1 = Nothing Private Shared fibase2 As IBase2 = Nothing Private Shared fimiddle As IMiddle= Nothing Private Shared fiderived As IDerived = Nothing Private fia As Object = fimiddle Private fic As Object = fimiddle Private fid As IBase1 = fiderived Private fie As IBase1 = fiderived Private fiff As IBase1 = fimiddle Private fig As Object = fiderived Private fih As IMiddle = fimiddle Private fik As IMiddle = fiderived Private fil As IMiddle = fiderived Private fio As Object = fimiddle Private fisink As Object = fibase2 Private fim As IBase2 = fiderived Sub M1() fc = New Base() fe = New Middle() ff = New Base() fg = New Base() fg = New Middle() fh = New Derived() fj = 10 fj = 10.1 MM(fl, fo) fic = fibase1 fie = fimiddle fiff = fibase1 fig = fibase1 fig = fimiddle fih = fiderived IMM(fil, fio) fisink = 3 End Sub Sub MM(ByRef p1 As Middle, ByRef p2 As Object) p1 = New Middle() p2 = Nothing End Sub Sub IMM(ByRef p1 As IMiddle, ByRef p2 As object) p1 = Nothing p2 = Nothing End Sub End Class Class Base End Class Class Middle Inherits Base End Class Class Derived Inherits Middle End Class Structure Value Public Sub New(a As Integer) X = a End Sub Public X As Integer End Structure Interface IBase1 End Interface Interface IBase2 End Interface Interface IMiddle Inherits IBase1 End Interface Interface IDerived Inherits IMiddle Inherits IBase2 End Interface ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New SymbolCouldHaveMoreSpecificTypeAnalyzer}, Nothing, Nothing, Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "a").WithArguments("a", "Middle").WithLocation(3, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "b").WithArguments("b", "Value").WithLocation(4, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "c").WithArguments("c", "Base").WithLocation(5, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "d").WithArguments("d", "Derived").WithLocation(7, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "e").WithArguments("e", "Middle").WithLocation(8, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "g").WithArguments("g", "Base").WithLocation(12, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "i").WithArguments("i", "Integer").WithLocation(17, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "k").WithArguments("k", "Derived").WithLocation(21, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ia").WithArguments("ia", "IMiddle").WithLocation(31, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ic").WithArguments("ic", "IBase1").WithLocation(32, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "id").WithArguments("id", "IDerived").WithLocation(34, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ie").WithArguments("ie", "IMiddle").WithLocation(35, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ig").WithArguments("ig", "IBase1").WithLocation(39, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ik").WithArguments("ik", "IDerived").WithLocation(44, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "im").WithArguments("im", "IDerived").WithLocation(48, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fa").WithArguments("Private fa As Object", "Middle").WithLocation(53, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fb").WithArguments("Private fb As Object", "Value").WithLocation(54, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fc").WithArguments("Private fc As Object", "Base").WithLocation(55, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fd").WithArguments("Private fd As Base", "Derived").WithLocation(56, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fe").WithArguments("Private fe As Base", "Middle").WithLocation(57, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fg").WithArguments("Private fg As Object", "Base").WithLocation(59, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fi").WithArguments("Private fi As Object", "Integer").WithLocation(61, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fk").WithArguments("Private fk As Middle", "Derived").WithLocation(63, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fia").WithArguments("Private fia As Object", "IMiddle").WithLocation(72, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fic").WithArguments("Private fic As Object", "IBase1").WithLocation(73, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fid").WithArguments("Private fid As IBase1", "IDerived").WithLocation(74, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fie").WithArguments("Private fie As IBase1", "IMiddle").WithLocation(75, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fig").WithArguments("Private fig As Object", "IBase1").WithLocation(77, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fik").WithArguments("Private fik As IMiddle", "IDerived").WithLocation(79, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fim").WithArguments("Private fim As IBase2", "IDerived").WithLocation(83, 13)) End Sub <Fact> Public Sub ValueContextsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(Optional a As Integer = 16, Optional b As Integer = 17, Optional c As Integer = 18) End Sub Public F1 As Integer = 16 Public F2 As Integer = 17 Public F3 As Integer = 18 Public Sub M1() M0(16, 17, 18) M0(f1, f2, f3) M0() End Sub End Class Enum E A = 16 B C = 17 D = 18 End Enum Class C1 Public Sub New (a As Integer, b As Integer, c As Integer) End Sub Public F1 As C1 = New C1(c:=16, a:=17, b:=18) Public F2 As New C1(16, 17, 18) Public F3(16) As Integer Public F4(17) As Integer ' The upper bound specification is not presently treated as a code block. This is suspect. Public F5(18) As Integer Public F6 As Integer() = New Integer(16) {} Public F7 As Integer() = New Integer(17) {} End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New SeventeenTestAnalyzer}, Nothing, Nothing, Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(2, 71), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(6, 28), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(10, 16), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(19, 9), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(27, 40), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(28, 29), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(33, 42), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "M0").WithLocation(12, 9)) ' The M0 diagnostic is an artifact of the VB compiler filling in default values in the high-level bound tree, and is questionable. End Sub <Fact> Public Sub NullArgumentVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class Goo Public Sub New(X As String) End Sub End Class Class C Public Sub M0(x As String, y As String) End Sub Public Sub M1() M0("""", """") M0(Nothing, """") M0("""", Nothing) M0(Nothing, Nothing) End Sub Public Sub M2() Dim f1 = New Goo("""") Dim f2 = New Goo(Nothing) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New NullArgumentTestAnalyzer}, Nothing, Nothing, Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "Nothing").WithLocation(13, 12), Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "Nothing").WithLocation(14, 18), Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "Nothing").WithLocation(15, 12), Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "Nothing").WithLocation(15, 21), Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "Nothing").WithLocation(20, 26)) End Sub <Fact> Public Sub MemberInitializerVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class Bar Public Field As Boolean End Class Class Goo Public Field As Integer Public Property Prop1 As String Public Property Prop2 As Bar End Class Class C Public Sub M1() Dim f1 = New Goo() Dim f2 = New Goo() With {.Field = 10} Dim f3 = New Goo With {.Prop1 = Nothing} Dim f4 = New Goo With {.Field = 10, .Prop1 = Nothing} Dim f5 = New Goo With {.Prop2 = New Bar() With {.Field = True}} Dim e1 = New Goo() With {.Prop1 = 10} Dim e2 = New Goo With {10} End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedQualifiedNameInInit, "").WithLocation(20, 32)) comp.VerifyAnalyzerDiagnostics({New MemberInitializerTestAnalyzer}, Nothing, Nothing, Diagnostic(MemberInitializerTestAnalyzer.DoNotUseFieldInitializerDescriptor.Id, "Field").WithLocation(14, 35), Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Prop1").WithLocation(15, 33), Diagnostic(MemberInitializerTestAnalyzer.DoNotUseFieldInitializerDescriptor.Id, "Field").WithLocation(16, 33), Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Prop1").WithLocation(16, 46), Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Prop2").WithLocation(17, 33), Diagnostic(MemberInitializerTestAnalyzer.DoNotUseFieldInitializerDescriptor.Id, "Field").WithLocation(17, 58), Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Prop1").WithLocation(19, 35)) End Sub <Fact> Public Sub AssignmentVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class Bar Public Field As Boolean End Class Class Goo Public Field As Integer Public Property Prop1 As String Public Property Prop2 As Bar End Class Class C Public Sub M1() Dim f1 = New Goo() Dim f2 = New Goo() With {.Field = 10} Dim f3 = New Goo With {.Prop1 = Nothing} Dim f4 = New Goo With {.Field = 10, .Prop1 = Nothing} Dim f5 = New Goo With {.Prop2 = New Bar() With {.Field = True}} End Sub Public Sub M2() Dim f1 = New Goo With {.Prop2 = New Bar() With {.Field = True}} f1.Field = 0 f1.Prop1 = Nothing Dim f2 = New Bar() f2.Field = True End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New AssignmentTestAnalyzer}, Nothing, Nothing, Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Prop2 = New Bar() With {.Field = True}").WithLocation(21, 32), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Field = 10").WithLocation(14, 34), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Prop1 = Nothing").WithLocation(15, 32), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Field = 10").WithLocation(16, 32), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Prop1 = Nothing").WithLocation(16, 45), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Prop2 = New Bar() With {.Field = True}").WithLocation(17, 32), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Field = True").WithLocation(17, 57), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Field = True").WithLocation(21, 57), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, "f1.Field = 0").WithLocation(22, 9), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, "f1.Prop1 = Nothing").WithLocation(23, 9), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, "f2.Field = True").WithLocation(26, 9)) End Sub <Fact> Public Sub ArrayInitializerVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M1() Dim arr1 = New Integer() {} Dim arr2 As Object = {} Dim arr3 = {} Dim arr4 = New Integer() {1, 2, 3} Dim arr5 = {1, 2, 3} Dim arr6 As C() = {Nothing, Nothing, Nothing} Dim arr7 = New Integer() {1, 2, 3, 4, 5, 6} ' LargeList Dim arr8 = {1, 2, 3, 4, 5, 6} ' LargeList Dim arr9 As C() = {Nothing, Nothing, Nothing, Nothing, Nothing, Nothing} ' LargeList Dim arr10 As Integer(,) = {{1, 2, 3, 4, 5, 6}} ' LargeList Dim arr11 = New Integer(,) {{1, 2, 3, 4, 5, 6}, ' LargeList {7, 8, 9, 10, 11, 12}} ' LargeList Dim arr12 As C(,) = {{Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}, ' LargeList {Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}} ' LargeList Dim arr13 = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}} ' jagged array Dim arr14 = {({1, 2, 3}), ({4, 5}), ({6}), ({7})} Dim arr15 = {({({1, 2, 3, 4, 5, 6})})} ' LargeList End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New ArrayInitializerTestAnalyzer()}, Nothing, Nothing, Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{1, 2, 3, 4, 5, 6}").WithLocation(11, 34), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{1, 2, 3, 4, 5, 6}").WithLocation(12, 20), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}").WithLocation(13, 27), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{1, 2, 3, 4, 5, 6}").WithLocation(15, 36), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{1, 2, 3, 4, 5, 6}").WithLocation(16, 37), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{7, 8, 9, 10, 11, 12}").WithLocation(17, 37), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}").WithLocation(18, 30), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}").WithLocation(19, 29), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{1, 2, 3, 4, 5, 6}").WithLocation(24, 25)) End Sub <Fact> Public Sub VariableDeclarationVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C #Disable Warning BC42024 Dim field1, field2, field3, field4 As Integer Public Sub M1() Dim a1 = 10 Dim b1 As New Integer, b2, b3, b4 As New Goo(1) 'too many Dim c1, c2 As Integer, c3, c4 As Goo 'too many Dim d1() As Goo Dim e1 As Integer = 10, e2 = {1, 2, 3}, e3, e4 As C 'too many Dim f1 = 10, f2 = 11, f3 As Integer Dim h1, h2, , h3 As Integer 'too many Dim i1, i2, i3, i4 As New UndefType 'too many Dim j1, j2, j3, j4 As UndefType 'too many Dim k1 As Integer, k2, k3, k4 As New Goo(1) 'too many End Sub #Enable Warning BC42024 End Class Class Goo Public Sub New(X As Integer) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_ExpectedIdentifier, "").WithLocation(11, 21), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(12, 35), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(12, 35), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(12, 35), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(12, 35), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(13, 31), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(13, 31), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(13, 31), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(13, 31)) comp.VerifyAnalyzerDiagnostics({New VariableDeclarationTestAnalyzer}, Nothing, Nothing, Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "a1").WithLocation(5, 13), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim b1 As New Integer, b2, b3, b4 As New Goo(1)").WithLocation(6, 9), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "b1").WithLocation(6, 13), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "b2").WithLocation(6, 32), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "b3").WithLocation(6, 36), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "b4").WithLocation(6, 40), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim c1, c2 As Integer, c3, c4 As Goo").WithLocation(7, 9), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim e1 As Integer = 10, e2 = {1, 2, 3}, e3, e4 As C").WithLocation(9, 9), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "e1").WithLocation(9, 13), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "e2").WithLocation(9, 33), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "f1").WithLocation(10, 13), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "f2").WithLocation(10, 22), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim h1, h2, , h3 As Integer").WithLocation(11, 9), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim i1, i2, i3, i4 As New UndefType").WithLocation(12, 9), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim j1, j2, j3, j4 As UndefType").WithLocation(13, 9), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim k1 As Integer, k2, k3, k4 As New Goo(1)").WithLocation(14, 9), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "k2").WithLocation(14, 28), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "k3").WithLocation(14, 32), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "k4").WithLocation(14, 36)) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29568")> Public Sub CaseVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M1(x As Integer) Select Case x Case 1, 2 Exit Select Case = 10 Exit Select Case Else Exit Select End Select Select Case x Case 1 Exit Select Case = 1000 Exit Select Case Else Exit Select End Select Select Case x Case 10 To 500 Exit Select Case = 1000 Exit Select Case Else Exit Select End Select Select Case x Case 1, 980 To 985 Exit Select Case Else Exit Select End Select Select Case x Case 1 to 3, 980 To 985 Exit Select End Select Select Case x Case 1 Exit Select Case > 100000 Exit Select End Select Select Case x Case Else Exit Select End Select Select Case x End Select Select Case x Case 1 Exit Select Case Exit Select End Select Select Case x Case 1 Exit Select Case = Exit Select End Select Select Case x Case 1 Exit Select Case 2 to Exit Select End Select End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(60, 17), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(68, 1), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(74, 22)) comp.VerifyAnalyzerDiagnostics({New CaseTestAnalyzer}, Nothing, Nothing, Diagnostic(CaseTestAnalyzer.MultipleCaseClausesDescriptor.Id, "Case 1, 2 Exit Select").WithLocation(4, 13), Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "Case Else").WithLocation(8, 13), Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "Case Else").WithLocation(17, 13), Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "Case Else").WithLocation(26, 13), Diagnostic(CaseTestAnalyzer.MultipleCaseClausesDescriptor.Id, "Case 1, 980 To 985 Exit Select").WithLocation(31, 13), Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "Case Else").WithLocation(33, 13), Diagnostic(CaseTestAnalyzer.MultipleCaseClausesDescriptor.Id, "Case 1 to 3, 980 To 985 Exit Select").WithLocation(38, 13), Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "Case Else").WithLocation(50, 13)) End Sub <Fact> Public Sub ExplicitVsImplicitInstancesVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Overridable Sub M1() Me.M1() M1() End Sub Public Sub M2() End Sub End Class Class D Inherits C Public Overrides Sub M1() MyBase.M1() M1() M2() End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New ExplicitVsImplicitInstanceAnalyzer}, Nothing, Nothing, Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ExplicitInstanceDescriptor.Id, "Me").WithLocation(3, 9), Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ImplicitInstanceDescriptor.Id, "M1").WithLocation(4, 9), Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ExplicitInstanceDescriptor.Id, "MyBase").WithLocation(13, 9), Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ImplicitInstanceDescriptor.Id, "M1").WithLocation(14, 9), Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ImplicitInstanceDescriptor.Id, "M2").WithLocation(15, 9)) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub EventAndMethodReferencesVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Delegate Sub MumbleEventHandler(sender As Object, args As System.EventArgs) Class C Public Event Mumble As MumbleEventHandler Public Sub OnMumble(args As System.EventArgs) AddHandler Mumble, New MumbleEventHandler(AddressOf Mumbler) AddHandler Mumble, New MumbleEventHandler(Sub(s As Object, a As System.EventArgs) End Sub) AddHandler Mumble, Sub(s As Object, a As System.EventArgs) End Sub RaiseEvent Mumble(Me, args) ' Dim o As object = AddressOf Mumble Dim d As MumbleEventHandler = AddressOf Mumbler Mumbler(Me, Nothing) RemoveHandler Mumble, AddressOf Mumbler End Sub Private Sub Mumbler(sender As Object, args As System.EventArgs) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New MemberReferenceAnalyzer}, Nothing, Nothing, Diagnostic(MemberReferenceAnalyzer.HandlerAddedDescriptor.Id, "AddHandler Mumble, New MumbleEventHandler(AddressOf Mumbler)").WithLocation(7, 9), ' Bug: we are missing diagnostics of "MethodBindingDescriptor" here. https://github.com/dotnet/roslyn/issues/20095 Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(7, 20), Diagnostic(MemberReferenceAnalyzer.MethodBindingDescriptor.Id, "AddressOf Mumbler").WithLocation(7, 51), Diagnostic(MemberReferenceAnalyzer.HandlerAddedDescriptor.Id, "AddHandler Mumble, New MumbleEventHandler(Sub(s As Object, a As System.EventArgs) End Sub)").WithLocation(8, 9), Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(8, 20), Diagnostic(MemberReferenceAnalyzer.HandlerAddedDescriptor.Id, "AddHandler Mumble, Sub(s As Object, a As System.EventArgs) End Sub").WithLocation(10, 9), Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(10, 20), Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(12, 20), Diagnostic(MemberReferenceAnalyzer.MethodBindingDescriptor.Id, "AddressOf Mumbler").WithLocation(14, 39), Diagnostic(MemberReferenceAnalyzer.HandlerRemovedDescriptor.Id, "RemoveHandler Mumble, AddressOf Mumbler").WithLocation(16, 9), Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(16, 23), Diagnostic(MemberReferenceAnalyzer.MethodBindingDescriptor.Id, "AddressOf Mumbler").WithLocation(16, 31) ) End Sub <Fact> Public Sub ParamArraysVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(a As Integer, ParamArray b As Integer()) End Sub Public Sub M1() M0(1) M0(1, 2) M0(1, 2, 3, 4) M0(1, 2, 3, 4, 5) M0(1, 2, 3, 4, 5, 6) M0(1, New Integer() { 2, 3, 4 }) M0(1, New Integer() { 2, 3, 4, 5 }) M0(1, New Integer() { 2, 3, 4, 5, 6 }) Dim local As D = new D(1, 2, 3, 4, 5) local = new D(1, New Integer() { 2, 3, 4, 5 }) local = new D(1, 2, 3, 4) local = new D(1, New Integer() { 2, 3, 4 }) End Sub End Class Class D Public Sub New(a As Integer, ParamArray b As Integer()) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New ParamsArrayTestAnalyzer}, Nothing, Nothing, Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "M0(1, 2, 3, 4, 5)").WithLocation(9, 9), Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "M0(1, 2, 3, 4, 5, 6)").WithLocation(10, 9), Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "New Integer() { 2, 3, 4, 5 }").WithLocation(12, 15), Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "New Integer() { 2, 3, 4, 5, 6 }").WithLocation(13, 15), Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "D").WithLocation(14, 30), Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "New Integer() { 2, 3, 4, 5 }").WithLocation(15, 26)) End Sub <Fact> Public Sub FieldInitializersVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public F1 As Integer = 44 Public F2 As String = "Hello" Public F3 As Integer = Goo() Public Shared Function Goo() Return 10 End Function Public Shared Function Bar(Optional P1 As Integer = 10, Optional F2 As Integer = 20) Return P1 + F2 End Function End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New EqualsValueTestAnalyzer}, Nothing, Nothing, Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= 44").WithLocation(2, 26), Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= ""Hello""").WithLocation(3, 25), Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= Goo()").WithLocation(4, 26), Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= 20").WithLocation(10, 84)) End Sub <Fact> Public Sub OwningSymbolVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub UnFunkyMethod() Dim x As Integer = 0 Dim y As Integer = x End Sub Public Sub FunkyMethod() Dim x As Integer = 0 Dim y As Integer = x End Sub Public FunkyField As Integer = 12 Public UnFunkyField As Integer = 12 End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New OwningSymbolTestAnalyzer}, Nothing, Nothing, Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "0").WithLocation(8, 28), Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "x").WithLocation(9, 28), Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "12").WithLocation(12, 36)) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29568")> Public Sub NoneOperationVisualBasic() ' BoundCaseStatement is OperationKind.None Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M1(x as Integer) Select Case x Case 1, 2 Exit Select Case = 10 Exit Select Case Else Exit Select End Select End Sub Public Property Fred As Integer Set(value As Integer) Exit Property End Set Get Return 12 End Get End Property Public Sub Barney Resume End Sub End Class ]]> </file> </compilation> ' We have 2 OperationKind.None operations in the operation tree: ' (1) BoundUnstructuredExceptionHandlingStatement for the method block with Resume statement ' (2) BoundResumeStatement for Resume statement Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New NoneOperationTestAnalyzer}, Nothing, Nothing, Diagnostic(NoneOperationTestAnalyzer.NoneOperationDescriptor.Id, <![CDATA[Public Sub Barney Resume End Sub]]>).WithLocation(22, 5), Diagnostic(NoneOperationTestAnalyzer.NoneOperationDescriptor.Id, "Resume").WithLocation(23, 9)) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29568")> Public Sub LambdaExpressionVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Imports System Class B Public Sub M1(x As Integer) Dim action1 As Action = Sub() End Sub Dim action2 As Action = Sub() Console.WriteLine(1) End Sub Dim func1 As Func(Of Integer, Integer) = Function(value As Integer) value = value + 1 value = value + 1 value = value + 1 Return value + 1 End Function End Sub End Class Delegate Sub MumbleEventHandler(sender As Object, args As EventArgs) Class C Public Event Mumble As MumbleEventHandler Public Sub OnMumble(args As EventArgs) AddHandler Mumble, New MumbleEventHandler(Sub(s As Object, a As EventArgs) End Sub) AddHandler Mumble, Sub(s As Object, a As EventArgs) Dim value = 1 value = value + 1 value = value + 1 value = value + 1 End Sub RaiseEvent Mumble(Me, args) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New LambdaTestAnalyzer}, Nothing, Nothing, Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "Sub() End Sub").WithLocation(5, 33), Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "Sub(s As Object, a As EventArgs) End Sub").WithLocation(25, 51), Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "Sub() Console.WriteLine(1) End Sub").WithLocation(7, 33), Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "Sub(s As Object, a As EventArgs) Dim value = 1 value = value + 1 value = value + 1 value = value + 1 End Sub").WithLocation(27, 28), Diagnostic(LambdaTestAnalyzer.TooManyStatementsInLambdaExpressionDescriptor.Id, "Sub(s As Object, a As EventArgs) Dim value = 1 value = value + 1 value = value + 1 value = value + 1 End Sub").WithLocation(27, 28), Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "Function(value As Integer) value = value + 1 value = value + 1 value = value + 1 Return value + 1 End Function").WithLocation(10, 50), Diagnostic(LambdaTestAnalyzer.TooManyStatementsInLambdaExpressionDescriptor.Id, "Function(value As Integer) value = value + 1 value = value + 1 value = value + 1 Return value + 1 End Function").WithLocation(10, 50)) End Sub <WorkItem(8385, "https://github.com/dotnet/roslyn/issues/8385")> <Fact(Skip:="https://github.com/dotnet/roslyn/issues/18839")> Public Sub StaticMemberReferenceVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class D Public Shared Event E() Public Shared Field As Integer Public Shared Property P As Integer Public Shared Sub Method() End Sub End Class Class C Public Shared Event E() Public Shared Sub Bar() End Sub Public Sub Goo() AddHandler C.E, AddressOf D.Method RaiseEvent E() ' Can't raise static event with type in VB C.Bar() AddHandler D.E, Sub() End Sub D.Field = 1 Dim x = D.P D.Method() End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New StaticMemberTestAnalyzer}, Nothing, Nothing, Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "AddHandler C.E, AddressOf D.Method").WithLocation(19, 9), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "AddressOf D.Method").WithLocation(19, 25), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "E").WithLocation(20, 20), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "C.Bar()").WithLocation(21, 9), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "AddHandler D.E, Sub() End Sub").WithLocation(23, 9), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "D.Field").WithLocation(25, 9), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "D.P").WithLocation(26, 17), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "D.Method()").WithLocation(27, 9)) End Sub <Fact> Public Sub LabelOperatorsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Public Class A Public Sub Fred() Wilma: GoTo Betty Betty: GoTo Wilma End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New LabelOperationsTestAnalyzer}, Nothing, Nothing, Diagnostic(LabelOperationsTestAnalyzer.LabelDescriptor.Id, "Wilma:").WithLocation(3, 9), Diagnostic(LabelOperationsTestAnalyzer.GotoDescriptor.Id, "GoTo Betty").WithLocation(4, 9), Diagnostic(LabelOperationsTestAnalyzer.LabelDescriptor.Id, "Betty:").WithLocation(5, 9), Diagnostic(LabelOperationsTestAnalyzer.GotoDescriptor.Id, "GoTo Wilma").WithLocation(6, 9)) End Sub <Fact> Public Sub UnaryBinaryOperatorsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Public Class A Private ReadOnly _value As Integer Public Sub New (value As Integer) _value = value End Sub Public Shared Operator +(x As A, Y As A) As A Return New A(x._value + y._value) End Operator Public Shared Operator *(x As A, y As A) As A Return New A(x._value * y._value) End Operator Public Shared Operator -(x As A) As A Return New A(-x._value) End Operator Public Shared operator +(x As A) As A Return New A(+x._value) End Operator End CLass Class C Public Shared Sub Main() Dim B As Boolean = False Dim d As Double = 100 Dim a1 As New A(0) Dim a2 As New A(100) b = Not b d = d * 100 a1 = a1 + a2 a1 = -a2 End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New UnaryAndBinaryOperationsTestAnalyzer}, Nothing, Nothing, Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.BooleanNotDescriptor.Id, "Not b").WithLocation(33, 13), Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.DoubleMultiplyDescriptor.Id, "d * 100").WithLocation(34, 13), Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.OperatorAddMethodDescriptor.Id, "a1 + a2").WithLocation(35, 14), Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.OperatorMinusMethodDescriptor.Id, "-a2").WithLocation(36, 14)) End Sub <Fact> Public Sub BinaryOperatorsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Public Class B2 Public Shared Operator +(x As B2, y As B2) As B2 System.Console.WriteLine("+") Return x End Operator Public Shared Operator -(x As B2, y As B2) As B2 System.Console.WriteLine("-") Return x End Operator Public Shared Operator *(x As B2, y As B2) As B2 System.Console.WriteLine("*") Return x End Operator Public Shared Operator /(x As B2, y As B2) As B2 System.Console.WriteLine("/") Return x End Operator Public Shared Operator \(x As B2, y As B2) As B2 System.Console.WriteLine("\") Return x End Operator Public Shared Operator Mod(x As B2, y As B2) As B2 System.Console.WriteLine("Mod") Return x End Operator Public Shared Operator ^(x As B2, y As B2) As B2 System.Console.WriteLine("^") Return x End Operator Public Shared Operator =(x As B2, y As B2) As B2 System.Console.WriteLine("=") Return x End Operator Public Shared Operator <>(x As B2, y As B2) As B2 System.Console.WriteLine("<>") Return x End Operator Public Shared Operator <(x As B2, y As B2) As B2 System.Console.WriteLine("<") Return x End Operator Public Shared Operator >(x As B2, y As B2) As B2 System.Console.WriteLine(">") Return x End Operator Public Shared Operator <=(x As B2, y As B2) As B2 System.Console.WriteLine("<=") Return x End Operator Public Shared Operator >=(x As B2, y As B2) As B2 System.Console.WriteLine(">=") Return x End Operator Public Shared Operator Like(x As B2, y As B2) As B2 System.Console.WriteLine("Like") Return x End Operator Public Shared Operator &(x As B2, y As B2) As B2 System.Console.WriteLine("&") Return x End Operator Public Shared Operator And(x As B2, y As B2) As B2 System.Console.WriteLine("And") Return x End Operator Public Shared Operator Or(x As B2, y As B2) As B2 System.Console.WriteLine("Or") Return x End Operator Public Shared Operator Xor(x As B2, y As B2) As B2 System.Console.WriteLine("Xor") Return x End Operator Public Shared Operator <<(x As B2, y As Integer) As B2 System.Console.WriteLine("<<") Return x End Operator Public Shared Operator >>(x As B2, y As Integer) As B2 System.Console.WriteLine(">>") Return x End Operator End Class Module Module1 Sub Main() Dim x, y As New B2() Dim r As B2 r = x + y r = x - y r = x * y r = x / y r = x \ y r = x Mod y r = x ^ y r = x = y r = x <> y r = x < y r = x > y r = x <= y r = x >= y r = x Like y r = x & y r = x And y r = x Or y r = x Xor y r = x << 2 r = x >> 3 End Sub End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New BinaryOperatorVBTestAnalyzer}, Nothing, Nothing, Diagnostic("BinaryUserDefinedOperator", "x + y").WithArguments("Add").WithLocation(109, 13), Diagnostic("BinaryUserDefinedOperator", "x - y").WithArguments("Subtract").WithLocation(110, 13), Diagnostic("BinaryUserDefinedOperator", "x * y").WithArguments("Multiply").WithLocation(111, 13), Diagnostic("BinaryUserDefinedOperator", "x / y").WithArguments("Divide").WithLocation(112, 13), Diagnostic("BinaryUserDefinedOperator", "x \ y").WithArguments("IntegerDivide").WithLocation(113, 13), Diagnostic("BinaryUserDefinedOperator", "x Mod y").WithArguments("Remainder").WithLocation(114, 13), Diagnostic("BinaryUserDefinedOperator", "x ^ y").WithArguments("Power").WithLocation(115, 13), Diagnostic("BinaryUserDefinedOperator", "x = y").WithArguments("Equals").WithLocation(116, 13), Diagnostic("BinaryUserDefinedOperator", "x <> y").WithArguments("NotEquals").WithLocation(117, 13), Diagnostic("BinaryUserDefinedOperator", "x < y").WithArguments("LessThan").WithLocation(118, 13), Diagnostic("BinaryUserDefinedOperator", "x > y").WithArguments("GreaterThan").WithLocation(119, 13), Diagnostic("BinaryUserDefinedOperator", "x <= y").WithArguments("LessThanOrEqual").WithLocation(120, 13), Diagnostic("BinaryUserDefinedOperator", "x >= y").WithArguments("GreaterThanOrEqual").WithLocation(121, 13), Diagnostic("BinaryUserDefinedOperator", "x Like y").WithArguments("Like").WithLocation(122, 13), Diagnostic("BinaryUserDefinedOperator", "x & y").WithArguments("Concatenate").WithLocation(123, 13), Diagnostic("BinaryUserDefinedOperator", "x And y").WithArguments("And").WithLocation(124, 13), Diagnostic("BinaryUserDefinedOperator", "x Or y").WithArguments("Or").WithLocation(125, 13), Diagnostic("BinaryUserDefinedOperator", "x Xor y").WithArguments("ExclusiveOr").WithLocation(126, 13), Diagnostic("BinaryUserDefinedOperator", "x << 2").WithArguments("LeftShift").WithLocation(127, 13), Diagnostic("BinaryUserDefinedOperator", "x >> 3").WithArguments("RightShift").WithLocation(128, 13)) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29568")> Public Sub InvalidOperatorsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Public Class B2 Public Shared Operator +(x As B2, y As B2) As B2 System.Console.WriteLine("+") Return x End Operator Public Shared Operator -(x As B2) As B2 System.Console.WriteLine("-") Return x End Operator Public Shared Operator -(x As B2) As B2 System.Console.WriteLine("-") Return x End Operator End Class Module Module1 Sub Main() Dim x, y As New B2() x = x + 10 x = x + y x = -x End Sub End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_DuplicateProcDef1, "-", New Object() {"Public Shared Operator -(x As B2) As B2"}).WithLocation(8, 28), Diagnostic(ERRID.ERR_TypeMismatch2, "10", New Object() {"Integer", "B2"}).WithLocation(23, 17), Diagnostic(ERRID.ERR_NoMostSpecificOverload2, "-x", New Object() {"-", Environment.NewLine & " 'Public Shared Operator -(x As B2) As B2': Not most specific." & vbCrLf & " 'Public Shared Operator -(x As B2) As B2': Not most specific."}).WithLocation(25, 13)) ' no diagnostic since nodes are invalid comp.VerifyAnalyzerDiagnostics({New OperatorPropertyPullerTestAnalyzer}) End Sub <Fact> Public Sub NullOperationSyntaxVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(ParamArray b As Integer()) End Sub Public Sub M1() M0() M0(1) M0(1, 2) M0(New Integer() { }) M0(New Integer() { 1 }) M0(New Integer() { 1, 2 }) End Sub End Class ]]> </file> </compilation> ' TODO: array should not be treated as ParamArray argument ' https://github.com/dotnet/roslyn/issues/8570 Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New NullOperationSyntaxTestAnalyzer}, Nothing, Nothing, Diagnostic(NullOperationSyntaxTestAnalyzer.ParamsArrayOperationDescriptor.Id, "M0()").WithLocation(6, 9), Diagnostic(NullOperationSyntaxTestAnalyzer.ParamsArrayOperationDescriptor.Id, "M0(1)").WithLocation(7, 9), Diagnostic(NullOperationSyntaxTestAnalyzer.ParamsArrayOperationDescriptor.Id, "M0(1, 2)").WithLocation(8, 9)) End Sub <WorkItem(8114, "https://github.com/dotnet/roslyn/issues/8114")> <Fact> Public Sub InvalidOperatorVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Function M1(a As Double, b as C) as Double Return b + c End Sub Public Function M2(s As C) As C Return -s End Function End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_EndFunctionExpected, "Public Function M1(a As Double, b as C) as Double").WithLocation(2, 5), Diagnostic(ERRID.ERR_InvalidEndSub, "End Sub").WithLocation(4, 5), Diagnostic(ERRID.ERR_InvInsideEndsProc, "Public Function M2(s As C) As C").WithLocation(6, 5), Diagnostic(ERRID.ERR_ClassNotExpression1, "c").WithArguments("C").WithLocation(3, 20), Diagnostic(ERRID.ERR_UnaryOperand2, "-s").WithArguments("-", "C").WithLocation(7, 16)) comp.VerifyAnalyzerDiagnostics({New InvalidOperatorExpressionTestAnalyzer}, Nothing, Nothing, Diagnostic(InvalidOperatorExpressionTestAnalyzer.InvalidBinaryDescriptor.Id, "b + c").WithLocation(3, 16), Diagnostic(InvalidOperatorExpressionTestAnalyzer.InvalidUnaryDescriptor.Id, "-s").WithLocation(7, 16)) End Sub <WorkItem(9014, "https://github.com/dotnet/roslyn/issues/9014")> <Fact> Public Sub InvalidConstructorVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Protected Structure S End Structure End Class Class D Shared Sub M(o) M(New C.S()) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30389: 'C.S' is not accessible in this context because it is 'Protected'. M(New C.S()) ~~~ ]]></errors>) ' Reuse ParamsArrayTestAnalyzer for this test. comp.VerifyAnalyzerDiagnostics({New ParamsArrayTestAnalyzer}, Nothing, Nothing, Diagnostic(ParamsArrayTestAnalyzer.InvalidConstructorDescriptor.Id, "New C.S()").WithLocation(7, 11)) Dim tree = comp.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of ObjectCreationExpressionSyntax)().Single() comp.VerifyOperationTree(node, expectedOperationTree:=<![CDATA[ IObjectCreationOperation (Constructor: <null>) (OperationKind.ObjectCreation, Type: C.S, IsInvalid) (Syntax: 'New C.S()') Arguments(0) Initializer: null ]]>.Value) End Sub <Fact> Public Sub ConditionalAccessOperationsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Property Prop As Integer Get Return 0 End Get Set End Set End Property Public Field As Integer Default Public Property Mumble(i As Integer) Get return Field End Get Set Field = Value End Set End Property Public Field1 As C = Nothing Public Sub M0(p As C) Dim x = p?.Prop x = p?.Field x = p?(0) p?.M0(Nothing) x = Field1?.Prop x = Field1?.Field x = Field1?(0) Field1?.M0(Nothing) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() ' https://github.com/dotnet/roslyn/issues/21294 comp.VerifyAnalyzerDiagnostics({New ConditionalAccessOperationTestAnalyzer}, Nothing, Nothing, Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?.Prop").WithLocation(24, 17), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(24, 17), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?.Field").WithLocation(25, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(25, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?(0)").WithLocation(26, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(26, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?.M0(Nothing)").WithLocation(27, 9), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(27, 9), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?.Prop").WithLocation(29, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(29, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?.Field").WithLocation(30, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(30, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?(0)").WithLocation(31, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(31, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?.M0(Nothing)").WithLocation(32, 9), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(32, 9)) End Sub <WorkItem(8955, "https://github.com/dotnet/roslyn/issues/8955")> <Fact> Public Sub ForToLoopConditionCrashVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Imports System Module M1 Class C1(Of t) Shared Widening Operator CType(ByVal p1 As C1(Of t)) As Integer Return 1 End Operator Shared Widening Operator CType(ByVal p1 As Integer) As C1(Of t) Return Nothing End Operator Shared Operator -(ByVal p1 As C1(Of t), ByVal p2 As C1(Of t)) As C1(Of Short) Return Nothing End Operator Shared Operator +(ByVal p1 As C1(Of t), ByVal p2 As C1(Of t)) As C1(Of Integer) Return Nothing End Operator End Class Sub goo() For i As C1(Of Integer) = 1 To 10 Next End Sub End Module Module M2 ReadOnly Property Moo As Integer Get Return 1 End Get End Property WriteOnly Property Boo As integer Set(value As integer) End Set End Property Sub Main() For Moo = 1 to Moo step Moo Next For Boo = 1 to Boo step Boo Next End Sub End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_LoopControlMustNotBeProperty, "Moo").WithLocation(38, 13), Diagnostic(ERRID.ERR_LoopControlMustNotBeProperty, "Boo").WithLocation(41, 13), Diagnostic(ERRID.ERR_NoGetProperty1, "Boo").WithArguments("Boo").WithLocation(41, 24), Diagnostic(ERRID.ERR_NoGetProperty1, "Boo").WithArguments("Boo").WithLocation(41, 33), Diagnostic(ERRID.ERR_UnacceptableForLoopOperator2, "For i As C1(Of Integer) = 1 To 10").WithArguments("Public Shared Operator -(p1 As M1.C1(Of Integer), p2 As M1.C1(Of Integer)) As M1.C1(Of Short)", "M1.C1(Of Integer)").WithLocation(19, 9), Diagnostic(ERRID.ERR_ForLoopOperatorRequired2, "For i As C1(Of Integer) = 1 To 10").WithArguments("M1.C1(Of Integer)", "<=").WithLocation(19, 9), Diagnostic(ERRID.ERR_ForLoopOperatorRequired2, "For i As C1(Of Integer) = 1 To 10").WithArguments("M1.C1(Of Integer)", ">=").WithLocation(19, 9), Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports System").WithLocation(1, 1)) comp.VerifyAnalyzerDiagnostics({New ForLoopConditionCrashVBTestAnalyzer}, Nothing, Nothing, Diagnostic(ForLoopConditionCrashVBTestAnalyzer.ForLoopConditionCrashDescriptor.Id, "Boo").WithLocation(41, 24), Diagnostic(ForLoopConditionCrashVBTestAnalyzer.ForLoopConditionCrashDescriptor.Id, "10").WithLocation(19, 40)) End Sub <WorkItem(9012, "https://github.com/dotnet/roslyn/issues/9012")> <Fact> Public Sub InvalidEventInstanceVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Imports System Imports System.Collections.Generic Module Program Sub Main(args As String()) AddHandler Function(ByVal x) x End Sub End Module Class TestClass Event TestEvent As Action Shared Sub Test(receiver As TestClass) AddHandler receiver?.TestEvent, AddressOf Main End Sub Shared Sub Main() End Sub End Class Module Module1 Sub Main() Dim x = {Iterator sub() yield, new object} Dim y = {Iterator sub() yield 1, Iterator sub() yield, new object} Dim z = {Sub() AddHandler, New Object} g0(Iterator sub() Yield) g1(Iterator Sub() Yield, 5) End Sub Sub g0(ByVal x As Func(Of IEnumerator)) End Sub Sub g1(ByVal x As Func(Of IEnumerator), ByVal y As Integer) End Sub Iterator Function f() As IEnumerator Yield End Function End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_ExpectedComma, "").WithLocation(6, 39), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(6, 39), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(24, 38), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(25, 62), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(26, 34), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(27, 32), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(28, 32), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(37, 14), Diagnostic(ERRID.ERR_TooFewGenericArguments1, "IEnumerator").WithArguments("System.Collections.Generic.IEnumerator(Of Out T)").WithLocation(31, 31), Diagnostic(ERRID.ERR_TooFewGenericArguments1, "IEnumerator").WithArguments("System.Collections.Generic.IEnumerator(Of Out T)").WithLocation(33, 31), Diagnostic(ERRID.ERR_TooFewGenericArguments1, "IEnumerator").WithArguments("System.Collections.Generic.IEnumerator(Of Out T)").WithLocation(36, 30), Diagnostic(ERRID.ERR_AddOrRemoveHandlerEvent, "receiver?.TestEvent").WithLocation(15, 20), Diagnostic(ERRID.ERR_AddOrRemoveHandlerEvent, "Function(ByVal x) x").WithLocation(6, 20), Diagnostic(ERRID.ERR_BadIteratorReturn, "sub").WithLocation(24, 27), Diagnostic(ERRID.ERR_BadIteratorReturn, "sub").WithLocation(25, 27), Diagnostic(ERRID.ERR_BadIteratorReturn, "sub").WithLocation(25, 51), Diagnostic(ERRID.ERR_BadIteratorReturn, "sub").WithLocation(27, 21), Diagnostic(ERRID.ERR_BadIteratorReturn, "Sub").WithLocation(28, 21), Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports System.Collections.Generic").WithLocation(2, 1)) comp.VerifyAnalyzerDiagnostics({New MemberReferenceAnalyzer}, Nothing, Nothing, Diagnostic("HandlerAdded", "AddHandler Function(ByVal x) x").WithLocation(6, 9), Diagnostic("InvalidEvent", "AddHandler Function(ByVal x) x").WithLocation(6, 9), Diagnostic("HandlerAdded", "AddHandler receiver?.TestEvent, AddressOf Main").WithLocation(15, 9), Diagnostic("InvalidEvent", "AddHandler receiver?.TestEvent, AddressOf Main").WithLocation(15, 9), Diagnostic("HandlerAdded", "AddHandler, New Object").WithLocation(26, 24), Diagnostic("InvalidEvent", "AddHandler, New Object").WithLocation(26, 24), Diagnostic("EventReference", ".TestEvent").WithLocation(15, 29)) End Sub <Fact, WorkItem(9127, "https://github.com/dotnet/roslyn/issues/9127")> Public Sub UnaryTrueFalseOperationVisualBasic() ' BoundCaseStatement is OperationKind.None Dim source = <compilation> <file name="c.vb"> <![CDATA[ Module Module1 Structure S8 Public Shared Narrowing Operator CType(x As S8) As Boolean System.Console.WriteLine("Narrowing Operator CType(x As S8) As Boolean") Return Nothing End Operator Public Shared Operator IsTrue(x As S8) As Boolean System.Console.WriteLine("IsTrue(x As S8) As Boolean") Return False End Operator Public Shared Operator IsFalse(x As S8) As Boolean System.Console.WriteLine("IsFalse(x As S8) As Boolean") Return False End Operator Public Shared Operator And(x As S8, y As S8) As S8 Return New S8() End Operator End Structure Sub Main() Dim x As New S8 Dim y As New S8 If x Then 'BIND1:"x" System.Console.WriteLine("If") Else System.Console.WriteLine("Else") End If If x AndAlso y Then End If End Sub End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New TrueFalseUnaryOperationTestAnalyzer}, Nothing, Nothing, Diagnostic(TrueFalseUnaryOperationTestAnalyzer.UnaryTrueDescriptor.Id, "x").WithLocation(27, 12), Diagnostic(TrueFalseUnaryOperationTestAnalyzer.UnaryTrueDescriptor.Id, "x AndAlso y").WithLocation(33, 12)) End Sub <Fact> Public Sub TestOperationBlockAnalyzer_EmptyMethodBody() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M() End Sub Public Sub M2(i as Integer) End Sub Public Sub M3(Optional i as Integer = 0) End Sub End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New OperationBlockAnalyzer}, Nothing, Nothing, Diagnostic("ID", "M").WithArguments("M", "Block").WithLocation(2, 16), Diagnostic("ID", "M2").WithArguments("M2", "Block").WithLocation(5, 16), Diagnostic("ID", "M3").WithArguments("M3", "ParameterInitializer").WithLocation(8, 16), Diagnostic("ID", "M3").WithArguments("M3", "Block").WithLocation(8, 16)) End Sub End Class End Namespace
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/Common/EmbeddedSyntaxTree.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.EmbeddedLanguages.VirtualChars; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.Common { internal abstract class EmbeddedSyntaxTree<TSyntaxKind, TSyntaxNode, TCompilationUnitSyntax> where TSyntaxKind : struct where TSyntaxNode : EmbeddedSyntaxNode<TSyntaxKind, TSyntaxNode> where TCompilationUnitSyntax : TSyntaxNode { public readonly VirtualCharSequence Text; public readonly TCompilationUnitSyntax Root; public readonly ImmutableArray<EmbeddedDiagnostic> Diagnostics; protected EmbeddedSyntaxTree( VirtualCharSequence text, TCompilationUnitSyntax root, ImmutableArray<EmbeddedDiagnostic> diagnostics) { Text = text; Root = root; Diagnostics = diagnostics; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.EmbeddedLanguages.VirtualChars; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.Common { internal abstract class EmbeddedSyntaxTree<TSyntaxKind, TSyntaxNode, TCompilationUnitSyntax> where TSyntaxKind : struct where TSyntaxNode : EmbeddedSyntaxNode<TSyntaxKind, TSyntaxNode> where TCompilationUnitSyntax : TSyntaxNode { public readonly VirtualCharSequence Text; public readonly TCompilationUnitSyntax Root; public readonly ImmutableArray<EmbeddedDiagnostic> Diagnostics; protected EmbeddedSyntaxTree( VirtualCharSequence text, TCompilationUnitSyntax root, ImmutableArray<EmbeddedDiagnostic> diagnostics) { Text = text; Root = root; Diagnostics = diagnostics; } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/EditorFeatures/CSharpTest/CodeRefactorings/UseExplicitOrImplicitType/UseExplicitTypeRefactoringTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeRefactorings.UseExplicitType; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.UseExplicitOrImplicitType { [Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public class UseExplicitTypeRefactoringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseExplicitTypeCodeRefactoringProvider(); [Fact] public async Task TestIntLocalDeclaration() { var code = @" class C { static void Main() { var[||] i = 0; } }"; var expected = @" class C { static void Main() { int i = 0; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestForeachInsideLocalDeclaration() { var code = @" class C { static void Main() { System.Action notThisLocal = () => { foreach (var[||] i in new int[0]) { } }; } }"; var expected = @" class C { static void Main() { System.Action notThisLocal = () => { foreach (int[||] i in new int[0]) { } }; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestInVarPattern() { var code = @" class C { static void Main() { _ = 0 is var[||] i; } }"; await TestMissingInRegularAndScriptAsync(code); } [Fact] public async Task TestIntLocalDeclaration_Multiple() { var code = @" class C { static void Main() { var[||] i = 0, j = j; } }"; await TestMissingInRegularAndScriptAsync(code); } [Fact] public async Task TestIntLocalDeclaration_NoInitializer() { var code = @" class C { static void Main() { var[||] i; } }"; await TestMissingInRegularAndScriptAsync(code); } [Fact] public async Task TestIntForLoop() { var code = @" class C { static void Main() { for (var[||] i = 0;;) { } } }"; var expected = @" class C { static void Main() { for (int i = 0;;) { } } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestInDispose() { var code = @" class C : System.IDisposable { static void Main() { using (var[||] c = new C()) { } } }"; var expected = @" class C : System.IDisposable { static void Main() { using (C c = new C()) { } } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestTypelessVarLocalDeclaration() { var code = @" class var { static void Main() { var[||] i = null; } }"; await TestMissingInRegularAndScriptAsync(code); } [Fact] public async Task TestIntForeachLoop() { var code = @" class C { static void Main() { foreach (var[||] i in new[] { 0 }) { } } }"; var expected = @" class C { static void Main() { foreach (int i in new[] { 0 }) { } } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestIntDeconstruction() { var code = @" class C { static void Main() { var[||] (i, j) = (0, 1); } }"; var expected = @" class C { static void Main() { (int i, int j) = (0, 1); } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestIntDeconstruction2() { var code = @" class C { static void Main() { (var[||] i, var j) = (0, 1); } }"; var expected = @" class C { static void Main() { (int i, var j) = (0, 1); } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestWithAnonymousType() { var code = @" class C { static void Main() { [|var|] x = new { Amount = 108, Message = ""Hello"" }; } }"; await TestMissingInRegularAndScriptAsync(code); } [Fact, WorkItem(26923, "https://github.com/dotnet/roslyn/issues/26923")] public async Task NoSuggestionOnForeachCollectionExpression() { var code = @"using System; using System.Collections.Generic; class Program { void Method(List<int> var) { foreach (int value in [|var|]) { Console.WriteLine(value.Value); } } }"; // We never want to get offered here under any circumstances. await TestMissingInRegularAndScriptAsync(code); } [Fact] public async Task NotOnConstVar() { // This error case is handled by a separate code fix (UseExplicitTypeForConst). await TestMissingInRegularAndScriptAsync( @"class C { void M() { const [||]var v = 0; } }"); } [Fact] public async Task TestWithTopLevelNullability() { var code = @" #nullable enable class C { private static string? s_data; static void Main() { var[||] v = s_data; } }"; var expected = @" #nullable enable class C { private static string? s_data; static void Main() { string? v = s_data; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestWithTopLevelAndNestedArrayNullability1() { var code = @" #nullable enable class C { private static string?[]?[,]? s_data; static void Main() { var[||] v = s_data; } }"; var expected = @" #nullable enable class C { private static string?[]?[,]? s_data; static void Main() { string?[]?[,]? v = s_data; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestWithTopLevelAndNestedArrayNullability2() { var code = @" #nullable enable class C { private static string?[][,]? s_data; static void Main() { var[||] v = s_data; } }"; var expected = @" #nullable enable class C { private static string?[][,]? s_data; static void Main() { string?[][,]? v = s_data; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestWithTopLevelAndNestedArrayNullability3() { var code = @" #nullable enable class C { private static string?[]?[,][,,]? s_data; static void Main() { var[||] v = s_data; } }"; var expected = @" #nullable enable class C { private static string?[]?[,][,,]? s_data; static void Main() { string?[]?[,][,,]? v = s_data; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact, WorkItem(42880, "https://github.com/dotnet/roslyn/issues/42880")] public async Task TestRefLocal1() { var code = @" class C { static void Main() { string str = """"; [||]ref var rStr1 = ref str; } }"; await TestMissingAsync(code); } [Fact, WorkItem(42880, "https://github.com/dotnet/roslyn/issues/42880")] public async Task TestRefLocal2() { var code = @" class C { static void Main() { string str = """"; ref [||]var rStr1 = ref str; } }"; var expected = @" class C { static void Main() { string str = """"; ref string rStr1 = ref str; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact, WorkItem(42880, "https://github.com/dotnet/roslyn/issues/42880")] public async Task TestRefLocal3() { var code = @" class C { static void Main() { string str = """"; ref var [||]rStr1 = ref str; } }"; var expected = @" class C { static void Main() { string str = """"; ref string rStr1 = ref str; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact, WorkItem(42880, "https://github.com/dotnet/roslyn/issues/42880")] public async Task TestRefReadonlyLocal1() { var code = @" class C { static void Main() { string str = """"; ref readonly [||]var rStr1 = ref str; } }"; var expected = @" class C { static void Main() { string str = """"; ref readonly string rStr1 = ref str; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact, WorkItem(42880, "https://github.com/dotnet/roslyn/issues/42880")] public async Task TestRefReadonlyLocal2() { var code = @" class C { static void Main() { string str = """"; ref readonly var[||] rStr1 = ref str; } }"; var expected = @" class C { static void Main() { string str = """"; ref readonly string rStr1 = ref str; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } private async Task TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(string initialMarkup, string expectedMarkup) { // Enabled because the diagnostic is disabled await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferExplicitTypeWithNone()); // Enabled because the diagnostic is checking for the other direction await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferImplicitTypeWithNone()); await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferImplicitTypeWithSilent()); await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferImplicitTypeWithInfo()); // Disabled because the diagnostic will report it instead await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithSilent())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithInfo())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithWarning())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithError())); // Currently this refactoring is still enabled in cases where it would cause a warning or error await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferImplicitTypeWithWarning()); await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferImplicitTypeWithError()); } private async Task TestMissingInRegularAndScriptAsync(string initialMarkup) { await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithNone())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithNone())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithSilent())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithSilent())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithInfo())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithInfo())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithWarning())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithWarning())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithError())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithError())); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeRefactorings.UseExplicitType; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.UseExplicitOrImplicitType { [Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)] public class UseExplicitTypeRefactoringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseExplicitTypeCodeRefactoringProvider(); [Fact] public async Task TestIntLocalDeclaration() { var code = @" class C { static void Main() { var[||] i = 0; } }"; var expected = @" class C { static void Main() { int i = 0; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestForeachInsideLocalDeclaration() { var code = @" class C { static void Main() { System.Action notThisLocal = () => { foreach (var[||] i in new int[0]) { } }; } }"; var expected = @" class C { static void Main() { System.Action notThisLocal = () => { foreach (int[||] i in new int[0]) { } }; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestInVarPattern() { var code = @" class C { static void Main() { _ = 0 is var[||] i; } }"; await TestMissingInRegularAndScriptAsync(code); } [Fact] public async Task TestIntLocalDeclaration_Multiple() { var code = @" class C { static void Main() { var[||] i = 0, j = j; } }"; await TestMissingInRegularAndScriptAsync(code); } [Fact] public async Task TestIntLocalDeclaration_NoInitializer() { var code = @" class C { static void Main() { var[||] i; } }"; await TestMissingInRegularAndScriptAsync(code); } [Fact] public async Task TestIntForLoop() { var code = @" class C { static void Main() { for (var[||] i = 0;;) { } } }"; var expected = @" class C { static void Main() { for (int i = 0;;) { } } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestInDispose() { var code = @" class C : System.IDisposable { static void Main() { using (var[||] c = new C()) { } } }"; var expected = @" class C : System.IDisposable { static void Main() { using (C c = new C()) { } } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestTypelessVarLocalDeclaration() { var code = @" class var { static void Main() { var[||] i = null; } }"; await TestMissingInRegularAndScriptAsync(code); } [Fact] public async Task TestIntForeachLoop() { var code = @" class C { static void Main() { foreach (var[||] i in new[] { 0 }) { } } }"; var expected = @" class C { static void Main() { foreach (int i in new[] { 0 }) { } } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestIntDeconstruction() { var code = @" class C { static void Main() { var[||] (i, j) = (0, 1); } }"; var expected = @" class C { static void Main() { (int i, int j) = (0, 1); } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestIntDeconstruction2() { var code = @" class C { static void Main() { (var[||] i, var j) = (0, 1); } }"; var expected = @" class C { static void Main() { (int i, var j) = (0, 1); } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestWithAnonymousType() { var code = @" class C { static void Main() { [|var|] x = new { Amount = 108, Message = ""Hello"" }; } }"; await TestMissingInRegularAndScriptAsync(code); } [Fact, WorkItem(26923, "https://github.com/dotnet/roslyn/issues/26923")] public async Task NoSuggestionOnForeachCollectionExpression() { var code = @"using System; using System.Collections.Generic; class Program { void Method(List<int> var) { foreach (int value in [|var|]) { Console.WriteLine(value.Value); } } }"; // We never want to get offered here under any circumstances. await TestMissingInRegularAndScriptAsync(code); } [Fact] public async Task NotOnConstVar() { // This error case is handled by a separate code fix (UseExplicitTypeForConst). await TestMissingInRegularAndScriptAsync( @"class C { void M() { const [||]var v = 0; } }"); } [Fact] public async Task TestWithTopLevelNullability() { var code = @" #nullable enable class C { private static string? s_data; static void Main() { var[||] v = s_data; } }"; var expected = @" #nullable enable class C { private static string? s_data; static void Main() { string? v = s_data; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestWithTopLevelAndNestedArrayNullability1() { var code = @" #nullable enable class C { private static string?[]?[,]? s_data; static void Main() { var[||] v = s_data; } }"; var expected = @" #nullable enable class C { private static string?[]?[,]? s_data; static void Main() { string?[]?[,]? v = s_data; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestWithTopLevelAndNestedArrayNullability2() { var code = @" #nullable enable class C { private static string?[][,]? s_data; static void Main() { var[||] v = s_data; } }"; var expected = @" #nullable enable class C { private static string?[][,]? s_data; static void Main() { string?[][,]? v = s_data; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact] public async Task TestWithTopLevelAndNestedArrayNullability3() { var code = @" #nullable enable class C { private static string?[]?[,][,,]? s_data; static void Main() { var[||] v = s_data; } }"; var expected = @" #nullable enable class C { private static string?[]?[,][,,]? s_data; static void Main() { string?[]?[,][,,]? v = s_data; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact, WorkItem(42880, "https://github.com/dotnet/roslyn/issues/42880")] public async Task TestRefLocal1() { var code = @" class C { static void Main() { string str = """"; [||]ref var rStr1 = ref str; } }"; await TestMissingAsync(code); } [Fact, WorkItem(42880, "https://github.com/dotnet/roslyn/issues/42880")] public async Task TestRefLocal2() { var code = @" class C { static void Main() { string str = """"; ref [||]var rStr1 = ref str; } }"; var expected = @" class C { static void Main() { string str = """"; ref string rStr1 = ref str; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact, WorkItem(42880, "https://github.com/dotnet/roslyn/issues/42880")] public async Task TestRefLocal3() { var code = @" class C { static void Main() { string str = """"; ref var [||]rStr1 = ref str; } }"; var expected = @" class C { static void Main() { string str = """"; ref string rStr1 = ref str; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact, WorkItem(42880, "https://github.com/dotnet/roslyn/issues/42880")] public async Task TestRefReadonlyLocal1() { var code = @" class C { static void Main() { string str = """"; ref readonly [||]var rStr1 = ref str; } }"; var expected = @" class C { static void Main() { string str = """"; ref readonly string rStr1 = ref str; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } [Fact, WorkItem(42880, "https://github.com/dotnet/roslyn/issues/42880")] public async Task TestRefReadonlyLocal2() { var code = @" class C { static void Main() { string str = """"; ref readonly var[||] rStr1 = ref str; } }"; var expected = @" class C { static void Main() { string str = """"; ref readonly string rStr1 = ref str; } }"; await TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(code, expected); } private async Task TestInRegularAndScriptWhenDiagnosticNotAppliedAsync(string initialMarkup, string expectedMarkup) { // Enabled because the diagnostic is disabled await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferExplicitTypeWithNone()); // Enabled because the diagnostic is checking for the other direction await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferImplicitTypeWithNone()); await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferImplicitTypeWithSilent()); await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferImplicitTypeWithInfo()); // Disabled because the diagnostic will report it instead await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithSilent())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithInfo())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithWarning())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithError())); // Currently this refactoring is still enabled in cases where it would cause a warning or error await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferImplicitTypeWithWarning()); await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: this.PreferImplicitTypeWithError()); } private async Task TestMissingInRegularAndScriptAsync(string initialMarkup) { await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithNone())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithNone())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithSilent())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithSilent())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithInfo())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithInfo())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithWarning())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithWarning())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferImplicitTypeWithError())); await TestMissingInRegularAndScriptAsync(initialMarkup, parameters: new TestParameters(options: this.PreferExplicitTypeWithError())); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/VirtualChars/VirtualCharSequence.Chunks.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Text; using Microsoft.CodeAnalysis.Text; #if DEBUG using System.Diagnostics; #endif namespace Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars { internal partial struct VirtualCharSequence { /// <summary> /// Abstraction over a contiguous chunk of <see cref="VirtualChar"/>s. This /// is used so we can expose <see cref="VirtualChar"/>s over an <see cref="ImmutableArray{VirtualChar}"/> /// or over a <see cref="string"/>. The latter is especially useful for reducing /// memory usage in common cases of string tokens without escapes. /// </summary> private abstract partial class Chunk { protected Chunk() { } public abstract int Length { get; } public abstract VirtualChar this[int index] { get; } } /// <summary> /// Thin wrapper over an actual <see cref="ImmutableArray{VirtualChar}"/>. /// This will be the common construct we generate when getting the /// <see cref="Chunk"/> for a string token that has escapes in it. /// </summary> private class ImmutableArrayChunk : Chunk { private readonly ImmutableArray<VirtualChar> _array; public ImmutableArrayChunk(ImmutableArray<VirtualChar> array) => _array = array; public override int Length => _array.Length; public override VirtualChar this[int index] => _array[index]; } /// <summary> /// Represents a <see cref="Chunk"/> on top of a normal /// string. This is the common case of the type of the sequence we would /// create for a normal string token without any escapes in it. /// </summary> private class StringChunk : Chunk { private readonly int _firstVirtualCharPosition; /// <summary> /// The underlying string that we're returning virtual chars from. Note: /// this will commonly include things like quote characters. Clients who /// do not want that should then ask for an appropriate <see cref="VirtualCharSequence.GetSubSequence"/> /// back that does not include those characters. /// </summary> private readonly string _underlyingData; public StringChunk(int firstVirtualCharPosition, string data) { _firstVirtualCharPosition = firstVirtualCharPosition; _underlyingData = data; } public override int Length => _underlyingData.Length; public override VirtualChar this[int index] { get { #if DEBUG // We should never have a property paired high/low surrogate in a StringChunk. We are only created // when the string has the same number of chars as there are VirtualChars. if (char.IsHighSurrogate(_underlyingData[index])) { Debug.Assert(index + 1 >= _underlyingData.Length || !char.IsLowSurrogate(_underlyingData[index + 1])); } #endif var span = new TextSpan(_firstVirtualCharPosition + index, length: 1); var ch = _underlyingData[index]; return char.IsSurrogate(ch) ? VirtualChar.Create(ch, span) : VirtualChar.Create(new Rune(ch), span); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Text; using Microsoft.CodeAnalysis.Text; #if DEBUG using System.Diagnostics; #endif namespace Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars { internal partial struct VirtualCharSequence { /// <summary> /// Abstraction over a contiguous chunk of <see cref="VirtualChar"/>s. This /// is used so we can expose <see cref="VirtualChar"/>s over an <see cref="ImmutableArray{VirtualChar}"/> /// or over a <see cref="string"/>. The latter is especially useful for reducing /// memory usage in common cases of string tokens without escapes. /// </summary> private abstract partial class Chunk { protected Chunk() { } public abstract int Length { get; } public abstract VirtualChar this[int index] { get; } } /// <summary> /// Thin wrapper over an actual <see cref="ImmutableArray{VirtualChar}"/>. /// This will be the common construct we generate when getting the /// <see cref="Chunk"/> for a string token that has escapes in it. /// </summary> private class ImmutableArrayChunk : Chunk { private readonly ImmutableArray<VirtualChar> _array; public ImmutableArrayChunk(ImmutableArray<VirtualChar> array) => _array = array; public override int Length => _array.Length; public override VirtualChar this[int index] => _array[index]; } /// <summary> /// Represents a <see cref="Chunk"/> on top of a normal /// string. This is the common case of the type of the sequence we would /// create for a normal string token without any escapes in it. /// </summary> private class StringChunk : Chunk { private readonly int _firstVirtualCharPosition; /// <summary> /// The underlying string that we're returning virtual chars from. Note: /// this will commonly include things like quote characters. Clients who /// do not want that should then ask for an appropriate <see cref="VirtualCharSequence.GetSubSequence"/> /// back that does not include those characters. /// </summary> private readonly string _underlyingData; public StringChunk(int firstVirtualCharPosition, string data) { _firstVirtualCharPosition = firstVirtualCharPosition; _underlyingData = data; } public override int Length => _underlyingData.Length; public override VirtualChar this[int index] { get { #if DEBUG // We should never have a property paired high/low surrogate in a StringChunk. We are only created // when the string has the same number of chars as there are VirtualChars. if (char.IsHighSurrogate(_underlyingData[index])) { Debug.Assert(index + 1 >= _underlyingData.Length || !char.IsLowSurrogate(_underlyingData[index + 1])); } #endif var span = new TextSpan(_firstVirtualCharPosition + index, length: 1); var ch = _underlyingData[index]; return char.IsSurrogate(ch) ? VirtualChar.Create(ch, span) : VirtualChar.Create(new Rune(ch), span); } } } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Features/Core/Portable/InlineMethod/AbstractInlineMethodRefactoringProvider.MethodParametersInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.InlineMethod { internal abstract partial class AbstractInlineMethodRefactoringProvider<TMethodDeclarationSyntax, TStatementSyntax, TExpressionSyntax, TInvocationSyntax> { /// <summary> /// Information about the callee method parameters to compute <see cref="InlineMethodContext"/>. /// </summary> private readonly struct MethodParametersInfo { /// <summary> /// Parameters map to variable declaration argument's name. /// This is only used for C# to support the 'out' variable declaration. For VB it should always be empty. /// Before: /// void Caller() /// { /// Callee(out var x); /// } /// void Callee(out int i) => i = 100; /// /// After: /// void Caller() /// { /// int x = 100; /// } /// void Callee(out int i) => i = 100; /// </summary> public ImmutableArray<(IParameterSymbol parameterSymbol, string name)> ParametersWithVariableDeclarationArgument { get; } /// <summary> /// Operations that represent Parameter has argument but the argument is not identifier or literal. /// For these parameters they are considered to be put into a declaration statement after inlining. /// Note: params array could maps to multiple/zero arguments. /// Example: /// Before: /// void Caller(bool x) /// { /// Callee(Foo(), x ? Foo() : Bar()) /// } /// void Callee(int a, int b) /// { /// DoSomething(a, b); /// } /// After: /// void Caller(bool x) /// { /// int a = Foo(); /// int b = x ? Foo() : Bar(); /// DoSomething(a, b); /// } /// void Callee(int a, int b) /// { /// DoSomething(a, b); /// } /// </summary> public ImmutableArray<(IParameterSymbol parameterSymbol, TExpressionSyntax initExpression)> ParametersToGenerateFreshVariablesFor { get; } /// <summary> /// A dictionary that contains Parameter that should be directly replaced. Key is the parameter and Value is the replacement exprssion /// It includes /// 1. Parameter mapping to literal expression /// 2. Parameter that has default value, and it has no argument. It should be replaced by the default value. /// 3. Parameter mapping to identifier expression /// Before: /// void Caller(int i, int j, bool[] k) /// { /// Callee(i, j, k); /// } /// void Callee(int a, int b, params bool[] c) /// { /// DoSomething(a, b, c); /// } /// After: /// void Caller(int i, int j, bool[] k) /// { /// DoSomething(i, j, k); /// } /// void Callee(int a, int b, params bool[] c) /// { /// DoSomething(a, b, c); /// } /// 4. A special case, the parameter is only read once in the callee method body /// Before: /// void Caller(bool x) /// { /// Callee(Foo(), Bar()) /// } /// void Callee(int a, int b) /// { /// DoSomething(a, b); /// } /// After: /// void Caller(bool x) /// { /// DoSomething(Foo(), Bar()); /// } /// void Callee(int a, int b) /// { /// DoSomething(a, b); /// } /// In this case, parameters 'a' and 'b' should just be replaced by the argument expression. /// Note: this might cause semantics changes. It is by design. /// </summary> public ImmutableDictionary<IParameterSymbol, TExpressionSyntax> ParametersToReplace { get; } /// <summary> /// Indicate should inline expression and variable declaration be merged into one line. /// Example: /// Before: /// void Caller() /// { /// Callee(out var x); /// } /// void Callee(out int i) => i = 100; /// After: /// (Correct version) /// void Caller() /// { /// int x = 100; /// } /// void Callee(out int i) => i = 100; /// (Wrong version) /// void Caller() /// { /// int x; /// x = 100; /// } /// void Callee(out int i) => i = 100; /// </summary> public bool MergeInlineContentAndVariableDeclarationArgument { get; } public MethodParametersInfo( ImmutableArray<(IParameterSymbol parameterSymbol, string name)> parametersWithVariableDeclarationArgument, ImmutableArray<(IParameterSymbol parameterSymbol, TExpressionSyntax initExpression)> parametersToGenerateFreshVariablesFor, ImmutableDictionary<IParameterSymbol, TExpressionSyntax> parametersToReplace, bool mergeInlineContentAndVariableDeclarationArgument) { ParametersWithVariableDeclarationArgument = parametersWithVariableDeclarationArgument; ParametersToGenerateFreshVariablesFor = parametersToGenerateFreshVariablesFor; ParametersToReplace = parametersToReplace; MergeInlineContentAndVariableDeclarationArgument = mergeInlineContentAndVariableDeclarationArgument; } } private async Task<MethodParametersInfo> GetMethodParametersInfoAsync( Document document, TInvocationSyntax calleeInvocationNode, TMethodDeclarationSyntax calleeMethodNode, TStatementSyntax? statementContainingInvocation, TExpressionSyntax rawInlineExpression, IInvocationOperation invocationOperation, CancellationToken cancellationToken) { var callerSemanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var allArgumentOperations = invocationOperation.Arguments; var calleeDocument = document.Project.Solution.GetRequiredDocument(calleeMethodNode.SyntaxTree); var syntaxGenerator = SyntaxGenerator.GetGenerator(document); if (statementContainingInvocation != null) { // 1. Find all the parameter maps to an identifier from caller. After inlining, this identifier would be used to replace the parameter in callee body. // For params array, it should be included here if it is accept an array identifier as argument. // Note: this might change the order of evaluation if the identifiers are property, this is by design because strictly // follow the semantics will cause strange code and this is a refactoring. // Example: // Before: // void Caller(int i, int j, bool[] k) // { // Callee(i, j, k); // } // void Callee(int a, int b, params bool[] c) // { // DoSomething(a, b, c); // } // After: // void Caller(int i, int j, bool[] k) // { // DoSomething(i, j, k); // } // void Callee(int a, int b, params bool[] c) // { // DoSomething(a, b, c); // } var operationsWithIdentifierArgument = allArgumentOperations .WhereAsArray(argument => _syntaxFacts.IsIdentifierName(argument.Value.Syntax) && argument.ArgumentKind == ArgumentKind.Explicit); // 2. Find all the declaration arguments (e.g. out var declaration in C#). // After inlining, an declaration needs to be put before the invocation. And also use the declared identifier to replace the mapping parameter in callee. // Example: // Before: // void Caller() // { // Callee(out var x); // } // void Callee(out int i) => i = 100; // // After: // void Caller() // { // int x; // x = 100; // } // void Callee(out int i) => i = 100; var operationsWithVariableDeclarationArgument = allArgumentOperations .WhereAsArray(argument => _syntaxFacts.IsDeclarationExpression(argument.Value.Syntax) && argument.ArgumentKind == ArgumentKind.Explicit); // 3. Find the literal arguments, and the mapping parameter will be replaced by that literal expression // Example: // Before: // void Caller(int k) // { // Callee(1, k); // } // void Callee(int i, int j) // { // DoSomething(i, k); // } // After: // void Caller(int k) // { // DoSomething(1, k); // } // void Callee(int i, int j) // { // DoSomething(i, j); // } var operationsWithLiteralArgument = allArgumentOperations .WhereAsArray(argument => _syntaxFacts.IsLiteralExpression(argument.Value.Syntax) && argument.ArgumentKind == ArgumentKind.Explicit); // 4. Find the default value parameters. Similarly to 3, they should be replaced by the default value. // Example: // Before: // void Caller(int k) // { // Callee(); // } // void Callee(int i = 1, int j = 2) // { // DoSomething(i, k); // } // After: // void Caller(int k) // { // DoSomething(1, 2); // } // void Callee(int i = 1, int j = 2) // { // DoSomething(i, j); // } var operationsWithDefaultValue = allArgumentOperations .WhereAsArray(argument => argument.ArgumentKind == ArgumentKind.DefaultValue); // 5. All the remaining arguments, which might includes method call and a lot of other expressions. // Generate a declaration in the caller. // Example: // Before: // void Caller(bool x) // { // Callee(Foo(), x ? Foo() : Bar()) // } // void Callee(int a, int b) // { // DoSomething(a, b); // } // After: // void Caller(bool x) // { // int a = Foo(); // int b = x ? Foo() : Bar(); // DoSomething(a, b); // } // void Callee(int a, int b) // { // DoSomething(a, b); // } var operationsToGenerateFreshVariablesFor = allArgumentOperations .RemoveRange(operationsWithIdentifierArgument) .RemoveRange(operationsWithVariableDeclarationArgument) .RemoveRange(operationsWithLiteralArgument) .RemoveRange(operationsWithDefaultValue) .WhereAsArray(argument => argument.Value.Syntax is TExpressionSyntax); // There is a special case that should be treated differently. If the parameter is only read once in the method body. // Then use the argument expression to directly replace it. // void Caller(bool x) // { // Callee(Foo(), Bar()) // } // void Callee(int a, int b) // { // DoSomething(a, b); // } // After: // void Caller(bool x) // { // DoSomething(Foo(), Bar()); // } // void Callee(int a, int b) // { // DoSomething(a, b); // } // Note: this change might change the order of evaluation. Strictly keep the semantics will make the // code becomes strange so it is by design. var operationsReadOnlyOnce = await GetArgumentsReadOnlyOnceAsync( calleeDocument, operationsToGenerateFreshVariablesFor, calleeMethodNode, cancellationToken).ConfigureAwait(false); operationsToGenerateFreshVariablesFor = operationsToGenerateFreshVariablesFor.RemoveRange(operationsReadOnlyOnce); var parametersToGenerateFreshVariablesFor = operationsToGenerateFreshVariablesFor // We excluded arglist callees, so Parameter will always be non null .SelectAsArray(argument => (argument.Parameter!, GenerateArgumentExpression(syntaxGenerator, argument))); var parameterToReplaceMap = operationsWithLiteralArgument .Concat(operationsWithIdentifierArgument) .Concat(operationsReadOnlyOnce) .Concat(operationsWithDefaultValue) .ToImmutableDictionary( // We excluded arglist callees, so Parameter will always be non null keySelector: argument => argument.Parameter!, elementSelector: argument => GenerateArgumentExpression(syntaxGenerator, argument)); // Use array instead of dictionary because using dictionary will make the parameter becomes unordered. // Example: // Before: // void Caller() // { // Callee(out var x, out var y); // } // void Callee(out int i, out int j) => DoSomething(out i, out j); // // After: // void Caller() // { // int y; // int x; // DoSomething(out x, out y); // } // void Callee(out int i, out int j) => DoSomething(out i, out j); // 'y' might becomes the first declaration if using dictionary instead of array. var parametersWithVariableDeclarationArgument = operationsWithVariableDeclarationArgument .Select(argument => ( argument.Parameter, callerSemanticModel.GetSymbolInfo(argument.Value.Syntax, cancellationToken).GetAnySymbol()?.Name)) .Where(parameterAndArgumentName => parameterAndArgumentName.Name != null) .ToImmutableArray(); var mergeInlineContentAndVariableDeclarationArgument = await ShouldMergeInlineContentAndVariableDeclarationArgumentAsync( calleeDocument, calleeInvocationNode, parametersWithVariableDeclarationArgument!, rawInlineExpression, cancellationToken).ConfigureAwait(false); return new MethodParametersInfo( parametersWithVariableDeclarationArgument!, parametersToGenerateFreshVariablesFor, parameterToReplaceMap, mergeInlineContentAndVariableDeclarationArgument); } else { // If the caller is this is invoked in an arrow function, we can't generate declaration // because there is nowhere to insert that. // This such case, just use the argument expression to parameter. // Note: this might also cause semantics changes but is acceptable for a refactoring var parameterToReplaceMap = allArgumentOperations .Where(argument => argument.Value.Syntax is TExpressionSyntax && !_syntaxFacts.IsDeclarationExpression(argument.Value.Syntax)) .ToImmutableDictionary( // We excluded arglist callees, so Parameter will always be non null keySelector: argument => argument.Parameter!, elementSelector: argument => GenerateArgumentExpression(syntaxGenerator, argument)); return new MethodParametersInfo( ImmutableArray<(IParameterSymbol parameterSymbol, string name)>.Empty, ImmutableArray<(IParameterSymbol parameterSymbol, TExpressionSyntax initExpression)>.Empty, parameterToReplaceMap, false); } } /// <summary> /// Check if the parameter is referenced only once, and it is referenced as 'read'. /// Determine a special case for a parameter that should be replaced by the argument instead of generating a declaration /// for it. /// Example: /// Before: /// void Caller(bool x) /// { /// Callee(Foo(), Bar()) /// } /// void Callee(int a, int b) /// { /// DoSomething(a, b); /// } /// After: /// void Caller(bool x) /// { /// DoSomething(Foo(), Bar()); /// } /// void Callee(int a, int b) /// { /// DoSomething(a, b); /// } /// Parameters 'a' and 'b' are used only once in the Callee, and their value are read not write. /// For this case just use the argument to replace the parameter. /// Note: This might cause a semantic change. In the previous example, if it is /// void Caller(bool x) /// { /// Callee(Foo(), Bar()) /// } /// void Callee(int a, int b) /// { /// DoSomething(b, a); /// } /// Then this operation will change the order of evaluation but is acceptable for a refactoring /// </summary> private static async Task<ImmutableArray<IArgumentOperation>> GetArgumentsReadOnlyOnceAsync( Document document, ImmutableArray<IArgumentOperation> arguments, TMethodDeclarationSyntax calleeMethodNode, CancellationToken cancellationToken) { using var _ = ArrayBuilder<IArgumentOperation>.GetInstance(out var builder); foreach (var argument in arguments) { var parameterSymbol = argument.Parameter; Contract.ThrowIfNull(parameterSymbol, "We filtered out varags methods earlier."); var allReferences = await SymbolFinder .FindReferencesAsync(parameterSymbol, document.Project.Solution, ImmutableHashSet<Document>.Empty.Add(document), cancellationToken).ConfigureAwait(false); // Need to check if the node is in CalleeMethodNode, because for this case // void Caller() { Callee(i: 10); } // void Callee(int i) { DoSomething(); } // the 'i' in the caller will be considered as the referenced location var allReferencedLocations = allReferences .SelectMany(@ref => @ref.Locations) .Where(location => !location.IsImplicit && calleeMethodNode.Contains(location.Location.FindNode(getInnermostNodeForTie: true, cancellationToken))) .ToImmutableArray(); if (allReferencedLocations.Length == 1 && allReferencedLocations[0].SymbolUsageInfo.IsReadFrom()) { builder.Add(argument); } } return builder.ToImmutable(); } /// <summary> /// Check if there is only one variable declaration argument and it is used for assignment /// in the method body. In this case, the method body and argument will be merged into one statement. /// For example: /// Before: /// void Caller() /// { /// Callee(out var x); /// } /// void Callee(out int i) => i = 100; /// /// After: /// void Caller() /// { /// int x = 100; /// } /// void Callee(out int i) => i = 100; /// </summary> private async Task<bool> ShouldMergeInlineContentAndVariableDeclarationArgumentAsync( Document calleeDocument, TInvocationSyntax calleInvocationNode, ImmutableArray<(IParameterSymbol parameterSymbol, string name)> parametersWithVariableDeclarationArgument, TExpressionSyntax inlineExpressionNode, CancellationToken cancellationToken) { var semanticModel = await calleeDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); return parametersWithVariableDeclarationArgument.Length == 1 && _syntaxFacts.IsExpressionStatement(calleInvocationNode.Parent) && semanticModel.GetOperation(inlineExpressionNode, cancellationToken) is ISimpleAssignmentOperation simpleAssignmentOperation && simpleAssignmentOperation.Target is IParameterReferenceOperation parameterOperation && parameterOperation.Parameter.Equals(parametersWithVariableDeclarationArgument[0].parameterSymbol); } private TExpressionSyntax GenerateArgumentExpression( SyntaxGenerator syntaxGenerator, IArgumentOperation argumentOperation) { var parameterSymbol = argumentOperation.Parameter; Debug.Assert(parameterSymbol is not null); var argumentExpressionOperation = argumentOperation.Value; if (argumentOperation.ArgumentKind == ArgumentKind.ParamArray && parameterSymbol.Type is IArrayTypeSymbol paramArrayParameter && argumentExpressionOperation is IArrayCreationOperation { Initializer: { } initializer } && argumentOperation.IsImplicit) { // if this argument is a param array & the array creation operation is implicitly generated, // it means it is in this format: // void caller() { Callee(1, 2, 3); } // void Callee(params int[] x) { } // Collect each of these arguments and generate a new array for it. // Note: it could be empty. return (TExpressionSyntax)syntaxGenerator.AddParentheses( syntaxGenerator.ArrayCreationExpression( GenerateTypeSyntax(paramArrayParameter.ElementType, allowVar: false), initializer.ElementValues.SelectAsArray(op => op.Syntax))); } // In all the other cases, one parameter should only maps to one argument. if (argumentOperation.ArgumentKind == ArgumentKind.DefaultValue && parameterSymbol.HasExplicitDefaultValue) { return GenerateLiteralExpression(parameterSymbol.Type, parameterSymbol.ExplicitDefaultValue); } return (TExpressionSyntax)syntaxGenerator.AddParentheses(argumentExpressionOperation.Syntax); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.InlineMethod { internal abstract partial class AbstractInlineMethodRefactoringProvider<TMethodDeclarationSyntax, TStatementSyntax, TExpressionSyntax, TInvocationSyntax> { /// <summary> /// Information about the callee method parameters to compute <see cref="InlineMethodContext"/>. /// </summary> private readonly struct MethodParametersInfo { /// <summary> /// Parameters map to variable declaration argument's name. /// This is only used for C# to support the 'out' variable declaration. For VB it should always be empty. /// Before: /// void Caller() /// { /// Callee(out var x); /// } /// void Callee(out int i) => i = 100; /// /// After: /// void Caller() /// { /// int x = 100; /// } /// void Callee(out int i) => i = 100; /// </summary> public ImmutableArray<(IParameterSymbol parameterSymbol, string name)> ParametersWithVariableDeclarationArgument { get; } /// <summary> /// Operations that represent Parameter has argument but the argument is not identifier or literal. /// For these parameters they are considered to be put into a declaration statement after inlining. /// Note: params array could maps to multiple/zero arguments. /// Example: /// Before: /// void Caller(bool x) /// { /// Callee(Foo(), x ? Foo() : Bar()) /// } /// void Callee(int a, int b) /// { /// DoSomething(a, b); /// } /// After: /// void Caller(bool x) /// { /// int a = Foo(); /// int b = x ? Foo() : Bar(); /// DoSomething(a, b); /// } /// void Callee(int a, int b) /// { /// DoSomething(a, b); /// } /// </summary> public ImmutableArray<(IParameterSymbol parameterSymbol, TExpressionSyntax initExpression)> ParametersToGenerateFreshVariablesFor { get; } /// <summary> /// A dictionary that contains Parameter that should be directly replaced. Key is the parameter and Value is the replacement exprssion /// It includes /// 1. Parameter mapping to literal expression /// 2. Parameter that has default value, and it has no argument. It should be replaced by the default value. /// 3. Parameter mapping to identifier expression /// Before: /// void Caller(int i, int j, bool[] k) /// { /// Callee(i, j, k); /// } /// void Callee(int a, int b, params bool[] c) /// { /// DoSomething(a, b, c); /// } /// After: /// void Caller(int i, int j, bool[] k) /// { /// DoSomething(i, j, k); /// } /// void Callee(int a, int b, params bool[] c) /// { /// DoSomething(a, b, c); /// } /// 4. A special case, the parameter is only read once in the callee method body /// Before: /// void Caller(bool x) /// { /// Callee(Foo(), Bar()) /// } /// void Callee(int a, int b) /// { /// DoSomething(a, b); /// } /// After: /// void Caller(bool x) /// { /// DoSomething(Foo(), Bar()); /// } /// void Callee(int a, int b) /// { /// DoSomething(a, b); /// } /// In this case, parameters 'a' and 'b' should just be replaced by the argument expression. /// Note: this might cause semantics changes. It is by design. /// </summary> public ImmutableDictionary<IParameterSymbol, TExpressionSyntax> ParametersToReplace { get; } /// <summary> /// Indicate should inline expression and variable declaration be merged into one line. /// Example: /// Before: /// void Caller() /// { /// Callee(out var x); /// } /// void Callee(out int i) => i = 100; /// After: /// (Correct version) /// void Caller() /// { /// int x = 100; /// } /// void Callee(out int i) => i = 100; /// (Wrong version) /// void Caller() /// { /// int x; /// x = 100; /// } /// void Callee(out int i) => i = 100; /// </summary> public bool MergeInlineContentAndVariableDeclarationArgument { get; } public MethodParametersInfo( ImmutableArray<(IParameterSymbol parameterSymbol, string name)> parametersWithVariableDeclarationArgument, ImmutableArray<(IParameterSymbol parameterSymbol, TExpressionSyntax initExpression)> parametersToGenerateFreshVariablesFor, ImmutableDictionary<IParameterSymbol, TExpressionSyntax> parametersToReplace, bool mergeInlineContentAndVariableDeclarationArgument) { ParametersWithVariableDeclarationArgument = parametersWithVariableDeclarationArgument; ParametersToGenerateFreshVariablesFor = parametersToGenerateFreshVariablesFor; ParametersToReplace = parametersToReplace; MergeInlineContentAndVariableDeclarationArgument = mergeInlineContentAndVariableDeclarationArgument; } } private async Task<MethodParametersInfo> GetMethodParametersInfoAsync( Document document, TInvocationSyntax calleeInvocationNode, TMethodDeclarationSyntax calleeMethodNode, TStatementSyntax? statementContainingInvocation, TExpressionSyntax rawInlineExpression, IInvocationOperation invocationOperation, CancellationToken cancellationToken) { var callerSemanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var allArgumentOperations = invocationOperation.Arguments; var calleeDocument = document.Project.Solution.GetRequiredDocument(calleeMethodNode.SyntaxTree); var syntaxGenerator = SyntaxGenerator.GetGenerator(document); if (statementContainingInvocation != null) { // 1. Find all the parameter maps to an identifier from caller. After inlining, this identifier would be used to replace the parameter in callee body. // For params array, it should be included here if it is accept an array identifier as argument. // Note: this might change the order of evaluation if the identifiers are property, this is by design because strictly // follow the semantics will cause strange code and this is a refactoring. // Example: // Before: // void Caller(int i, int j, bool[] k) // { // Callee(i, j, k); // } // void Callee(int a, int b, params bool[] c) // { // DoSomething(a, b, c); // } // After: // void Caller(int i, int j, bool[] k) // { // DoSomething(i, j, k); // } // void Callee(int a, int b, params bool[] c) // { // DoSomething(a, b, c); // } var operationsWithIdentifierArgument = allArgumentOperations .WhereAsArray(argument => _syntaxFacts.IsIdentifierName(argument.Value.Syntax) && argument.ArgumentKind == ArgumentKind.Explicit); // 2. Find all the declaration arguments (e.g. out var declaration in C#). // After inlining, an declaration needs to be put before the invocation. And also use the declared identifier to replace the mapping parameter in callee. // Example: // Before: // void Caller() // { // Callee(out var x); // } // void Callee(out int i) => i = 100; // // After: // void Caller() // { // int x; // x = 100; // } // void Callee(out int i) => i = 100; var operationsWithVariableDeclarationArgument = allArgumentOperations .WhereAsArray(argument => _syntaxFacts.IsDeclarationExpression(argument.Value.Syntax) && argument.ArgumentKind == ArgumentKind.Explicit); // 3. Find the literal arguments, and the mapping parameter will be replaced by that literal expression // Example: // Before: // void Caller(int k) // { // Callee(1, k); // } // void Callee(int i, int j) // { // DoSomething(i, k); // } // After: // void Caller(int k) // { // DoSomething(1, k); // } // void Callee(int i, int j) // { // DoSomething(i, j); // } var operationsWithLiteralArgument = allArgumentOperations .WhereAsArray(argument => _syntaxFacts.IsLiteralExpression(argument.Value.Syntax) && argument.ArgumentKind == ArgumentKind.Explicit); // 4. Find the default value parameters. Similarly to 3, they should be replaced by the default value. // Example: // Before: // void Caller(int k) // { // Callee(); // } // void Callee(int i = 1, int j = 2) // { // DoSomething(i, k); // } // After: // void Caller(int k) // { // DoSomething(1, 2); // } // void Callee(int i = 1, int j = 2) // { // DoSomething(i, j); // } var operationsWithDefaultValue = allArgumentOperations .WhereAsArray(argument => argument.ArgumentKind == ArgumentKind.DefaultValue); // 5. All the remaining arguments, which might includes method call and a lot of other expressions. // Generate a declaration in the caller. // Example: // Before: // void Caller(bool x) // { // Callee(Foo(), x ? Foo() : Bar()) // } // void Callee(int a, int b) // { // DoSomething(a, b); // } // After: // void Caller(bool x) // { // int a = Foo(); // int b = x ? Foo() : Bar(); // DoSomething(a, b); // } // void Callee(int a, int b) // { // DoSomething(a, b); // } var operationsToGenerateFreshVariablesFor = allArgumentOperations .RemoveRange(operationsWithIdentifierArgument) .RemoveRange(operationsWithVariableDeclarationArgument) .RemoveRange(operationsWithLiteralArgument) .RemoveRange(operationsWithDefaultValue) .WhereAsArray(argument => argument.Value.Syntax is TExpressionSyntax); // There is a special case that should be treated differently. If the parameter is only read once in the method body. // Then use the argument expression to directly replace it. // void Caller(bool x) // { // Callee(Foo(), Bar()) // } // void Callee(int a, int b) // { // DoSomething(a, b); // } // After: // void Caller(bool x) // { // DoSomething(Foo(), Bar()); // } // void Callee(int a, int b) // { // DoSomething(a, b); // } // Note: this change might change the order of evaluation. Strictly keep the semantics will make the // code becomes strange so it is by design. var operationsReadOnlyOnce = await GetArgumentsReadOnlyOnceAsync( calleeDocument, operationsToGenerateFreshVariablesFor, calleeMethodNode, cancellationToken).ConfigureAwait(false); operationsToGenerateFreshVariablesFor = operationsToGenerateFreshVariablesFor.RemoveRange(operationsReadOnlyOnce); var parametersToGenerateFreshVariablesFor = operationsToGenerateFreshVariablesFor // We excluded arglist callees, so Parameter will always be non null .SelectAsArray(argument => (argument.Parameter!, GenerateArgumentExpression(syntaxGenerator, argument))); var parameterToReplaceMap = operationsWithLiteralArgument .Concat(operationsWithIdentifierArgument) .Concat(operationsReadOnlyOnce) .Concat(operationsWithDefaultValue) .ToImmutableDictionary( // We excluded arglist callees, so Parameter will always be non null keySelector: argument => argument.Parameter!, elementSelector: argument => GenerateArgumentExpression(syntaxGenerator, argument)); // Use array instead of dictionary because using dictionary will make the parameter becomes unordered. // Example: // Before: // void Caller() // { // Callee(out var x, out var y); // } // void Callee(out int i, out int j) => DoSomething(out i, out j); // // After: // void Caller() // { // int y; // int x; // DoSomething(out x, out y); // } // void Callee(out int i, out int j) => DoSomething(out i, out j); // 'y' might becomes the first declaration if using dictionary instead of array. var parametersWithVariableDeclarationArgument = operationsWithVariableDeclarationArgument .Select(argument => ( argument.Parameter, callerSemanticModel.GetSymbolInfo(argument.Value.Syntax, cancellationToken).GetAnySymbol()?.Name)) .Where(parameterAndArgumentName => parameterAndArgumentName.Name != null) .ToImmutableArray(); var mergeInlineContentAndVariableDeclarationArgument = await ShouldMergeInlineContentAndVariableDeclarationArgumentAsync( calleeDocument, calleeInvocationNode, parametersWithVariableDeclarationArgument!, rawInlineExpression, cancellationToken).ConfigureAwait(false); return new MethodParametersInfo( parametersWithVariableDeclarationArgument!, parametersToGenerateFreshVariablesFor, parameterToReplaceMap, mergeInlineContentAndVariableDeclarationArgument); } else { // If the caller is this is invoked in an arrow function, we can't generate declaration // because there is nowhere to insert that. // This such case, just use the argument expression to parameter. // Note: this might also cause semantics changes but is acceptable for a refactoring var parameterToReplaceMap = allArgumentOperations .Where(argument => argument.Value.Syntax is TExpressionSyntax && !_syntaxFacts.IsDeclarationExpression(argument.Value.Syntax)) .ToImmutableDictionary( // We excluded arglist callees, so Parameter will always be non null keySelector: argument => argument.Parameter!, elementSelector: argument => GenerateArgumentExpression(syntaxGenerator, argument)); return new MethodParametersInfo( ImmutableArray<(IParameterSymbol parameterSymbol, string name)>.Empty, ImmutableArray<(IParameterSymbol parameterSymbol, TExpressionSyntax initExpression)>.Empty, parameterToReplaceMap, false); } } /// <summary> /// Check if the parameter is referenced only once, and it is referenced as 'read'. /// Determine a special case for a parameter that should be replaced by the argument instead of generating a declaration /// for it. /// Example: /// Before: /// void Caller(bool x) /// { /// Callee(Foo(), Bar()) /// } /// void Callee(int a, int b) /// { /// DoSomething(a, b); /// } /// After: /// void Caller(bool x) /// { /// DoSomething(Foo(), Bar()); /// } /// void Callee(int a, int b) /// { /// DoSomething(a, b); /// } /// Parameters 'a' and 'b' are used only once in the Callee, and their value are read not write. /// For this case just use the argument to replace the parameter. /// Note: This might cause a semantic change. In the previous example, if it is /// void Caller(bool x) /// { /// Callee(Foo(), Bar()) /// } /// void Callee(int a, int b) /// { /// DoSomething(b, a); /// } /// Then this operation will change the order of evaluation but is acceptable for a refactoring /// </summary> private static async Task<ImmutableArray<IArgumentOperation>> GetArgumentsReadOnlyOnceAsync( Document document, ImmutableArray<IArgumentOperation> arguments, TMethodDeclarationSyntax calleeMethodNode, CancellationToken cancellationToken) { using var _ = ArrayBuilder<IArgumentOperation>.GetInstance(out var builder); foreach (var argument in arguments) { var parameterSymbol = argument.Parameter; Contract.ThrowIfNull(parameterSymbol, "We filtered out varags methods earlier."); var allReferences = await SymbolFinder .FindReferencesAsync(parameterSymbol, document.Project.Solution, ImmutableHashSet<Document>.Empty.Add(document), cancellationToken).ConfigureAwait(false); // Need to check if the node is in CalleeMethodNode, because for this case // void Caller() { Callee(i: 10); } // void Callee(int i) { DoSomething(); } // the 'i' in the caller will be considered as the referenced location var allReferencedLocations = allReferences .SelectMany(@ref => @ref.Locations) .Where(location => !location.IsImplicit && calleeMethodNode.Contains(location.Location.FindNode(getInnermostNodeForTie: true, cancellationToken))) .ToImmutableArray(); if (allReferencedLocations.Length == 1 && allReferencedLocations[0].SymbolUsageInfo.IsReadFrom()) { builder.Add(argument); } } return builder.ToImmutable(); } /// <summary> /// Check if there is only one variable declaration argument and it is used for assignment /// in the method body. In this case, the method body and argument will be merged into one statement. /// For example: /// Before: /// void Caller() /// { /// Callee(out var x); /// } /// void Callee(out int i) => i = 100; /// /// After: /// void Caller() /// { /// int x = 100; /// } /// void Callee(out int i) => i = 100; /// </summary> private async Task<bool> ShouldMergeInlineContentAndVariableDeclarationArgumentAsync( Document calleeDocument, TInvocationSyntax calleInvocationNode, ImmutableArray<(IParameterSymbol parameterSymbol, string name)> parametersWithVariableDeclarationArgument, TExpressionSyntax inlineExpressionNode, CancellationToken cancellationToken) { var semanticModel = await calleeDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); return parametersWithVariableDeclarationArgument.Length == 1 && _syntaxFacts.IsExpressionStatement(calleInvocationNode.Parent) && semanticModel.GetOperation(inlineExpressionNode, cancellationToken) is ISimpleAssignmentOperation simpleAssignmentOperation && simpleAssignmentOperation.Target is IParameterReferenceOperation parameterOperation && parameterOperation.Parameter.Equals(parametersWithVariableDeclarationArgument[0].parameterSymbol); } private TExpressionSyntax GenerateArgumentExpression( SyntaxGenerator syntaxGenerator, IArgumentOperation argumentOperation) { var parameterSymbol = argumentOperation.Parameter; Debug.Assert(parameterSymbol is not null); var argumentExpressionOperation = argumentOperation.Value; if (argumentOperation.ArgumentKind == ArgumentKind.ParamArray && parameterSymbol.Type is IArrayTypeSymbol paramArrayParameter && argumentExpressionOperation is IArrayCreationOperation { Initializer: { } initializer } && argumentOperation.IsImplicit) { // if this argument is a param array & the array creation operation is implicitly generated, // it means it is in this format: // void caller() { Callee(1, 2, 3); } // void Callee(params int[] x) { } // Collect each of these arguments and generate a new array for it. // Note: it could be empty. return (TExpressionSyntax)syntaxGenerator.AddParentheses( syntaxGenerator.ArrayCreationExpression( GenerateTypeSyntax(paramArrayParameter.ElementType, allowVar: false), initializer.ElementValues.SelectAsArray(op => op.Syntax))); } // In all the other cases, one parameter should only maps to one argument. if (argumentOperation.ArgumentKind == ArgumentKind.DefaultValue && parameterSymbol.HasExplicitDefaultValue) { return GenerateLiteralExpression(parameterSymbol.Type, parameterSymbol.ExplicitDefaultValue); } return (TExpressionSyntax)syntaxGenerator.AddParentheses(argumentExpressionOperation.Syntax); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/Core/Portable/InternalUtilities/ArrayExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Roslyn.Utilities { internal static class ArrayExtensions { internal static T[] Copy<T>(this T[] array, int start, int length) { // It's ok for 'start' to equal 'array.Length'. In that case you'll // just get an empty array back. Debug.Assert(start >= 0); Debug.Assert(start <= array.Length); if (start + length > array.Length) { length = array.Length - start; } T[] newArray = new T[length]; Array.Copy(array, start, newArray, 0, length); return newArray; } internal static T[] InsertAt<T>(this T[] array, int position, T item) { T[] newArray = new T[array.Length + 1]; if (position > 0) { Array.Copy(array, newArray, position); } if (position < array.Length) { Array.Copy(array, position, newArray, position + 1, array.Length - position); } newArray[position] = item; return newArray; } internal static T[] Append<T>(this T[] array, T item) { return InsertAt(array, array.Length, item); } internal static T[] InsertAt<T>(this T[] array, int position, T[] items) { T[] newArray = new T[array.Length + items.Length]; if (position > 0) { Array.Copy(array, newArray, position); } if (position < array.Length) { Array.Copy(array, position, newArray, position + items.Length, array.Length - position); } items.CopyTo(newArray, position); return newArray; } internal static T[] Append<T>(this T[] array, T[] items) { return InsertAt(array, array.Length, items); } internal static T[] RemoveAt<T>(this T[] array, int position) { return RemoveAt(array, position, 1); } internal static T[] RemoveAt<T>(this T[] array, int position, int length) { if (position + length > array.Length) { length = array.Length - position; } T[] newArray = new T[array.Length - length]; if (position > 0) { Array.Copy(array, newArray, position); } if (position < newArray.Length) { Array.Copy(array, position + length, newArray, position, newArray.Length - position); } return newArray; } internal static T[] ReplaceAt<T>(this T[] array, int position, T item) { T[] newArray = new T[array.Length]; Array.Copy(array, newArray, array.Length); newArray[position] = item; return newArray; } internal static T[] ReplaceAt<T>(this T[] array, int position, int length, T[] items) { return InsertAt(RemoveAt(array, position, length), position, items); } internal static void ReverseContents<T>(this T[] array) { ReverseContents(array, 0, array.Length); } internal static void ReverseContents<T>(this T[] array, int start, int count) { int end = start + count - 1; for (int i = start, j = end; i < j; i++, j--) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } // same as Array.BinarySearch, but without using IComparer to compare ints internal static int BinarySearch(this int[] array, int value) { var low = 0; var high = array.Length - 1; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; if (midValue == value) { return middle; } else if (midValue > value) { high = middle - 1; } else { low = middle + 1; } } return ~low; } /// <summary> /// Search a sorted integer array for the target value in O(log N) time. /// </summary> /// <param name="array">The array of integers which must be sorted in ascending order.</param> /// <param name="value">The target value.</param> /// <returns>An index in the array pointing to the position where <paramref name="value"/> should be /// inserted in order to maintain the sorted order. All values to the right of this position will be /// strictly greater than <paramref name="value"/>. Note that this may return a position off the end /// of the array if all elements are less than or equal to <paramref name="value"/>.</returns> internal static int BinarySearchUpperBound(this int[] array, int value) { int low = 0; int high = array.Length - 1; while (low <= high) { int middle = low + ((high - low) >> 1); if (array[middle] > value) { high = middle - 1; } else { low = middle + 1; } } return low; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace Roslyn.Utilities { internal static class ArrayExtensions { internal static T[] Copy<T>(this T[] array, int start, int length) { // It's ok for 'start' to equal 'array.Length'. In that case you'll // just get an empty array back. Debug.Assert(start >= 0); Debug.Assert(start <= array.Length); if (start + length > array.Length) { length = array.Length - start; } T[] newArray = new T[length]; Array.Copy(array, start, newArray, 0, length); return newArray; } internal static T[] InsertAt<T>(this T[] array, int position, T item) { T[] newArray = new T[array.Length + 1]; if (position > 0) { Array.Copy(array, newArray, position); } if (position < array.Length) { Array.Copy(array, position, newArray, position + 1, array.Length - position); } newArray[position] = item; return newArray; } internal static T[] Append<T>(this T[] array, T item) { return InsertAt(array, array.Length, item); } internal static T[] InsertAt<T>(this T[] array, int position, T[] items) { T[] newArray = new T[array.Length + items.Length]; if (position > 0) { Array.Copy(array, newArray, position); } if (position < array.Length) { Array.Copy(array, position, newArray, position + items.Length, array.Length - position); } items.CopyTo(newArray, position); return newArray; } internal static T[] Append<T>(this T[] array, T[] items) { return InsertAt(array, array.Length, items); } internal static T[] RemoveAt<T>(this T[] array, int position) { return RemoveAt(array, position, 1); } internal static T[] RemoveAt<T>(this T[] array, int position, int length) { if (position + length > array.Length) { length = array.Length - position; } T[] newArray = new T[array.Length - length]; if (position > 0) { Array.Copy(array, newArray, position); } if (position < newArray.Length) { Array.Copy(array, position + length, newArray, position, newArray.Length - position); } return newArray; } internal static T[] ReplaceAt<T>(this T[] array, int position, T item) { T[] newArray = new T[array.Length]; Array.Copy(array, newArray, array.Length); newArray[position] = item; return newArray; } internal static T[] ReplaceAt<T>(this T[] array, int position, int length, T[] items) { return InsertAt(RemoveAt(array, position, length), position, items); } internal static void ReverseContents<T>(this T[] array) { ReverseContents(array, 0, array.Length); } internal static void ReverseContents<T>(this T[] array, int start, int count) { int end = start + count - 1; for (int i = start, j = end; i < j; i++, j--) { T tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } // same as Array.BinarySearch, but without using IComparer to compare ints internal static int BinarySearch(this int[] array, int value) { var low = 0; var high = array.Length - 1; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; if (midValue == value) { return middle; } else if (midValue > value) { high = middle - 1; } else { low = middle + 1; } } return ~low; } /// <summary> /// Search a sorted integer array for the target value in O(log N) time. /// </summary> /// <param name="array">The array of integers which must be sorted in ascending order.</param> /// <param name="value">The target value.</param> /// <returns>An index in the array pointing to the position where <paramref name="value"/> should be /// inserted in order to maintain the sorted order. All values to the right of this position will be /// strictly greater than <paramref name="value"/>. Note that this may return a position off the end /// of the array if all elements are less than or equal to <paramref name="value"/>.</returns> internal static int BinarySearchUpperBound(this int[] array, int value) { int low = 0; int high = array.Length - 1; while (low <= high) { int middle = low + ((high - low) >> 1); if (array[middle] > value) { high = middle - 1; } else { low = middle + 1; } } return low; } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/EditorFeatures/VisualBasicTest/EndConstructGeneration/EndConstructTestingHelpers.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Shared.Options Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration Imports Microsoft.VisualStudio.Composition Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Microsoft.VisualStudio.Text.Operations Imports Moq Imports Roslyn.Test.EditorUtilities Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration Friend Module EndConstructTestingHelpers Private Function CreateMockIndentationService() As ISmartIndentationService Dim mock As New Mock(Of ISmartIndentationService)(MockBehavior.Strict) mock.Setup(Function(service) service.GetDesiredIndentation(It.IsAny(Of ITextView), It.IsAny(Of ITextSnapshotLine))).Returns(0) Return mock.Object End Function Private Sub DisableLineCommit(workspace As Workspace) workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(FeatureOnOffOptions.PrettyListing, LanguageNames.VisualBasic, False))) End Sub Private Sub VerifyTypedCharApplied(doFunc As Func(Of VisualBasicEndConstructService, ITextView, ITextBuffer, Boolean), before As String, after As String, typedChar As Char, endCaretPos As Integer()) Dim caretPos = before.IndexOf("$$", StringComparison.Ordinal) Dim beforeText = before.Replace("$$", "") Using workspace = TestWorkspace.CreateVisualBasic(beforeText, composition:=EditorTestCompositions.EditorFeatures) DisableLineCommit(workspace) Dim view = workspace.Documents.First().GetTextView() view.Caret.MoveTo(New SnapshotPoint(view.TextSnapshot, caretPos)) Dim endConstructService As New VisualBasicEndConstructService( CreateMockIndentationService(), workspace.GetService(Of ITextUndoHistoryRegistry), workspace.GetService(Of IEditorOperationsFactoryService), workspace.GetService(Of IEditorOptionsFactoryService)) view.TextBuffer.Replace(New Span(caretPos, 0), typedChar.ToString()) Assert.True(doFunc(endConstructService, view, view.TextBuffer)) Assert.Equal(after, view.TextSnapshot.GetText()) Dim actualLine As Integer Dim actualChar As Integer view.Caret.Position.BufferPosition.GetLineAndCharacter(actualLine, actualChar) Assert.Equal(endCaretPos(0), actualLine) Assert.Equal(endCaretPos(1), actualChar) End Using End Sub Private Sub VerifyApplied(doFunc As Func(Of VisualBasicEndConstructService, ITextView, ITextBuffer, Boolean), before As String, beforeCaret As Integer(), after As String, afterCaret As Integer()) Using workspace = TestWorkspace.CreateVisualBasic(before, composition:=EditorTestCompositions.EditorFeatures) DisableLineCommit(workspace) Dim textView = workspace.Documents.First().GetTextView() Dim subjectBuffer = workspace.Documents.First().GetTextBuffer() textView.TryMoveCaretToAndEnsureVisible(GetSnapshotPointFromArray(textView, beforeCaret, beforeCaret.Length - 2)) If beforeCaret.Length = 4 Then Dim span = New SnapshotSpan( GetSnapshotPointFromArray(textView, beforeCaret, 0), GetSnapshotPointFromArray(textView, beforeCaret, 2)) textView.SetSelection(span) End If Dim endConstructService As New VisualBasicEndConstructService( CreateMockIndentationService(), workspace.GetService(Of ITextUndoHistoryRegistry), workspace.GetService(Of IEditorOperationsFactoryService), workspace.GetService(Of IEditorOptionsFactoryService)) Assert.True(doFunc(endConstructService, textView, textView.TextSnapshot.TextBuffer)) Assert.Equal(EditorFactory.LinesToFullText(after), textView.TextSnapshot.GetText()) Dim afterLine = textView.TextSnapshot.GetLineFromLineNumber(afterCaret(0)) Dim afterCaretPoint As SnapshotPoint If afterCaret(1) = -1 Then afterCaretPoint = afterLine.End Else afterCaretPoint = New SnapshotPoint(textView.TextSnapshot, afterLine.Start + afterCaret(1)) End If Assert.Equal(Of Integer)(afterCaretPoint, textView.GetCaretPoint(subjectBuffer).Value.Position) End Using End Sub Private Function GetSnapshotPointFromArray(view As ITextView, caret As Integer(), startIndex As Integer) As SnapshotPoint Dim line = view.TextSnapshot.GetLineFromLineNumber(caret(startIndex)) If caret(startIndex + 1) = -1 Then Return line.End Else Return line.Start + caret(startIndex + 1) End If End Function Private Sub VerifyNotApplied(doFunc As Func(Of VisualBasicEndConstructService, ITextView, ITextBuffer, Boolean), text As String, caret As Integer()) Using workspace = TestWorkspace.CreateVisualBasic(text) Dim textView = workspace.Documents.First().GetTextView() Dim subjectBuffer = workspace.Documents.First().GetTextBuffer() Dim line = textView.TextSnapshot.GetLineFromLineNumber(caret(0)) Dim caretPosition As SnapshotPoint If caret(1) = -1 Then caretPosition = line.End Else caretPosition = New SnapshotPoint(textView.TextSnapshot, line.Start + caret(1)) End If textView.TryMoveCaretToAndEnsureVisible(caretPosition) Dim endConstructService As New VisualBasicEndConstructService( CreateMockIndentationService(), workspace.GetService(Of ITextUndoHistoryRegistry), workspace.GetService(Of IEditorOperationsFactoryService), workspace.GetService(Of IEditorOptionsFactoryService)) Assert.False(doFunc(endConstructService, textView, textView.TextSnapshot.TextBuffer), "End Construct should not have generated anything.") ' The text should not have changed Assert.Equal(EditorFactory.LinesToFullText(text), textView.TextSnapshot.GetText()) ' The caret should not have moved Assert.Equal(Of Integer)(caretPosition, textView.GetCaretPoint(subjectBuffer).Value.Position) End Using End Sub Public Sub VerifyStatementEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer()) VerifyApplied(Function(s, v, b) s.TryDoEndConstructForEnterKey(v, b, CancellationToken.None), before, beforeCaret, after, afterCaret) End Sub Public Sub VerifyStatementEndConstructNotApplied(text As String, caret As Integer()) VerifyNotApplied(Function(s, v, b) s.TryDoEndConstructForEnterKey(v, b, CancellationToken.None), text, caret) End Sub Public Sub VerifyXmlElementEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer()) VerifyApplied(Function(s, v, b) s.TryDoXmlElementEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret) End Sub Public Sub VerifyXmlElementEndConstructNotApplied(text As String, caret As Integer()) VerifyNotApplied(Function(s, v, b) s.TryDoXmlElementEndConstruct(v, b, Nothing), text, caret) End Sub Public Sub VerifyXmlCommentEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer()) VerifyApplied(Function(s, v, b) s.TryDoXmlCommentEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret) End Sub Public Sub VerifyXmlCommentEndConstructNotApplied(text As String, caret As Integer()) VerifyNotApplied(Function(s, v, b) s.TryDoXmlCommentEndConstruct(v, b, Nothing), text, caret) End Sub Public Sub VerifyXmlCDataEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer()) VerifyApplied(Function(s, v, b) s.TryDoXmlCDataEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret) End Sub Public Sub VerifyXmlCDataEndConstructNotApplied(text As String, caret As Integer()) VerifyNotApplied(Function(s, v, b) s.TryDoXmlCDataEndConstruct(v, b, Nothing), text, caret) End Sub Public Sub VerifyXmlEmbeddedExpressionEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer()) VerifyApplied(Function(s, v, b) s.TryDoXmlEmbeddedExpressionEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret) End Sub Public Sub VerifyXmlEmbeddedExpressionEndConstructNotApplied(text As String, caret As Integer()) VerifyNotApplied(Function(s, v, b) s.TryDoXmlEmbeddedExpressionEndConstruct(v, b, Nothing), text, caret) End Sub Public Sub VerifyXmlProcessingInstructionEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer()) VerifyApplied(Function(s, v, b) s.TryDoXmlProcessingInstructionEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret) End Sub Public Sub VerifyXmlProcessingInstructionNotApplied(text As String, caret As Integer()) VerifyNotApplied(Function(s, v, b) s.TryDoXmlProcessingInstructionEndConstruct(v, b, Nothing), text, caret) End Sub Public Sub VerifyEndConstructAppliedAfterChar(before As String, after As String, typedChar As Char, endCaretPos As Integer()) VerifyTypedCharApplied(Function(s, v, b) s.TryDo(v, b, typedChar, Nothing), before, after, typedChar, endCaretPos) End Sub Public Sub VerifyEndConstructNotAppliedAfterChar(before As String, after As String, typedChar As Char, endCaretPos As Integer()) VerifyTypedCharApplied(Function(s, v, b) Not s.TryDo(v, b, typedChar, Nothing), before, after, typedChar, endCaretPos) End Sub Public Sub VerifyAppliedAfterReturnUsingCommandHandler( before As String, beforeCaret As Integer(), after As String, afterCaret As Integer()) ' create separate composition Using workspace = TestWorkspace.CreateVisualBasic(before, composition:=EditorTestCompositions.EditorFeatures) DisableLineCommit(workspace) Dim view = workspace.Documents.First().GetTextView() Dim line = view.TextSnapshot.GetLineFromLineNumber(beforeCaret(0)) If beforeCaret(1) = -1 Then view.Caret.MoveTo(line.End) Else view.Caret.MoveTo(New SnapshotPoint(view.TextSnapshot, line.Start + beforeCaret(1))) End If Dim factory = workspace.ExportProvider.GetExportedValue(Of IEditorOperationsFactoryService)() Dim endConstructor = New EndConstructCommandHandler( factory, workspace.ExportProvider.GetExportedValue(Of ITextUndoHistoryRegistry)()) Dim operations = factory.GetEditorOperations(view) endConstructor.ExecuteCommand_ReturnKeyCommandHandler(New ReturnKeyCommandArgs(view, view.TextBuffer), Sub() operations.InsertNewLine(), TestCommandExecutionContext.Create()) Assert.Equal(after, view.TextSnapshot.GetText()) Dim afterLine = view.TextSnapshot.GetLineFromLineNumber(afterCaret(0)) Dim afterCaretPoint As Integer If afterCaret(1) = -1 Then afterCaretPoint = afterLine.End Else afterCaretPoint = afterLine.Start + afterCaret(1) End If Dim caretPosition = view.Caret.Position.VirtualBufferPosition Assert.Equal(Of Integer)(afterCaretPoint, If(caretPosition.IsInVirtualSpace, caretPosition.Position + caretPosition.VirtualSpaces, caretPosition.Position)) End Using End Sub End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Shared.Options Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration Imports Microsoft.VisualStudio.Composition Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Microsoft.VisualStudio.Text.Operations Imports Moq Imports Roslyn.Test.EditorUtilities Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration Friend Module EndConstructTestingHelpers Private Function CreateMockIndentationService() As ISmartIndentationService Dim mock As New Mock(Of ISmartIndentationService)(MockBehavior.Strict) mock.Setup(Function(service) service.GetDesiredIndentation(It.IsAny(Of ITextView), It.IsAny(Of ITextSnapshotLine))).Returns(0) Return mock.Object End Function Private Sub DisableLineCommit(workspace As Workspace) workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options _ .WithChangedOption(FeatureOnOffOptions.PrettyListing, LanguageNames.VisualBasic, False))) End Sub Private Sub VerifyTypedCharApplied(doFunc As Func(Of VisualBasicEndConstructService, ITextView, ITextBuffer, Boolean), before As String, after As String, typedChar As Char, endCaretPos As Integer()) Dim caretPos = before.IndexOf("$$", StringComparison.Ordinal) Dim beforeText = before.Replace("$$", "") Using workspace = TestWorkspace.CreateVisualBasic(beforeText, composition:=EditorTestCompositions.EditorFeatures) DisableLineCommit(workspace) Dim view = workspace.Documents.First().GetTextView() view.Caret.MoveTo(New SnapshotPoint(view.TextSnapshot, caretPos)) Dim endConstructService As New VisualBasicEndConstructService( CreateMockIndentationService(), workspace.GetService(Of ITextUndoHistoryRegistry), workspace.GetService(Of IEditorOperationsFactoryService), workspace.GetService(Of IEditorOptionsFactoryService)) view.TextBuffer.Replace(New Span(caretPos, 0), typedChar.ToString()) Assert.True(doFunc(endConstructService, view, view.TextBuffer)) Assert.Equal(after, view.TextSnapshot.GetText()) Dim actualLine As Integer Dim actualChar As Integer view.Caret.Position.BufferPosition.GetLineAndCharacter(actualLine, actualChar) Assert.Equal(endCaretPos(0), actualLine) Assert.Equal(endCaretPos(1), actualChar) End Using End Sub Private Sub VerifyApplied(doFunc As Func(Of VisualBasicEndConstructService, ITextView, ITextBuffer, Boolean), before As String, beforeCaret As Integer(), after As String, afterCaret As Integer()) Using workspace = TestWorkspace.CreateVisualBasic(before, composition:=EditorTestCompositions.EditorFeatures) DisableLineCommit(workspace) Dim textView = workspace.Documents.First().GetTextView() Dim subjectBuffer = workspace.Documents.First().GetTextBuffer() textView.TryMoveCaretToAndEnsureVisible(GetSnapshotPointFromArray(textView, beforeCaret, beforeCaret.Length - 2)) If beforeCaret.Length = 4 Then Dim span = New SnapshotSpan( GetSnapshotPointFromArray(textView, beforeCaret, 0), GetSnapshotPointFromArray(textView, beforeCaret, 2)) textView.SetSelection(span) End If Dim endConstructService As New VisualBasicEndConstructService( CreateMockIndentationService(), workspace.GetService(Of ITextUndoHistoryRegistry), workspace.GetService(Of IEditorOperationsFactoryService), workspace.GetService(Of IEditorOptionsFactoryService)) Assert.True(doFunc(endConstructService, textView, textView.TextSnapshot.TextBuffer)) Assert.Equal(EditorFactory.LinesToFullText(after), textView.TextSnapshot.GetText()) Dim afterLine = textView.TextSnapshot.GetLineFromLineNumber(afterCaret(0)) Dim afterCaretPoint As SnapshotPoint If afterCaret(1) = -1 Then afterCaretPoint = afterLine.End Else afterCaretPoint = New SnapshotPoint(textView.TextSnapshot, afterLine.Start + afterCaret(1)) End If Assert.Equal(Of Integer)(afterCaretPoint, textView.GetCaretPoint(subjectBuffer).Value.Position) End Using End Sub Private Function GetSnapshotPointFromArray(view As ITextView, caret As Integer(), startIndex As Integer) As SnapshotPoint Dim line = view.TextSnapshot.GetLineFromLineNumber(caret(startIndex)) If caret(startIndex + 1) = -1 Then Return line.End Else Return line.Start + caret(startIndex + 1) End If End Function Private Sub VerifyNotApplied(doFunc As Func(Of VisualBasicEndConstructService, ITextView, ITextBuffer, Boolean), text As String, caret As Integer()) Using workspace = TestWorkspace.CreateVisualBasic(text) Dim textView = workspace.Documents.First().GetTextView() Dim subjectBuffer = workspace.Documents.First().GetTextBuffer() Dim line = textView.TextSnapshot.GetLineFromLineNumber(caret(0)) Dim caretPosition As SnapshotPoint If caret(1) = -1 Then caretPosition = line.End Else caretPosition = New SnapshotPoint(textView.TextSnapshot, line.Start + caret(1)) End If textView.TryMoveCaretToAndEnsureVisible(caretPosition) Dim endConstructService As New VisualBasicEndConstructService( CreateMockIndentationService(), workspace.GetService(Of ITextUndoHistoryRegistry), workspace.GetService(Of IEditorOperationsFactoryService), workspace.GetService(Of IEditorOptionsFactoryService)) Assert.False(doFunc(endConstructService, textView, textView.TextSnapshot.TextBuffer), "End Construct should not have generated anything.") ' The text should not have changed Assert.Equal(EditorFactory.LinesToFullText(text), textView.TextSnapshot.GetText()) ' The caret should not have moved Assert.Equal(Of Integer)(caretPosition, textView.GetCaretPoint(subjectBuffer).Value.Position) End Using End Sub Public Sub VerifyStatementEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer()) VerifyApplied(Function(s, v, b) s.TryDoEndConstructForEnterKey(v, b, CancellationToken.None), before, beforeCaret, after, afterCaret) End Sub Public Sub VerifyStatementEndConstructNotApplied(text As String, caret As Integer()) VerifyNotApplied(Function(s, v, b) s.TryDoEndConstructForEnterKey(v, b, CancellationToken.None), text, caret) End Sub Public Sub VerifyXmlElementEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer()) VerifyApplied(Function(s, v, b) s.TryDoXmlElementEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret) End Sub Public Sub VerifyXmlElementEndConstructNotApplied(text As String, caret As Integer()) VerifyNotApplied(Function(s, v, b) s.TryDoXmlElementEndConstruct(v, b, Nothing), text, caret) End Sub Public Sub VerifyXmlCommentEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer()) VerifyApplied(Function(s, v, b) s.TryDoXmlCommentEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret) End Sub Public Sub VerifyXmlCommentEndConstructNotApplied(text As String, caret As Integer()) VerifyNotApplied(Function(s, v, b) s.TryDoXmlCommentEndConstruct(v, b, Nothing), text, caret) End Sub Public Sub VerifyXmlCDataEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer()) VerifyApplied(Function(s, v, b) s.TryDoXmlCDataEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret) End Sub Public Sub VerifyXmlCDataEndConstructNotApplied(text As String, caret As Integer()) VerifyNotApplied(Function(s, v, b) s.TryDoXmlCDataEndConstruct(v, b, Nothing), text, caret) End Sub Public Sub VerifyXmlEmbeddedExpressionEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer()) VerifyApplied(Function(s, v, b) s.TryDoXmlEmbeddedExpressionEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret) End Sub Public Sub VerifyXmlEmbeddedExpressionEndConstructNotApplied(text As String, caret As Integer()) VerifyNotApplied(Function(s, v, b) s.TryDoXmlEmbeddedExpressionEndConstruct(v, b, Nothing), text, caret) End Sub Public Sub VerifyXmlProcessingInstructionEndConstructApplied(before As String, beforeCaret As Integer(), after As String, afterCaret As Integer()) VerifyApplied(Function(s, v, b) s.TryDoXmlProcessingInstructionEndConstruct(v, b, Nothing), before, beforeCaret, after, afterCaret) End Sub Public Sub VerifyXmlProcessingInstructionNotApplied(text As String, caret As Integer()) VerifyNotApplied(Function(s, v, b) s.TryDoXmlProcessingInstructionEndConstruct(v, b, Nothing), text, caret) End Sub Public Sub VerifyEndConstructAppliedAfterChar(before As String, after As String, typedChar As Char, endCaretPos As Integer()) VerifyTypedCharApplied(Function(s, v, b) s.TryDo(v, b, typedChar, Nothing), before, after, typedChar, endCaretPos) End Sub Public Sub VerifyEndConstructNotAppliedAfterChar(before As String, after As String, typedChar As Char, endCaretPos As Integer()) VerifyTypedCharApplied(Function(s, v, b) Not s.TryDo(v, b, typedChar, Nothing), before, after, typedChar, endCaretPos) End Sub Public Sub VerifyAppliedAfterReturnUsingCommandHandler( before As String, beforeCaret As Integer(), after As String, afterCaret As Integer()) ' create separate composition Using workspace = TestWorkspace.CreateVisualBasic(before, composition:=EditorTestCompositions.EditorFeatures) DisableLineCommit(workspace) Dim view = workspace.Documents.First().GetTextView() Dim line = view.TextSnapshot.GetLineFromLineNumber(beforeCaret(0)) If beforeCaret(1) = -1 Then view.Caret.MoveTo(line.End) Else view.Caret.MoveTo(New SnapshotPoint(view.TextSnapshot, line.Start + beforeCaret(1))) End If Dim factory = workspace.ExportProvider.GetExportedValue(Of IEditorOperationsFactoryService)() Dim endConstructor = New EndConstructCommandHandler( factory, workspace.ExportProvider.GetExportedValue(Of ITextUndoHistoryRegistry)()) Dim operations = factory.GetEditorOperations(view) endConstructor.ExecuteCommand_ReturnKeyCommandHandler(New ReturnKeyCommandArgs(view, view.TextBuffer), Sub() operations.InsertNewLine(), TestCommandExecutionContext.Create()) Assert.Equal(after, view.TextSnapshot.GetText()) Dim afterLine = view.TextSnapshot.GetLineFromLineNumber(afterCaret(0)) Dim afterCaretPoint As Integer If afterCaret(1) = -1 Then afterCaretPoint = afterLine.End Else afterCaretPoint = afterLine.Start + afterCaret(1) End If Dim caretPosition = view.Caret.Position.VirtualBufferPosition Assert.Equal(Of Integer)(afterCaretPoint, If(caretPosition.IsInVirtualSpace, caretPosition.Position + caretPosition.VirtualSpaces, caretPosition.Position)) End Using End Sub End Module End Namespace
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_MarshalAs.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_MarshalAs : WellKnownAttributesTestBase { #region Helpers private void VerifyFieldMetadataDecoding(CompilationVerifier verifier, Dictionary<string, byte[]> blobs) { int count = 0; using (var assembly = AssemblyMetadata.CreateFromImage(verifier.EmittedAssemblyData)) { var compilation = CreateEmptyCompilation(new SyntaxTree[0], new[] { assembly.GetReference() }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); foreach (NamedTypeSymbol type in compilation.GlobalNamespace.GetMembers().Where(s => s.Kind == SymbolKind.NamedType)) { var fields = type.GetMembers().Where(s => s.Kind == SymbolKind.Field); foreach (FieldSymbol field in fields) { Assert.Null(field.MarshallingInformation); var blob = blobs[field.Name]; if (blob != null && blob[0] <= 0x50) { Assert.Equal((UnmanagedType)blob[0], field.MarshallingType); } else { Assert.Equal((UnmanagedType)0, field.MarshallingType); } count++; } } } Assert.True(count > 0, "Expected at least one parameter"); } private void VerifyParameterMetadataDecoding(CompilationVerifier verifier, Dictionary<string, byte[]> blobs) { int count = 0; using (var assembly = AssemblyMetadata.CreateFromImage(verifier.EmittedAssemblyData)) { var compilation = CreateEmptyCompilation( new SyntaxTree[0], new[] { assembly.GetReference() }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)); foreach (NamedTypeSymbol type in compilation.GlobalNamespace.GetMembers().Where(s => s.Kind == SymbolKind.NamedType)) { var methods = type.GetMembers().Where(s => s.Kind == SymbolKind.Method); foreach (MethodSymbol method in methods) { foreach (ParameterSymbol parameter in method.Parameters) { Assert.Null(parameter.MarshallingInformation); var blob = blobs[method.Name + ":" + parameter.Name]; if (blob != null && blob[0] <= 0x50) { Assert.Equal((UnmanagedType)blob[0], parameter.MarshallingType); } else { Assert.Equal((UnmanagedType)0, parameter.MarshallingType); } count++; } } } } Assert.True(count > 0, "Expected at least one parameter"); } #endregion #region Fields /// <summary> /// type only, others ignored, field type ignored /// </summary> [Fact] public void SimpleTypes() { var source = @" using System; using System.Runtime.InteropServices; public class X { [MarshalAs((short)0)] public X ZeroShort; [MarshalAs((UnmanagedType)0)] public X Zero; [MarshalAs((UnmanagedType)0x1FFFFFFF)] public X MaxValue; [MarshalAs((UnmanagedType)(0x123456))] public X _0x123456; [MarshalAs((UnmanagedType)(0x1000))] public X _0x1000; [MarshalAs(UnmanagedType.AnsiBStr, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public X AnsiBStr; [MarshalAs(UnmanagedType.AsAny, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public double AsAny; [MarshalAs(UnmanagedType.Bool, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public X Bool; [MarshalAs(UnmanagedType.BStr, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public X BStr; [MarshalAs(UnmanagedType.Currency, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int Currency; [MarshalAs(UnmanagedType.Error, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int Error; [MarshalAs(UnmanagedType.FunctionPtr, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int FunctionPtr; [MarshalAs(UnmanagedType.I1, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int I1; [MarshalAs(UnmanagedType.I2, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int I2; [MarshalAs(UnmanagedType.I4, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int I4; [MarshalAs(UnmanagedType.I8, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int I8; [MarshalAs(UnmanagedType.LPStr, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int LPStr; [MarshalAs(UnmanagedType.LPStruct, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int LPStruct; [MarshalAs(UnmanagedType.LPTStr, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int LPTStr; [MarshalAs(UnmanagedType.LPWStr, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int LPWStr; [MarshalAs(UnmanagedType.R4, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int R4; [MarshalAs(UnmanagedType.R8, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int R8; [MarshalAs(UnmanagedType.Struct, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int Struct; [MarshalAs(UnmanagedType.SysInt, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public decimal SysInt; [MarshalAs(UnmanagedType.SysUInt, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int[] SysUInt; [MarshalAs(UnmanagedType.TBStr, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public object[] TBStr; [MarshalAs(UnmanagedType.U1, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int U1; [MarshalAs(UnmanagedType.U2, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public double U2; [MarshalAs(UnmanagedType.U4, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public bool U4; [MarshalAs(UnmanagedType.U8, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public string U8; [MarshalAs(UnmanagedType.VariantBool, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int VariantBool; }"; var blobs = new Dictionary<string, byte[]> { { "ZeroShort", new byte[] { 0x00 } }, { "Zero", new byte[] { 0x00 } }, { "MaxValue", new byte[] { 0xdf, 0xff, 0xff, 0xff } }, { "_0x1000", new byte[] { 0x90, 0x00 } }, { "_0x123456", new byte[] { 0xC0, 0x12, 0x34, 0x56 } }, { "AnsiBStr", new byte[] { 0x23 } }, { "AsAny", new byte[] { 0x28 } }, { "Bool", new byte[] { 0x02 } }, { "BStr", new byte[] { 0x13 } }, { "Currency", new byte[] { 0x0f } }, { "Error", new byte[] { 0x2d } }, { "FunctionPtr", new byte[] { 0x26 } }, { "I1", new byte[] { 0x03 } }, { "I2", new byte[] { 0x05 } }, { "I4", new byte[] { 0x07 } }, { "I8", new byte[] { 0x09 } }, { "LPStr", new byte[] { 0x14 } }, { "LPStruct", new byte[] { 0x2b } }, { "LPTStr", new byte[] { 0x16 } }, { "LPWStr", new byte[] { 0x15 } }, { "R4", new byte[] { 0x0b } }, { "R8", new byte[] { 0x0c } }, { "Struct", new byte[] { 0x1b } }, { "SysInt", new byte[] { 0x1f } }, { "SysUInt", new byte[] { 0x20 } }, { "TBStr", new byte[] { 0x24 } }, { "U1", new byte[] { 0x04 } }, { "U2", new byte[] { 0x06 } }, { "U4", new byte[] { 0x08 } }, { "U8", new byte[] { 0x0a } }, { "VariantBool", new byte[] { 0x25 } }, }; var verifier = CompileAndVerifyFieldMarshal(source, blobs); VerifyFieldMetadataDecoding(verifier, blobs); } [Fact] public void SimpleTypes_Errors() { var source = @" #pragma warning disable 169 using System.Runtime.InteropServices; class X { [MarshalAs((UnmanagedType)(-1))] X MinValue_1; [MarshalAs((UnmanagedType)0x20000000)] X MaxValue_1; } "; CreateCompilation(source).VerifyDiagnostics( // (6,16): error CS0591: Invalid value for argument to 'MarshalAs' attribute Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "(UnmanagedType)(-1)").WithArguments("MarshalAs"), // (9,16): error CS0591: Invalid value for argument to 'MarshalAs' attribute Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "(UnmanagedType)0x20000000").WithArguments("MarshalAs")); } /// <summary> /// (type, IidParamIndex), others ignored, field type ignored /// </summary> [Fact] public void ComInterfaces() { var source = @" using System; using System.Runtime.InteropServices; public class X { [MarshalAs(UnmanagedType.IDispatch, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 0, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public byte IDispatch; [MarshalAs(UnmanagedType.Interface, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public X Interface; [MarshalAs(UnmanagedType.IUnknown, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 2, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public X[] IUnknown; [MarshalAs(UnmanagedType.IUnknown, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 0x1FFFFFFF, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int MaxValue; [MarshalAs(UnmanagedType.IUnknown, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 0x123456, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int _123456; [MarshalAs(UnmanagedType.IUnknown, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 0x1000, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public X _0x1000; [MarshalAs(UnmanagedType.IDispatch)] public int Default; } "; var blobs = new Dictionary<string, byte[]> { { "IDispatch", new byte[] { 0x1a, 0x00 } }, { "Interface", new byte[] { 0x1c, 0x01 } }, { "IUnknown", new byte[] { 0x19, 0x02 } }, { "MaxValue", new byte[] { 0x19, 0xdf, 0xff, 0xff, 0xff } }, { "_123456", new byte[] { 0x19, 0xc0, 0x12, 0x34, 0x56 } }, { "_0x1000", new byte[] { 0x19, 0x90, 0x00 } }, { "Default", new byte[] { 0x1a } }, }; var verifier = CompileAndVerifyFieldMarshal(source, blobs); VerifyFieldMetadataDecoding(verifier, blobs); } [Fact] [WorkItem(22512, "https://github.com/dotnet/roslyn/issues/22512")] public void ComInterfacesInProperties() { var source = @" using System; using System.Runtime.InteropServices; public class X { [field: MarshalAs(UnmanagedType.IDispatch, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 0, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public byte IDispatch { get; set; } [field: MarshalAs(UnmanagedType.Interface, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public X Interface { get; set; } [field: MarshalAs(UnmanagedType.IUnknown, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 2, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public X[] IUnknown { get; set; } [field: MarshalAs(UnmanagedType.IUnknown, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 0x1FFFFFFF, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int MaxValue { get; set; } [field: MarshalAs(UnmanagedType.IUnknown, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 0x123456, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int _123456 { get; set; } [field: MarshalAs(UnmanagedType.IUnknown, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 0x1000, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public X _0x1000 { get; set; } [field: MarshalAs(UnmanagedType.IDispatch)] public int Default { get; set; } } "; var blobs = new Dictionary<string, byte[]> { { "<IDispatch>k__BackingField", new byte[] { 0x1a, 0x00 } }, { "<Interface>k__BackingField", new byte[] { 0x1c, 0x01 } }, { "<IUnknown>k__BackingField", new byte[] { 0x19, 0x02 } }, { "<MaxValue>k__BackingField", new byte[] { 0x19, 0xdf, 0xff, 0xff, 0xff } }, { "<_123456>k__BackingField", new byte[] { 0x19, 0xc0, 0x12, 0x34, 0x56 } }, { "<_0x1000>k__BackingField", new byte[] { 0x19, 0x90, 0x00 } }, { "<Default>k__BackingField", new byte[] { 0x1a } }, }; var verifier = CompileAndVerifyFieldMarshal(source, blobs); VerifyFieldMetadataDecoding(verifier, blobs); } [Fact] public void ComInterfaces_Errors() { var source = @" #pragma warning disable 169 using System.Runtime.InteropServices; class X { [MarshalAs(UnmanagedType.IDispatch, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType=null, SizeConst=-1, SizeParamIndex=-1)] int IDispatch_MinValue_1; [MarshalAs(UnmanagedType.Interface, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType=null, SizeConst=-1, SizeParamIndex=-1)] int Interface_MinValue_1; [MarshalAs(UnmanagedType.IUnknown, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType=null, SizeConst=-1, SizeParamIndex=-1)] int IUnknown_MinValue_1; [MarshalAs(UnmanagedType.IUnknown, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 0x20000000, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType=null, SizeConst=-1, SizeParamIndex=-1)] int IUnknown_MaxValue_1; } "; CreateCompilation(source).VerifyDiagnostics( // (8,81): error CS0599: Invalid value for argument to 'MarshalAs' attribute Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "IidParameterIndex = -1").WithArguments("IidParameterIndex"), // (11,81): error CS0599: Invalid value for argument to 'MarshalAs' attribute Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "IidParameterIndex = -1").WithArguments("IidParameterIndex"), // (14,80): error CS0599: Invalid value for argument to 'MarshalAs' attribute Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "IidParameterIndex = -1").WithArguments("IidParameterIndex"), // (17,80): error CS0599: Invalid value for argument to 'MarshalAs' attribute Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "IidParameterIndex = 0x20000000").WithArguments("IidParameterIndex")); } /// <summary> /// (ArraySubType, SizeConst, SizeParamIndex), SafeArraySubType not allowed, others ignored /// </summary> [Fact] public void NativeTypeArray() { var source = @" using System; using System.Runtime.InteropServices; public class X { [MarshalAs(UnmanagedType.LPArray)] public int LPArray0; [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArrayUserDefinedSubType = null)] public int LPArray1; [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = 0, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArrayUserDefinedSubType = null)] public int LPArray2; [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = 0x1fffffff, SizeParamIndex = short.MaxValue, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArrayUserDefinedSubType = null)] public int LPArray3; // NATIVE_TYPE_MAX = 0x50 [MarshalAs(UnmanagedType.LPArray, ArraySubType = (UnmanagedType)0x50)] public int LPArray4; [MarshalAs(UnmanagedType.LPArray, ArraySubType = (UnmanagedType)0x1fffffff)] public int LPArray5; [MarshalAs(UnmanagedType.LPArray, ArraySubType = (UnmanagedType)0)] public int LPArray6; } "; var blobs = new Dictionary<string, byte[]> { { "LPArray0", new byte[] { 0x2a, 0x50 } }, { "LPArray1", new byte[] { 0x2a, 0x17 } }, { "LPArray2", new byte[] { 0x2a, 0x17, 0x00, 0x00, 0x00 } }, { "LPArray3", new byte[] { 0x2a, 0x17, 0xc0, 0x00, 0x7f, 0xff, 0xdf, 0xff, 0xff, 0xff, 0x01 } }, { "LPArray4", new byte[] { 0x2a, 0x50 } }, { "LPArray5", new byte[] { 0x2a, 0xdf, 0xff, 0xff, 0xff } }, { "LPArray6", new byte[] { 0x2a, 0x00 } }, }; var verifier = CompileAndVerifyFieldMarshal(source, blobs); VerifyFieldMetadataDecoding(verifier, blobs); } [Fact] public void NativeTypeArray_ElementTypes() { StringBuilder source = new StringBuilder(@" using System; using System.Runtime.InteropServices; class X { "); var expectedBlobs = new Dictionary<string, byte[]>(); for (int i = 0; i < sbyte.MaxValue; i++) { // CustomMarshaler is not allowed if (i != (int)UnmanagedType.CustomMarshaler) { string fldName = string.Format("_{0:X}", i); source.AppendLine(string.Format("[MarshalAs(UnmanagedType.LPArray, ArraySubType = (UnmanagedType)0x{0:X})]int {1};", i, fldName)); expectedBlobs.Add(fldName, new byte[] { 0x2a, (byte)i }); } } source.AppendLine("}"); CompileAndVerifyFieldMarshal(source.ToString(), expectedBlobs); } [Fact] public void NativeTypeArray_Errors() { var source = @" #pragma warning disable 169 using System.Runtime.InteropServices; class X { [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)]int LPArray_e0; [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = -1)] int LPArray_e1; [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = 0, SizeParamIndex = -1)] int LPArray_e2; [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = int.MaxValue, SizeParamIndex = short.MaxValue)] int LPArray_e3; [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U8, SizeConst = int.MaxValue/4 + 1, SizeParamIndex = short.MaxValue)] int LPArray_e4; [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.CustomMarshaler)] int LPArray_e5; [MarshalAs(UnmanagedType.LPArray, SafeArraySubType=VarEnum.VT_I1)] int LPArray_e6; [MarshalAs(UnmanagedType.LPArray, ArraySubType = (UnmanagedType)0x20000000)] int LPArray_e7; [MarshalAs(UnmanagedType.LPArray, ArraySubType = (UnmanagedType)(-1))] int LPArray_e8; } "; CreateCompilation(source).VerifyDiagnostics( // (8,79): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)]int LPArray_e0; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SafeArraySubType = VarEnum.VT_BSTR"), // (8,151): error CS0599: Invalid value for named attribute argument 'SizeConst' // [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)]int LPArray_e0; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "SizeConst = -1").WithArguments("SizeConst"), // (8,167): error CS0599: Invalid value for named attribute argument 'SizeParamIndex' // [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)]int LPArray_e0; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "SizeParamIndex = -1").WithArguments("SizeParamIndex"), // (9,79): error CS0599: Invalid value for named attribute argument 'SizeConst' // [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = -1)] int LPArray_e1; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "SizeConst = -1").WithArguments("SizeConst"), // (10,94): error CS0599: Invalid value for named attribute argument 'SizeParamIndex' // [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = 0, SizeParamIndex = -1)] int LPArray_e2; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "SizeParamIndex = -1").WithArguments("SizeParamIndex"), // (11,79): error CS0599: Invalid value for named attribute argument 'SizeConst' // [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = int.MaxValue, SizeParamIndex = short.MaxValue)] int LPArray_e3; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "SizeConst = int.MaxValue").WithArguments("SizeConst"), // (12,72): error CS0599: Invalid value for named attribute argument 'SizeConst' // [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U8, SizeConst = int.MaxValue/4 + 1, SizeParamIndex = short.MaxValue)] int LPArray_e4; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "SizeConst = int.MaxValue/4 + 1").WithArguments("SizeConst"), // (13,39): error CS0599: Invalid value for named attribute argument 'ArraySubType' // [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.CustomMarshaler)] int LPArray_e5; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "ArraySubType = UnmanagedType.CustomMarshaler").WithArguments("ArraySubType"), // (14,39): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.LPArray, SafeArraySubType=VarEnum.VT_I1)] int LPArray_e6; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SafeArraySubType=VarEnum.VT_I1"), // (15,39): error CS0599: Invalid value for named attribute argument 'ArraySubType' // [MarshalAs(UnmanagedType.LPArray, ArraySubType = (UnmanagedType)0x20000000)] int LPArray_e7; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "ArraySubType = (UnmanagedType)0x20000000").WithArguments("ArraySubType"), // (16,39): error CS0599: Invalid value for named attribute argument 'ArraySubType' // [MarshalAs(UnmanagedType.LPArray, ArraySubType = (UnmanagedType)(-1))] int LPArray_e8; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "ArraySubType = (UnmanagedType)(-1)").WithArguments("ArraySubType")); } /// <summary> /// (ArraySubType, SizeConst), (SizeParamIndex, SafeArraySubType) not allowed, others ignored /// </summary> [Fact] public void NativeTypeFixedArray() { var source = @" using System; using System.Runtime.InteropServices; public class X { [MarshalAs(UnmanagedType.ByValArray)] public int ByValArray0; [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArrayUserDefinedSubType = null)] public int ByValArray1; [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = 0, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArrayUserDefinedSubType = null)] public int ByValArray2; [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = (int.MaxValue - 3) / 4, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArrayUserDefinedSubType = null)] public int ByValArray3; [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.AsAny)] public int ByValArray4; [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.CustomMarshaler)] public int ByValArray5; } "; var blobs = new Dictionary<string, byte[]> { { "ByValArray0", new byte[] { 0x1e, 0x01 } }, { "ByValArray1", new byte[] { 0x1e, 0x01, 0x17 } }, { "ByValArray2", new byte[] { 0x1e, 0x00, 0x17 } }, { "ByValArray3", new byte[] { 0x1e, 0xdf, 0xff, 0xff, 0xff, 0x17} }, { "ByValArray4", new byte[] { 0x1e, 0x01, 0x28 } }, { "ByValArray5", new byte[] { 0x1e, 0x01, 0x2c } }, }; var verifier = CompileAndVerifyFieldMarshal(source, blobs); VerifyFieldMetadataDecoding(verifier, blobs); } [Fact] public void NativeTypeFixedArray_ElementTypes() { StringBuilder source = new StringBuilder(@" using System; using System.Runtime.InteropServices; class X { "); var expectedBlobs = new Dictionary<string, byte[]>(); for (int i = 0; i < sbyte.MaxValue; i++) { string fldName = string.Format("_{0:X}", i); source.AppendLine(string.Format("[MarshalAs(UnmanagedType.ByValArray, ArraySubType = (UnmanagedType)0x{0:X})]int {1};", i, fldName)); expectedBlobs.Add(fldName, new byte[] { 0x1e, 0x01, (byte)i }); } source.AppendLine("}"); CompileAndVerifyFieldMarshal(source.ToString(), expectedBlobs); } [Fact] public void NativeTypeFixedArray_Errors() { var source = @" #pragma warning disable 169 using System.Runtime.InteropServices; public class X { [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)]int ByValArray_e1; [MarshalAs(UnmanagedType.ByValArray, SizeParamIndex = short.MaxValue)] int ByValArray_e2; [MarshalAs(UnmanagedType.ByValArray, SafeArraySubType = VarEnum.VT_I2)] int ByValArray_e3; [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = 0x20000000)] int ByValArray_e4; } "; CreateCompilation(source).VerifyDiagnostics( // (8,82): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)]int ByValArray_e1; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SafeArraySubType = VarEnum.VT_BSTR"), // (8,154):error CS0599: Invalid value for named attribute argument 'SizeConst' // [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)]int ByValArray_e1; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "SizeConst = -1").WithArguments("SizeConst"), // (8,170): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)]int ByValArray_e1; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SizeParamIndex = -1"), // (9,42): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.ByValArray, SizeParamIndex = short.MaxValue)] int ByValArray_e2; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SizeParamIndex = short.MaxValue"), // (10,42): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.ByValArray, SafeArraySubType = VarEnum.VT_I2)] int ByValArray_e3; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SafeArraySubType = VarEnum.VT_I2"), // (11,82): error CS0599: Invalid value for named attribute argument 'SizeConst' // [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = 0x20000000)] int ByValArray_e4; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "SizeConst = 0x20000000").WithArguments("SizeConst")); } /// <summary> /// (SafeArraySubType, SafeArrayUserDefinedSubType), (ArraySubType, SizeConst, SizeParamIndex) not allowed, /// (SafeArraySubType, SafeArrayUserDefinedSubType) not allowed together unless VT_DISPATCH, VT_UNKNOWN, VT_RECORD; others ignored. /// </summary> [Fact] public void NativeTypeSafeArray() { var source = @" using System; using System.Collections.Generic; using System.Runtime.InteropServices; public class X { [MarshalAs(UnmanagedType.SafeArray)] public int SafeArray0; [MarshalAs(UnmanagedType.SafeArray, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR)] public int SafeArray1; [MarshalAs(UnmanagedType.SafeArray, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArrayUserDefinedSubType = typeof(X))] public int SafeArray2; [MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType = null)] public int SafeArray3; [MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType = typeof(void))] public int SafeArray4; [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_EMPTY)] public int SafeArray8; [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_RECORD, SafeArrayUserDefinedSubType = typeof(int*[][]))] public int SafeArray9; [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_RECORD, SafeArrayUserDefinedSubType = typeof(Nullable<>))] public int SafeArray10; } "; var arrayAqn = Encoding.ASCII.GetBytes("System.Int32*[][], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); var openGenericAqn = Encoding.ASCII.GetBytes("System.Nullable`1, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); var blobs = new Dictionary<string, byte[]> { { "SafeArray0", new byte[] { 0x1d } }, { "SafeArray1", new byte[] { 0x1d, 0x08 } }, { "SafeArray2", new byte[] { 0x1d } }, { "SafeArray3", new byte[] { 0x1d } }, { "SafeArray4", new byte[] { 0x1d } }, { "SafeArray8", new byte[] { 0x1d, 0x00 } }, { "SafeArray9", new byte[] { 0x1d, 0x24, (byte)arrayAqn.Length }.Append(arrayAqn) }, { "SafeArray10", new byte[] { 0x1d, 0x24, (byte)openGenericAqn.Length }.Append(openGenericAqn) }, }; var verifier = CompileAndVerifyFieldMarshal(source, blobs); VerifyFieldMetadataDecoding(verifier, blobs); } [Fact] public void NativeTypeSafeArray_CCIOnly() { var source = @" using System; using System.Collections.Generic; using System.Runtime.InteropServices; public class C<T> { public class D<S> { public class E { } } } public class X { [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_RECORD, SafeArrayUserDefinedSubType = typeof(C<int>.D<bool>.E))] public int SafeArray11; } "; var nestedAqn = Encoding.ASCII.GetBytes("C`1+D`1+E[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); var blobs = new Dictionary<string, byte[]> { { "SafeArray11", new byte[] { 0x1d, 0x24, 0x80, 0xc4 }.Append(nestedAqn) }, }; // RefEmit has slightly different encoding of the type name var verifier = CompileAndVerifyFieldMarshal(source, blobs); VerifyFieldMetadataDecoding(verifier, blobs); } [Fact] public void NativeTypeSafeArray_RefEmitDiffers() { var source = @" using System; using System.Collections.Generic; using System.Runtime.InteropServices; public class X { [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_DISPATCH, SafeArrayUserDefinedSubType = typeof(List<X>[][]))] int SafeArray5; [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UNKNOWN, SafeArrayUserDefinedSubType = typeof(X))] int SafeArray6; [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_RECORD, SafeArrayUserDefinedSubType = typeof(X))] int SafeArray7; } "; var e = Encoding.ASCII; var cciBlobs = new Dictionary<string, byte[]> { { "SafeArray5", new byte[] { 0x1d, 0x09, 0x75 }.Append(e.GetBytes("System.Collections.Generic.List`1[X][][], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")) }, { "SafeArray6", new byte[] { 0x1d, 0x0d, 0x01, 0x58 } }, { "SafeArray7", new byte[] { 0x1d, 0x24, 0x01, 0x58 } }, }; CompileAndVerifyFieldMarshal(source, cciBlobs); } [Fact] public void NativeTypeSafeArray_Errors() { var source = @" #pragma warning disable 169 using System.Runtime.InteropServices; public class X { [MarshalAs(UnmanagedType.SafeArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] int SafeArray_e1; [MarshalAs(UnmanagedType.SafeArray, ArraySubType = UnmanagedType.ByValTStr)] int SafeArray_e2; [MarshalAs(UnmanagedType.SafeArray, SizeConst = 1)] int SafeArray_e3; [MarshalAs(UnmanagedType.SafeArray, SizeParamIndex = 1)] int SafeArray_e4; [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null)] int SafeArray_e5; [MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType = null, SafeArraySubType = VarEnum.VT_BLOB)] int SafeArray_e6; [MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType = typeof(int), SafeArraySubType = 0)] int SafeArray_e7; } "; CreateCompilation(source).VerifyDiagnostics( // (8,41): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.SafeArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] int SafeArray_e1; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "ArraySubType = UnmanagedType.ByValTStr"), // (8,153): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.SafeArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] int SafeArray_e1; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SizeConst = -1"), // (8,169): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.SafeArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] int SafeArray_e1; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SizeParamIndex = -1"), // (8,117): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.SafeArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] int SafeArray_e1; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType = null"), // (9,41): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.SafeArray, ArraySubType = UnmanagedType.ByValTStr)] int SafeArray_e2; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "ArraySubType = UnmanagedType.ByValTStr"), // (10,41): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.SafeArray, SizeConst = 1)] int SafeArray_e3; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SizeConst = 1"), // (11,41): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.SafeArray, SizeParamIndex = 1)] int SafeArray_e4; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SizeParamIndex = 1"), // (12,77): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null)] int SafeArray_e5; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType = null"), // (13,41): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType = null, SafeArraySubType = VarEnum.VT_BLOB)] int SafeArray_e6; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType = null"), // (14,41): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType = typeof(int), SafeArraySubType = 0)] int SafeArray_e7; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType = typeof(int)")); } /// <summary> /// (SizeConst - required), (SizeParamIndex, ArraySubType) not allowed /// </summary> [Fact] public void NativeTypeFixedSysString() { var source = @" using System; using System.Runtime.InteropServices; public class X { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)] public int ByValTStr1; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x1fffffff, SafeArrayUserDefinedSubType = typeof(int), IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null)] public int ByValTStr2; } "; var blobs = new Dictionary<string, byte[]> { { "ByValTStr1", new byte[] { 0x17, 0x01 } }, { "ByValTStr2", new byte[] { 0x17, 0xdf, 0xff, 0xff, 0xff } }, }; var verifier = CompileAndVerifyFieldMarshal(source, blobs); VerifyFieldMetadataDecoding(verifier, blobs); } [Fact] public void NativeTypeFixedSysString_Errors() { var source = @" #pragma warning disable 169 using System; using System.Runtime.InteropServices; public class X { [MarshalAs(UnmanagedType.ByValTStr, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] int ByValTStr_e1; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = -1)] int ByValTStr_e2; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Int32.MaxValue / 4 + 1)] int ByValTStr_e3; [MarshalAs(UnmanagedType.ByValTStr)] int ByValTStr_e4; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1, SizeParamIndex=1)] int ByValTStr_e5; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1, ArraySubType = UnmanagedType.ByValTStr)] int ByValTStr_e6; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1, SafeArraySubType = VarEnum.VT_BSTR)] int ByValTStr_e7; } "; CreateCompilation(source).VerifyDiagnostics( // (9,41): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.ByValTStr, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] int ByValTStr_e1; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "ArraySubType = UnmanagedType.ByValTStr"), // (9,153): error CS0599: Invalid value for named attribute argument 'SizeConst' // [MarshalAs(UnmanagedType.ByValTStr, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] int ByValTStr_e1; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "SizeConst = -1").WithArguments("SizeConst"), // (9,169): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.ByValTStr, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] int ByValTStr_e1; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SizeParamIndex = -1"), // (9,6): error CS7046: Attribute parameter 'SizeConst' must be specified. // [MarshalAs(UnmanagedType.ByValTStr, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] int ByValTStr_e1; Diagnostic(ErrorCode.ERR_AttributeParameterRequired1, "MarshalAs").WithArguments("SizeConst"), // (10,41): error CS0599: Invalid value for named attribute argument 'SizeConst' // [MarshalAs(UnmanagedType.ByValTStr, SizeConst = -1)] int ByValTStr_e2; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "SizeConst = -1").WithArguments("SizeConst"), // (10,6): error CS7046: Attribute parameter 'SizeConst' must be specified. // [MarshalAs(UnmanagedType.ByValTStr, SizeConst = -1)] int ByValTStr_e2; Diagnostic(ErrorCode.ERR_AttributeParameterRequired1, "MarshalAs").WithArguments("SizeConst"), // (11,41): error CS0599: Invalid value for named attribute argument 'SizeConst' // [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Int32.MaxValue / 4 + 1)] int ByValTStr_e3; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "SizeConst = Int32.MaxValue / 4 + 1").WithArguments("SizeConst"), // (12,6): error CS7046: Attribute parameter 'SizeConst' must be specified. // [MarshalAs(UnmanagedType.ByValTStr)] int ByValTStr_e4; Diagnostic(ErrorCode.ERR_AttributeParameterRequired1, "MarshalAs").WithArguments("SizeConst"), // (13,56): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1, SizeParamIndex=1)] int ByValTStr_e5; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SizeParamIndex=1"), // (14,56): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1, ArraySubType = UnmanagedType.ByValTStr)] int ByValTStr_e6; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "ArraySubType = UnmanagedType.ByValTStr")); } /// <summary> /// Custom (MarshalType, MarshalTypeRef, MarshalCookie) one of {MarshalType, MarshalTypeRef} required, others ignored /// </summary> [Fact] public void CustomMarshal() { var source = @" using System; using System.Runtime.InteropServices; public class X { [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = null)] public int CustomMarshaler1; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = null)] public int CustomMarshaler2; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = ""foo"", MarshalTypeRef = typeof(int))] public int CustomMarshaler3; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = ""\u1234f\0oozzz"")] public int CustomMarshaler4; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = ""f\0oozzz"")] public int CustomMarshaler5; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = ""xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"")] public int CustomMarshaler6; [MarshalAs(UnmanagedType.CustomMarshaler, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int CustomMarshaler7; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(int))] public int CustomMarshaler8; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(int), MarshalType = ""foo"", MarshalCookie = ""hello\0world(\u1234)"")] public int CustomMarshaler9; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = null, MarshalTypeRef = typeof(int))] public int CustomMarshaler10; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = ""foo"", MarshalTypeRef = null)] public int CustomMarshaler11; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = null, MarshalTypeRef = null)] public int CustomMarshaler12; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = ""aaa\0bbb"", MarshalCookie = ""ccc\0ddd"" )] public int CustomMarshaler13; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = ""\uD869\uDED6"", MarshalCookie = ""\uD869\uDED6"" )] public int CustomMarshaler14; } "; var blobs = new Dictionary<string, byte[]> { { "CustomMarshaler1", new byte[] { 0x2c, 0x00, 0x00, 0x00, 0x00 } }, { "CustomMarshaler2", new byte[] { 0x2c, 0x00, 0x00, 0x00, 0x00 } }, { "CustomMarshaler3", new byte[] { 0x2c, 0x00, 0x00, 0x03, 0x66, 0x6f, 0x6f, 0x00 } }, { "CustomMarshaler4", new byte[] { 0x2c, 0x00, 0x00, 0x0a, 0xe1, 0x88, 0xb4, 0x66, 0x00, 0x6f, 0x6f, 0x7a, 0x7a, 0x7a, 0x00 } }, { "CustomMarshaler5", new byte[] { 0x2c, 0x00, 0x00, 0x07, 0x66, 0x00, 0x6f, 0x6f, 0x7a, 0x7a, 0x7a, 0x00 } }, { "CustomMarshaler6", new byte[] { 0x2c, 0x00, 0x00, 0x60 }.Append(Encoding.UTF8.GetBytes("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\0")) }, { "CustomMarshaler7", new byte[] { 0x2c, 0x00, 0x00, 0x00, 0x00 } }, { "CustomMarshaler8", new byte[] { 0x2c, 0x00, 0x00, 0x59 }.Append(Encoding.UTF8.GetBytes("System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\0")) }, { "CustomMarshaler9", new byte[] { 0x2c, 0x00, 0x00, 0x03, 0x66, 0x6f, 0x6f, 0x10, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x28, 0xe1, 0x88, 0xb4, 0x29 } }, { "CustomMarshaler10", new byte[] { 0x2c, 0x00, 0x00, 0x00, 0x00 } }, { "CustomMarshaler11", new byte[] { 0x2c, 0x00, 0x00, 0x03, 0x66, 0x6f, 0x6f, 0x00 } }, { "CustomMarshaler12", new byte[] { 0x2c, 0x00, 0x00, 0x00, 0x00 } }, { "CustomMarshaler13", new byte[] { 0x2c, 0x00, 0x00, 0x07, 0x61, 0x61, 0x61, 0x00, 0x62, 0x62, 0x62, 0x07, 0x63, 0x63, 0x63, 0x00, 0x64, 0x64, 0x64 } }, { "CustomMarshaler14", new byte[] { 0x2c, 0x00, 0x00, 0x04, 0xf0, 0xaa, 0x9b, 0x96, 0x04, 0xf0, 0xaa, 0x9b, 0x96 } }, }; var verifier = CompileAndVerifyFieldMarshal(source, blobs); VerifyFieldMetadataDecoding(verifier, blobs); } [Fact] public void CustomMarshal_Errors() { var source = @" #pragma warning disable 169 using System.Runtime.InteropServices; public class X { [MarshalAs(UnmanagedType.CustomMarshaler)]int CustomMarshaler_e0; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = ""a\udc00b"", MarshalCookie = ""b"" )]int CustomMarshaler_e1; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = ""x"", MarshalCookie = ""y\udc00"" )]int CustomMarshaler_e2; } "; // Dev10 encodes incomplete surrogates, we don't. CreateCompilation(source).VerifyDiagnostics( // (8,6): error CS7047: Attribute parameter 'MarshalType' or 'MarshalTypeRef' must be specified. // [MarshalAs(UnmanagedType.CustomMarshaler)]int CustomMarshaler_e0; Diagnostic(ErrorCode.ERR_AttributeParameterRequired2, "MarshalAs").WithArguments("MarshalType", "MarshalTypeRef"), // (9,47): error CS0599: Invalid value for named attribute argument 'MarshalType' // [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "a\udc00b", MarshalCookie = "b" )]int CustomMarshaler_e1; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, @"MarshalType = ""a\udc00b""").WithArguments("MarshalType"), // (10,66): error CS0599: Invalid value for named attribute argument 'MarshalCookie' // [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "x", MarshalCookie = "y\udc00" )]int CustomMarshaler_e2; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, @"MarshalCookie = ""y\udc00""").WithArguments("MarshalCookie")); } [Fact] public void EventAndEnumMembers() { var source = @" using System; using System.Runtime.InteropServices; class C { [field: MarshalAs(UnmanagedType.Bool)] event Action e; } enum E { [MarshalAs(UnmanagedType.Bool)] X = 1 } "; CompileAndVerifyFieldMarshal(source, (name, _omitted1) => (name == "e" || name == "X") ? new byte[] { 0x02 } : null); } #endregion #region Parameters and Return Values [Fact] public void Parameters() { var source = @" using System; using System.Runtime.InteropServices; class X { [return: MarshalAs(UnmanagedType.LPStr)] public static X foo( [MarshalAs(UnmanagedType.IDispatch)] ref int IDispatch, [MarshalAs(UnmanagedType.LPArray)] out int LPArray0, [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_EMPTY)] int SafeArray8, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = ""aaa\0bbb"", MarshalCookie = ""ccc\0ddd"" )] int CustomMarshaler13 ) { throw null; } } "; var blobs = new Dictionary<string, byte[]>() { { "foo:", new byte[] { 0x14 } }, // return value { "foo:IDispatch", new byte[] { 0x1a } }, { "foo:LPArray0", new byte[] { 0x2a, 0x50 } }, { "foo:SafeArray8", new byte[] { 0x1d, 0x00 } }, { "foo:CustomMarshaler13", new byte[] { 0x2c, 0x00, 0x00, 0x07, 0x61, 0x61, 0x61, 0x00, 0x62, 0x62, 0x62, 0x07, 0x63, 0x63, 0x63, 0x00, 0x64, 0x64, 0x64 } }, }; var verifier = CompileAndVerifyFieldMarshal(source, blobs, isField: false); VerifyParameterMetadataDecoding(verifier, blobs); } [Fact] public void Parameters_LocalFunction() { var source = @" using System; using System.Runtime.InteropServices; class X { void M() { [return: MarshalAs(UnmanagedType.LPStr)] static X local( [MarshalAs(UnmanagedType.IDispatch)] ref int IDispatch, [MarshalAs(UnmanagedType.LPArray)] out int LPArray0, [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_EMPTY)] int SafeArray8, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = ""aaa\0bbb"", MarshalCookie = ""ccc\0ddd"" )] int CustomMarshaler13 ) { throw null; } } } "; var blobs = new Dictionary<string, byte[]>() { { "<M>g__local|0_0:", new byte[] { 0x14 } }, // return value { "<M>g__local|0_0:IDispatch", new byte[] { 0x1a } }, { "<M>g__local|0_0:LPArray0", new byte[] { 0x2a, 0x50 } }, { "<M>g__local|0_0:SafeArray8", new byte[] { 0x1d, 0x00 } }, { "<M>g__local|0_0:CustomMarshaler13", new byte[] { 0x2c, 0x00, 0x00, 0x07, 0x61, 0x61, 0x61, 0x00, 0x62, 0x62, 0x62, 0x07, 0x63, 0x63, 0x63, 0x00, 0x64, 0x64, 0x64 } }, }; var verifier = CompileAndVerifyFieldMarshal(source, blobs, isField: false); VerifyParameterMetadataDecoding(verifier, blobs); } [Fact] public void MarshalAs_AllParameterTargets_PartialMethods() { var source = @" using System; using System.Runtime.InteropServices; public partial class X { partial void F([MarshalAs(UnmanagedType.BStr)] int pf); partial void F(int pf) { } partial void G(int pg); partial void G([MarshalAs(UnmanagedType.BStr)] int pg) {} partial void H([MarshalAs(UnmanagedType.BStr)] int ph) {} partial void H(int ph); partial void I(int pi) { } partial void I([MarshalAs(UnmanagedType.BStr)] int pi); } "; var blobs = new Dictionary<string, byte[]>() { {"F:pf", new byte[] {0x13}}, {"G:pg", new byte[] {0x13}}, {"H:ph", new byte[] {0x13}}, {"I:pi", new byte[] {0x13}}, }; CompileAndVerifyFieldMarshal(source, blobs, isField: false); } [WorkItem(544508, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544508")] [Fact] public void Parameters_Property_Accessors() { var source = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; public interface I { string P { [return: MarshalAs(UnmanagedType.BStr)] get; [param: MarshalAs(UnmanagedType.BStr)] set; } }"; CompileAndVerifyFieldMarshal(source, new Dictionary<string, byte[]>() { { "get_P:", new byte[] { 0x13 } }, // return value for get accessor { "set_P:" + ParameterSymbol.ValueParameterName, new byte[] { 0x13 } }, // value parameter for set accessor }, isField: false); } [WorkItem(544508, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544508")] [Fact] public void Parameters_Event_Accessors() { var source = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; class C { event Action<string> E { [param: MarshalAs(UnmanagedType.BStr)] add { } [param: MarshalAs(UnmanagedType.BStr)] remove { } } }"; CompileAndVerifyFieldMarshal(source, new Dictionary<string, byte[]>() { { "add_E:" + ParameterSymbol.ValueParameterName, new byte[] { 0x13 } }, { "remove_E:" + ParameterSymbol.ValueParameterName, new byte[] { 0x13 } }, }, isField: false); } [Fact] public void Parameters_Indexer_Getter() { var source = @" using System.Runtime.InteropServices; public class C { public int this[[MarshalAs(UnmanagedType.BStr)]int a, [MarshalAs(UnmanagedType.BStr)]int b] { get { return 0; } } } "; CompileAndVerifyFieldMarshal(source, new Dictionary<string, byte[]>() { { "get_Item:a", new byte[] { 0x13 } }, { "get_Item:b", new byte[] { 0x13 } }, }, isField: false); } [Fact] public void Parameters_Indexer_Setter() { var source = @" using System.Runtime.InteropServices; public class C { public int this[[MarshalAs(UnmanagedType.BStr)]int a, [MarshalAs(UnmanagedType.BStr)]int b] { [param: MarshalAs(UnmanagedType.BStr)] set { } } } "; CompileAndVerifyFieldMarshal(source, new Dictionary<string, byte[]>() { { "set_Item:" + ParameterSymbol.ValueParameterName, new byte[] { 0x13 } }, { "set_Item:a", new byte[] { 0x13 } }, { "set_Item:b", new byte[] { 0x13 } }, }, isField: false); } [WorkItem(544509, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544509")] [Fact] public void Parameters_DelegateType() { var source = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; class C { [return: MarshalAs(UnmanagedType.BStr)] public delegate string Delegate( [In, MarshalAs(UnmanagedType.BStr)]string p1, [param: In, Out, MarshalAs(UnmanagedType.BStr)]ref string p2, [Out, MarshalAs(UnmanagedType.BStr)]out string p3); }"; var marshalAsBstr = new byte[] { 0x13 }; CompileAndVerifyFieldMarshal(source, new Dictionary<string, byte[]>() { { ".ctor:object", null }, { ".ctor:method", null }, { "Invoke:", marshalAsBstr}, // return value { "Invoke:p1", marshalAsBstr }, { "Invoke:p2", marshalAsBstr }, { "Invoke:p3", marshalAsBstr }, { "BeginInvoke:p1", marshalAsBstr }, { "BeginInvoke:p2", marshalAsBstr }, { "BeginInvoke:p3", marshalAsBstr }, { "BeginInvoke:object", null }, { "BeginInvoke:callback", null }, { "EndInvoke:", marshalAsBstr }, { "EndInvoke:p1", marshalAsBstr }, { "EndInvoke:p2", marshalAsBstr }, { "EndInvoke:p3", marshalAsBstr }, { "EndInvoke:result", null }, }, isField: false); } [Fact] public void Parameters_Errors() { var source = @" #pragma warning disable 169 using System.Runtime.InteropServices; class X { public static void f1( [MarshalAs(UnmanagedType.ByValArray)] int ByValArray, [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)] int ByValTStr ) { } [return: MarshalAs(UnmanagedType.ByValArray)] public static int f2() { return 0; } [return: MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)] public static int f3() { return 0; } [MarshalAs(UnmanagedType.VBByRefStr)] public int field; } "; CreateCompilation(source).VerifyDiagnostics( // (7,20): error CS7055: Unmanaged type 'ByValArray' is only valid for fields. Diagnostic(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValArray").WithArguments("ByValArray"), // (10,20): error CS7055: Unmanaged type 'ByValTStr' is only valid for fields. Diagnostic(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValTStr").WithArguments("ByValTStr"), // (16,24): error CS7055: Unmanaged type 'ByValArray' is only valid for fields. Diagnostic(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValArray").WithArguments("ByValArray"), // (19,24): error CS7055: Unmanaged type 'ByValTStr' is only valid for fields. Diagnostic(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValTStr").WithArguments("ByValTStr"), // (22,16): error CS7054: Unmanaged type 'VBByRefStr' not valid for fields. Diagnostic(ErrorCode.ERR_MarshalUnmanagedTypeNotValidForFields, "UnmanagedType.VBByRefStr").WithArguments("VBByRefStr"), // TODO (tomat): remove // (23,16): warning CS0649: Field 'X.field' is never assigned to, and will always have its default value 0 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("X.field", "0")); } [Fact] public void Parameters_Errors_LocalFunction() { var source = @" #pragma warning disable 8321 // Unreferenced local function using System.Runtime.InteropServices; class X { void M() { static void f1( [MarshalAs(UnmanagedType.ByValArray)] int ByValArray, [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)] int ByValTStr ) { } [return: MarshalAs(UnmanagedType.ByValArray)] static int f2() { return 0; } [return: MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)] static int f3() { return 0; } } } "; CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (11,24): error CS7055: Unmanaged type 'ByValArray' is only valid for fields. // [MarshalAs(UnmanagedType.ByValArray)] Diagnostic(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValArray").WithArguments("ByValArray").WithLocation(11, 24), // (14,24): error CS7055: Unmanaged type 'ByValTStr' is only valid for fields. // [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)] Diagnostic(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValTStr").WithArguments("ByValTStr").WithLocation(14, 24), // (20,28): error CS7055: Unmanaged type 'ByValArray' is only valid for fields. // [return: MarshalAs(UnmanagedType.ByValArray)] Diagnostic(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValArray").WithArguments("ByValArray").WithLocation(20, 28), // (23,28): error CS7055: Unmanaged type 'ByValTStr' is only valid for fields. // [return: MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)] Diagnostic(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValTStr").WithArguments("ByValTStr").WithLocation(23, 28)); } /// <summary> /// type only, only on parameters /// </summary> [Fact] public void NativeTypeByValStr() { var source = @" using System; using System.Runtime.InteropServices; class X { [return: MarshalAs(UnmanagedType.VBByRefStr, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] static void f( [MarshalAs(UnmanagedType.VBByRefStr, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] ref int VBByRefStr_e1, [MarshalAs(UnmanagedType.VBByRefStr, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] char[] VBByRefStr_e2, [MarshalAs(UnmanagedType.VBByRefStr, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] int VBByRefStr_e3) { } } "; CompileAndVerifyFieldMarshal(source, new Dictionary<string, byte[]> { { "f:", new byte[] { 0x22 } }, // return value { "f:VBByRefStr_e1", new byte[] { 0x22 } }, { "f:VBByRefStr_e2", new byte[] { 0x22 } }, { "f:VBByRefStr_e3", new byte[] { 0x22 } }, }, isField: false); } [Fact, WorkItem(545374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545374")] public void ImportOptionalMarshalAsParameter() { string text1 = @" using System.Runtime.InteropServices; public class P2<T> { public int Foo([Optional][MarshalAs(UnmanagedType.IDispatch)] T i) { if (i == null) return 0; return 1; } } "; string text2 = @" class C { public static void Main() { P2<object> p2 = new P2<object>(); System.Console.WriteLine(p2.Foo()); } } "; var comp1 = CreateCompilation(text1, assemblyName: "OptionalMarshalAsLibrary"); var comp2 = CreateCompilation(text2, options: TestOptions.ReleaseExe, references: new[] { comp1.EmitToImageReference() }, // it has to be real assembly, Comp2comp reference OK assemblyName: "APP"); CompileAndVerify(comp2, expectedOutput: @"0").VerifyIL("C.Main", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: newobj ""P2<object>..ctor()"" IL_0005: ldnull IL_0006: callvirt ""int P2<object>.Foo(object)"" IL_000b: call ""void System.Console.WriteLine(int)"" IL_0010: ret } "); } #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.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_MarshalAs : WellKnownAttributesTestBase { #region Helpers private void VerifyFieldMetadataDecoding(CompilationVerifier verifier, Dictionary<string, byte[]> blobs) { int count = 0; using (var assembly = AssemblyMetadata.CreateFromImage(verifier.EmittedAssemblyData)) { var compilation = CreateEmptyCompilation(new SyntaxTree[0], new[] { assembly.GetReference() }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); foreach (NamedTypeSymbol type in compilation.GlobalNamespace.GetMembers().Where(s => s.Kind == SymbolKind.NamedType)) { var fields = type.GetMembers().Where(s => s.Kind == SymbolKind.Field); foreach (FieldSymbol field in fields) { Assert.Null(field.MarshallingInformation); var blob = blobs[field.Name]; if (blob != null && blob[0] <= 0x50) { Assert.Equal((UnmanagedType)blob[0], field.MarshallingType); } else { Assert.Equal((UnmanagedType)0, field.MarshallingType); } count++; } } } Assert.True(count > 0, "Expected at least one parameter"); } private void VerifyParameterMetadataDecoding(CompilationVerifier verifier, Dictionary<string, byte[]> blobs) { int count = 0; using (var assembly = AssemblyMetadata.CreateFromImage(verifier.EmittedAssemblyData)) { var compilation = CreateEmptyCompilation( new SyntaxTree[0], new[] { assembly.GetReference() }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)); foreach (NamedTypeSymbol type in compilation.GlobalNamespace.GetMembers().Where(s => s.Kind == SymbolKind.NamedType)) { var methods = type.GetMembers().Where(s => s.Kind == SymbolKind.Method); foreach (MethodSymbol method in methods) { foreach (ParameterSymbol parameter in method.Parameters) { Assert.Null(parameter.MarshallingInformation); var blob = blobs[method.Name + ":" + parameter.Name]; if (blob != null && blob[0] <= 0x50) { Assert.Equal((UnmanagedType)blob[0], parameter.MarshallingType); } else { Assert.Equal((UnmanagedType)0, parameter.MarshallingType); } count++; } } } } Assert.True(count > 0, "Expected at least one parameter"); } #endregion #region Fields /// <summary> /// type only, others ignored, field type ignored /// </summary> [Fact] public void SimpleTypes() { var source = @" using System; using System.Runtime.InteropServices; public class X { [MarshalAs((short)0)] public X ZeroShort; [MarshalAs((UnmanagedType)0)] public X Zero; [MarshalAs((UnmanagedType)0x1FFFFFFF)] public X MaxValue; [MarshalAs((UnmanagedType)(0x123456))] public X _0x123456; [MarshalAs((UnmanagedType)(0x1000))] public X _0x1000; [MarshalAs(UnmanagedType.AnsiBStr, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public X AnsiBStr; [MarshalAs(UnmanagedType.AsAny, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public double AsAny; [MarshalAs(UnmanagedType.Bool, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public X Bool; [MarshalAs(UnmanagedType.BStr, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public X BStr; [MarshalAs(UnmanagedType.Currency, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int Currency; [MarshalAs(UnmanagedType.Error, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int Error; [MarshalAs(UnmanagedType.FunctionPtr, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int FunctionPtr; [MarshalAs(UnmanagedType.I1, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int I1; [MarshalAs(UnmanagedType.I2, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int I2; [MarshalAs(UnmanagedType.I4, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int I4; [MarshalAs(UnmanagedType.I8, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int I8; [MarshalAs(UnmanagedType.LPStr, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int LPStr; [MarshalAs(UnmanagedType.LPStruct, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int LPStruct; [MarshalAs(UnmanagedType.LPTStr, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int LPTStr; [MarshalAs(UnmanagedType.LPWStr, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int LPWStr; [MarshalAs(UnmanagedType.R4, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int R4; [MarshalAs(UnmanagedType.R8, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int R8; [MarshalAs(UnmanagedType.Struct, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int Struct; [MarshalAs(UnmanagedType.SysInt, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public decimal SysInt; [MarshalAs(UnmanagedType.SysUInt, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int[] SysUInt; [MarshalAs(UnmanagedType.TBStr, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public object[] TBStr; [MarshalAs(UnmanagedType.U1, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int U1; [MarshalAs(UnmanagedType.U2, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public double U2; [MarshalAs(UnmanagedType.U4, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public bool U4; [MarshalAs(UnmanagedType.U8, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public string U8; [MarshalAs(UnmanagedType.VariantBool, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int VariantBool; }"; var blobs = new Dictionary<string, byte[]> { { "ZeroShort", new byte[] { 0x00 } }, { "Zero", new byte[] { 0x00 } }, { "MaxValue", new byte[] { 0xdf, 0xff, 0xff, 0xff } }, { "_0x1000", new byte[] { 0x90, 0x00 } }, { "_0x123456", new byte[] { 0xC0, 0x12, 0x34, 0x56 } }, { "AnsiBStr", new byte[] { 0x23 } }, { "AsAny", new byte[] { 0x28 } }, { "Bool", new byte[] { 0x02 } }, { "BStr", new byte[] { 0x13 } }, { "Currency", new byte[] { 0x0f } }, { "Error", new byte[] { 0x2d } }, { "FunctionPtr", new byte[] { 0x26 } }, { "I1", new byte[] { 0x03 } }, { "I2", new byte[] { 0x05 } }, { "I4", new byte[] { 0x07 } }, { "I8", new byte[] { 0x09 } }, { "LPStr", new byte[] { 0x14 } }, { "LPStruct", new byte[] { 0x2b } }, { "LPTStr", new byte[] { 0x16 } }, { "LPWStr", new byte[] { 0x15 } }, { "R4", new byte[] { 0x0b } }, { "R8", new byte[] { 0x0c } }, { "Struct", new byte[] { 0x1b } }, { "SysInt", new byte[] { 0x1f } }, { "SysUInt", new byte[] { 0x20 } }, { "TBStr", new byte[] { 0x24 } }, { "U1", new byte[] { 0x04 } }, { "U2", new byte[] { 0x06 } }, { "U4", new byte[] { 0x08 } }, { "U8", new byte[] { 0x0a } }, { "VariantBool", new byte[] { 0x25 } }, }; var verifier = CompileAndVerifyFieldMarshal(source, blobs); VerifyFieldMetadataDecoding(verifier, blobs); } [Fact] public void SimpleTypes_Errors() { var source = @" #pragma warning disable 169 using System.Runtime.InteropServices; class X { [MarshalAs((UnmanagedType)(-1))] X MinValue_1; [MarshalAs((UnmanagedType)0x20000000)] X MaxValue_1; } "; CreateCompilation(source).VerifyDiagnostics( // (6,16): error CS0591: Invalid value for argument to 'MarshalAs' attribute Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "(UnmanagedType)(-1)").WithArguments("MarshalAs"), // (9,16): error CS0591: Invalid value for argument to 'MarshalAs' attribute Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "(UnmanagedType)0x20000000").WithArguments("MarshalAs")); } /// <summary> /// (type, IidParamIndex), others ignored, field type ignored /// </summary> [Fact] public void ComInterfaces() { var source = @" using System; using System.Runtime.InteropServices; public class X { [MarshalAs(UnmanagedType.IDispatch, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 0, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public byte IDispatch; [MarshalAs(UnmanagedType.Interface, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public X Interface; [MarshalAs(UnmanagedType.IUnknown, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 2, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public X[] IUnknown; [MarshalAs(UnmanagedType.IUnknown, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 0x1FFFFFFF, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int MaxValue; [MarshalAs(UnmanagedType.IUnknown, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 0x123456, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int _123456; [MarshalAs(UnmanagedType.IUnknown, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 0x1000, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public X _0x1000; [MarshalAs(UnmanagedType.IDispatch)] public int Default; } "; var blobs = new Dictionary<string, byte[]> { { "IDispatch", new byte[] { 0x1a, 0x00 } }, { "Interface", new byte[] { 0x1c, 0x01 } }, { "IUnknown", new byte[] { 0x19, 0x02 } }, { "MaxValue", new byte[] { 0x19, 0xdf, 0xff, 0xff, 0xff } }, { "_123456", new byte[] { 0x19, 0xc0, 0x12, 0x34, 0x56 } }, { "_0x1000", new byte[] { 0x19, 0x90, 0x00 } }, { "Default", new byte[] { 0x1a } }, }; var verifier = CompileAndVerifyFieldMarshal(source, blobs); VerifyFieldMetadataDecoding(verifier, blobs); } [Fact] [WorkItem(22512, "https://github.com/dotnet/roslyn/issues/22512")] public void ComInterfacesInProperties() { var source = @" using System; using System.Runtime.InteropServices; public class X { [field: MarshalAs(UnmanagedType.IDispatch, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 0, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public byte IDispatch { get; set; } [field: MarshalAs(UnmanagedType.Interface, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public X Interface { get; set; } [field: MarshalAs(UnmanagedType.IUnknown, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 2, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public X[] IUnknown { get; set; } [field: MarshalAs(UnmanagedType.IUnknown, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 0x1FFFFFFF, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int MaxValue { get; set; } [field: MarshalAs(UnmanagedType.IUnknown, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 0x123456, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int _123456 { get; set; } [field: MarshalAs(UnmanagedType.IUnknown, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 0x1000, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public X _0x1000 { get; set; } [field: MarshalAs(UnmanagedType.IDispatch)] public int Default { get; set; } } "; var blobs = new Dictionary<string, byte[]> { { "<IDispatch>k__BackingField", new byte[] { 0x1a, 0x00 } }, { "<Interface>k__BackingField", new byte[] { 0x1c, 0x01 } }, { "<IUnknown>k__BackingField", new byte[] { 0x19, 0x02 } }, { "<MaxValue>k__BackingField", new byte[] { 0x19, 0xdf, 0xff, 0xff, 0xff } }, { "<_123456>k__BackingField", new byte[] { 0x19, 0xc0, 0x12, 0x34, 0x56 } }, { "<_0x1000>k__BackingField", new byte[] { 0x19, 0x90, 0x00 } }, { "<Default>k__BackingField", new byte[] { 0x1a } }, }; var verifier = CompileAndVerifyFieldMarshal(source, blobs); VerifyFieldMetadataDecoding(verifier, blobs); } [Fact] public void ComInterfaces_Errors() { var source = @" #pragma warning disable 169 using System.Runtime.InteropServices; class X { [MarshalAs(UnmanagedType.IDispatch, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType=null, SizeConst=-1, SizeParamIndex=-1)] int IDispatch_MinValue_1; [MarshalAs(UnmanagedType.Interface, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType=null, SizeConst=-1, SizeParamIndex=-1)] int Interface_MinValue_1; [MarshalAs(UnmanagedType.IUnknown, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType=null, SizeConst=-1, SizeParamIndex=-1)] int IUnknown_MinValue_1; [MarshalAs(UnmanagedType.IUnknown, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = 0x20000000, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType=VarEnum.VT_BSTR, SafeArrayUserDefinedSubType=null, SizeConst=-1, SizeParamIndex=-1)] int IUnknown_MaxValue_1; } "; CreateCompilation(source).VerifyDiagnostics( // (8,81): error CS0599: Invalid value for argument to 'MarshalAs' attribute Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "IidParameterIndex = -1").WithArguments("IidParameterIndex"), // (11,81): error CS0599: Invalid value for argument to 'MarshalAs' attribute Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "IidParameterIndex = -1").WithArguments("IidParameterIndex"), // (14,80): error CS0599: Invalid value for argument to 'MarshalAs' attribute Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "IidParameterIndex = -1").WithArguments("IidParameterIndex"), // (17,80): error CS0599: Invalid value for argument to 'MarshalAs' attribute Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "IidParameterIndex = 0x20000000").WithArguments("IidParameterIndex")); } /// <summary> /// (ArraySubType, SizeConst, SizeParamIndex), SafeArraySubType not allowed, others ignored /// </summary> [Fact] public void NativeTypeArray() { var source = @" using System; using System.Runtime.InteropServices; public class X { [MarshalAs(UnmanagedType.LPArray)] public int LPArray0; [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArrayUserDefinedSubType = null)] public int LPArray1; [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = 0, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArrayUserDefinedSubType = null)] public int LPArray2; [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = 0x1fffffff, SizeParamIndex = short.MaxValue, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArrayUserDefinedSubType = null)] public int LPArray3; // NATIVE_TYPE_MAX = 0x50 [MarshalAs(UnmanagedType.LPArray, ArraySubType = (UnmanagedType)0x50)] public int LPArray4; [MarshalAs(UnmanagedType.LPArray, ArraySubType = (UnmanagedType)0x1fffffff)] public int LPArray5; [MarshalAs(UnmanagedType.LPArray, ArraySubType = (UnmanagedType)0)] public int LPArray6; } "; var blobs = new Dictionary<string, byte[]> { { "LPArray0", new byte[] { 0x2a, 0x50 } }, { "LPArray1", new byte[] { 0x2a, 0x17 } }, { "LPArray2", new byte[] { 0x2a, 0x17, 0x00, 0x00, 0x00 } }, { "LPArray3", new byte[] { 0x2a, 0x17, 0xc0, 0x00, 0x7f, 0xff, 0xdf, 0xff, 0xff, 0xff, 0x01 } }, { "LPArray4", new byte[] { 0x2a, 0x50 } }, { "LPArray5", new byte[] { 0x2a, 0xdf, 0xff, 0xff, 0xff } }, { "LPArray6", new byte[] { 0x2a, 0x00 } }, }; var verifier = CompileAndVerifyFieldMarshal(source, blobs); VerifyFieldMetadataDecoding(verifier, blobs); } [Fact] public void NativeTypeArray_ElementTypes() { StringBuilder source = new StringBuilder(@" using System; using System.Runtime.InteropServices; class X { "); var expectedBlobs = new Dictionary<string, byte[]>(); for (int i = 0; i < sbyte.MaxValue; i++) { // CustomMarshaler is not allowed if (i != (int)UnmanagedType.CustomMarshaler) { string fldName = string.Format("_{0:X}", i); source.AppendLine(string.Format("[MarshalAs(UnmanagedType.LPArray, ArraySubType = (UnmanagedType)0x{0:X})]int {1};", i, fldName)); expectedBlobs.Add(fldName, new byte[] { 0x2a, (byte)i }); } } source.AppendLine("}"); CompileAndVerifyFieldMarshal(source.ToString(), expectedBlobs); } [Fact] public void NativeTypeArray_Errors() { var source = @" #pragma warning disable 169 using System.Runtime.InteropServices; class X { [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)]int LPArray_e0; [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = -1)] int LPArray_e1; [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = 0, SizeParamIndex = -1)] int LPArray_e2; [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = int.MaxValue, SizeParamIndex = short.MaxValue)] int LPArray_e3; [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U8, SizeConst = int.MaxValue/4 + 1, SizeParamIndex = short.MaxValue)] int LPArray_e4; [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.CustomMarshaler)] int LPArray_e5; [MarshalAs(UnmanagedType.LPArray, SafeArraySubType=VarEnum.VT_I1)] int LPArray_e6; [MarshalAs(UnmanagedType.LPArray, ArraySubType = (UnmanagedType)0x20000000)] int LPArray_e7; [MarshalAs(UnmanagedType.LPArray, ArraySubType = (UnmanagedType)(-1))] int LPArray_e8; } "; CreateCompilation(source).VerifyDiagnostics( // (8,79): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)]int LPArray_e0; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SafeArraySubType = VarEnum.VT_BSTR"), // (8,151): error CS0599: Invalid value for named attribute argument 'SizeConst' // [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)]int LPArray_e0; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "SizeConst = -1").WithArguments("SizeConst"), // (8,167): error CS0599: Invalid value for named attribute argument 'SizeParamIndex' // [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)]int LPArray_e0; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "SizeParamIndex = -1").WithArguments("SizeParamIndex"), // (9,79): error CS0599: Invalid value for named attribute argument 'SizeConst' // [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = -1)] int LPArray_e1; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "SizeConst = -1").WithArguments("SizeConst"), // (10,94): error CS0599: Invalid value for named attribute argument 'SizeParamIndex' // [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = 0, SizeParamIndex = -1)] int LPArray_e2; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "SizeParamIndex = -1").WithArguments("SizeParamIndex"), // (11,79): error CS0599: Invalid value for named attribute argument 'SizeConst' // [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = int.MaxValue, SizeParamIndex = short.MaxValue)] int LPArray_e3; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "SizeConst = int.MaxValue").WithArguments("SizeConst"), // (12,72): error CS0599: Invalid value for named attribute argument 'SizeConst' // [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U8, SizeConst = int.MaxValue/4 + 1, SizeParamIndex = short.MaxValue)] int LPArray_e4; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "SizeConst = int.MaxValue/4 + 1").WithArguments("SizeConst"), // (13,39): error CS0599: Invalid value for named attribute argument 'ArraySubType' // [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.CustomMarshaler)] int LPArray_e5; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "ArraySubType = UnmanagedType.CustomMarshaler").WithArguments("ArraySubType"), // (14,39): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.LPArray, SafeArraySubType=VarEnum.VT_I1)] int LPArray_e6; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SafeArraySubType=VarEnum.VT_I1"), // (15,39): error CS0599: Invalid value for named attribute argument 'ArraySubType' // [MarshalAs(UnmanagedType.LPArray, ArraySubType = (UnmanagedType)0x20000000)] int LPArray_e7; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "ArraySubType = (UnmanagedType)0x20000000").WithArguments("ArraySubType"), // (16,39): error CS0599: Invalid value for named attribute argument 'ArraySubType' // [MarshalAs(UnmanagedType.LPArray, ArraySubType = (UnmanagedType)(-1))] int LPArray_e8; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "ArraySubType = (UnmanagedType)(-1)").WithArguments("ArraySubType")); } /// <summary> /// (ArraySubType, SizeConst), (SizeParamIndex, SafeArraySubType) not allowed, others ignored /// </summary> [Fact] public void NativeTypeFixedArray() { var source = @" using System; using System.Runtime.InteropServices; public class X { [MarshalAs(UnmanagedType.ByValArray)] public int ByValArray0; [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArrayUserDefinedSubType = null)] public int ByValArray1; [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = 0, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArrayUserDefinedSubType = null)] public int ByValArray2; [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = (int.MaxValue - 3) / 4, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArrayUserDefinedSubType = null)] public int ByValArray3; [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.AsAny)] public int ByValArray4; [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.CustomMarshaler)] public int ByValArray5; } "; var blobs = new Dictionary<string, byte[]> { { "ByValArray0", new byte[] { 0x1e, 0x01 } }, { "ByValArray1", new byte[] { 0x1e, 0x01, 0x17 } }, { "ByValArray2", new byte[] { 0x1e, 0x00, 0x17 } }, { "ByValArray3", new byte[] { 0x1e, 0xdf, 0xff, 0xff, 0xff, 0x17} }, { "ByValArray4", new byte[] { 0x1e, 0x01, 0x28 } }, { "ByValArray5", new byte[] { 0x1e, 0x01, 0x2c } }, }; var verifier = CompileAndVerifyFieldMarshal(source, blobs); VerifyFieldMetadataDecoding(verifier, blobs); } [Fact] public void NativeTypeFixedArray_ElementTypes() { StringBuilder source = new StringBuilder(@" using System; using System.Runtime.InteropServices; class X { "); var expectedBlobs = new Dictionary<string, byte[]>(); for (int i = 0; i < sbyte.MaxValue; i++) { string fldName = string.Format("_{0:X}", i); source.AppendLine(string.Format("[MarshalAs(UnmanagedType.ByValArray, ArraySubType = (UnmanagedType)0x{0:X})]int {1};", i, fldName)); expectedBlobs.Add(fldName, new byte[] { 0x1e, 0x01, (byte)i }); } source.AppendLine("}"); CompileAndVerifyFieldMarshal(source.ToString(), expectedBlobs); } [Fact] public void NativeTypeFixedArray_Errors() { var source = @" #pragma warning disable 169 using System.Runtime.InteropServices; public class X { [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)]int ByValArray_e1; [MarshalAs(UnmanagedType.ByValArray, SizeParamIndex = short.MaxValue)] int ByValArray_e2; [MarshalAs(UnmanagedType.ByValArray, SafeArraySubType = VarEnum.VT_I2)] int ByValArray_e3; [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = 0x20000000)] int ByValArray_e4; } "; CreateCompilation(source).VerifyDiagnostics( // (8,82): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)]int ByValArray_e1; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SafeArraySubType = VarEnum.VT_BSTR"), // (8,154):error CS0599: Invalid value for named attribute argument 'SizeConst' // [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)]int ByValArray_e1; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "SizeConst = -1").WithArguments("SizeConst"), // (8,170): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)]int ByValArray_e1; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SizeParamIndex = -1"), // (9,42): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.ByValArray, SizeParamIndex = short.MaxValue)] int ByValArray_e2; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SizeParamIndex = short.MaxValue"), // (10,42): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.ByValArray, SafeArraySubType = VarEnum.VT_I2)] int ByValArray_e3; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SafeArraySubType = VarEnum.VT_I2"), // (11,82): error CS0599: Invalid value for named attribute argument 'SizeConst' // [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.ByValTStr, SizeConst = 0x20000000)] int ByValArray_e4; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "SizeConst = 0x20000000").WithArguments("SizeConst")); } /// <summary> /// (SafeArraySubType, SafeArrayUserDefinedSubType), (ArraySubType, SizeConst, SizeParamIndex) not allowed, /// (SafeArraySubType, SafeArrayUserDefinedSubType) not allowed together unless VT_DISPATCH, VT_UNKNOWN, VT_RECORD; others ignored. /// </summary> [Fact] public void NativeTypeSafeArray() { var source = @" using System; using System.Collections.Generic; using System.Runtime.InteropServices; public class X { [MarshalAs(UnmanagedType.SafeArray)] public int SafeArray0; [MarshalAs(UnmanagedType.SafeArray, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR)] public int SafeArray1; [MarshalAs(UnmanagedType.SafeArray, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArrayUserDefinedSubType = typeof(X))] public int SafeArray2; [MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType = null)] public int SafeArray3; [MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType = typeof(void))] public int SafeArray4; [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_EMPTY)] public int SafeArray8; [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_RECORD, SafeArrayUserDefinedSubType = typeof(int*[][]))] public int SafeArray9; [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_RECORD, SafeArrayUserDefinedSubType = typeof(Nullable<>))] public int SafeArray10; } "; var arrayAqn = Encoding.ASCII.GetBytes("System.Int32*[][], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); var openGenericAqn = Encoding.ASCII.GetBytes("System.Nullable`1, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); var blobs = new Dictionary<string, byte[]> { { "SafeArray0", new byte[] { 0x1d } }, { "SafeArray1", new byte[] { 0x1d, 0x08 } }, { "SafeArray2", new byte[] { 0x1d } }, { "SafeArray3", new byte[] { 0x1d } }, { "SafeArray4", new byte[] { 0x1d } }, { "SafeArray8", new byte[] { 0x1d, 0x00 } }, { "SafeArray9", new byte[] { 0x1d, 0x24, (byte)arrayAqn.Length }.Append(arrayAqn) }, { "SafeArray10", new byte[] { 0x1d, 0x24, (byte)openGenericAqn.Length }.Append(openGenericAqn) }, }; var verifier = CompileAndVerifyFieldMarshal(source, blobs); VerifyFieldMetadataDecoding(verifier, blobs); } [Fact] public void NativeTypeSafeArray_CCIOnly() { var source = @" using System; using System.Collections.Generic; using System.Runtime.InteropServices; public class C<T> { public class D<S> { public class E { } } } public class X { [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_RECORD, SafeArrayUserDefinedSubType = typeof(C<int>.D<bool>.E))] public int SafeArray11; } "; var nestedAqn = Encoding.ASCII.GetBytes("C`1+D`1+E[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); var blobs = new Dictionary<string, byte[]> { { "SafeArray11", new byte[] { 0x1d, 0x24, 0x80, 0xc4 }.Append(nestedAqn) }, }; // RefEmit has slightly different encoding of the type name var verifier = CompileAndVerifyFieldMarshal(source, blobs); VerifyFieldMetadataDecoding(verifier, blobs); } [Fact] public void NativeTypeSafeArray_RefEmitDiffers() { var source = @" using System; using System.Collections.Generic; using System.Runtime.InteropServices; public class X { [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_DISPATCH, SafeArrayUserDefinedSubType = typeof(List<X>[][]))] int SafeArray5; [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UNKNOWN, SafeArrayUserDefinedSubType = typeof(X))] int SafeArray6; [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_RECORD, SafeArrayUserDefinedSubType = typeof(X))] int SafeArray7; } "; var e = Encoding.ASCII; var cciBlobs = new Dictionary<string, byte[]> { { "SafeArray5", new byte[] { 0x1d, 0x09, 0x75 }.Append(e.GetBytes("System.Collections.Generic.List`1[X][][], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")) }, { "SafeArray6", new byte[] { 0x1d, 0x0d, 0x01, 0x58 } }, { "SafeArray7", new byte[] { 0x1d, 0x24, 0x01, 0x58 } }, }; CompileAndVerifyFieldMarshal(source, cciBlobs); } [Fact] public void NativeTypeSafeArray_Errors() { var source = @" #pragma warning disable 169 using System.Runtime.InteropServices; public class X { [MarshalAs(UnmanagedType.SafeArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] int SafeArray_e1; [MarshalAs(UnmanagedType.SafeArray, ArraySubType = UnmanagedType.ByValTStr)] int SafeArray_e2; [MarshalAs(UnmanagedType.SafeArray, SizeConst = 1)] int SafeArray_e3; [MarshalAs(UnmanagedType.SafeArray, SizeParamIndex = 1)] int SafeArray_e4; [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null)] int SafeArray_e5; [MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType = null, SafeArraySubType = VarEnum.VT_BLOB)] int SafeArray_e6; [MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType = typeof(int), SafeArraySubType = 0)] int SafeArray_e7; } "; CreateCompilation(source).VerifyDiagnostics( // (8,41): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.SafeArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] int SafeArray_e1; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "ArraySubType = UnmanagedType.ByValTStr"), // (8,153): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.SafeArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] int SafeArray_e1; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SizeConst = -1"), // (8,169): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.SafeArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] int SafeArray_e1; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SizeParamIndex = -1"), // (8,117): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.SafeArray, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] int SafeArray_e1; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType = null"), // (9,41): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.SafeArray, ArraySubType = UnmanagedType.ByValTStr)] int SafeArray_e2; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "ArraySubType = UnmanagedType.ByValTStr"), // (10,41): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.SafeArray, SizeConst = 1)] int SafeArray_e3; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SizeConst = 1"), // (11,41): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.SafeArray, SizeParamIndex = 1)] int SafeArray_e4; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SizeParamIndex = 1"), // (12,77): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null)] int SafeArray_e5; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType = null"), // (13,41): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType = null, SafeArraySubType = VarEnum.VT_BLOB)] int SafeArray_e6; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType = null"), // (14,41): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType = typeof(int), SafeArraySubType = 0)] int SafeArray_e7; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SafeArrayUserDefinedSubType = typeof(int)")); } /// <summary> /// (SizeConst - required), (SizeParamIndex, ArraySubType) not allowed /// </summary> [Fact] public void NativeTypeFixedSysString() { var source = @" using System; using System.Runtime.InteropServices; public class X { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)] public int ByValTStr1; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x1fffffff, SafeArrayUserDefinedSubType = typeof(int), IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null)] public int ByValTStr2; } "; var blobs = new Dictionary<string, byte[]> { { "ByValTStr1", new byte[] { 0x17, 0x01 } }, { "ByValTStr2", new byte[] { 0x17, 0xdf, 0xff, 0xff, 0xff } }, }; var verifier = CompileAndVerifyFieldMarshal(source, blobs); VerifyFieldMetadataDecoding(verifier, blobs); } [Fact] public void NativeTypeFixedSysString_Errors() { var source = @" #pragma warning disable 169 using System; using System.Runtime.InteropServices; public class X { [MarshalAs(UnmanagedType.ByValTStr, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] int ByValTStr_e1; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = -1)] int ByValTStr_e2; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Int32.MaxValue / 4 + 1)] int ByValTStr_e3; [MarshalAs(UnmanagedType.ByValTStr)] int ByValTStr_e4; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1, SizeParamIndex=1)] int ByValTStr_e5; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1, ArraySubType = UnmanagedType.ByValTStr)] int ByValTStr_e6; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1, SafeArraySubType = VarEnum.VT_BSTR)] int ByValTStr_e7; } "; CreateCompilation(source).VerifyDiagnostics( // (9,41): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.ByValTStr, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] int ByValTStr_e1; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "ArraySubType = UnmanagedType.ByValTStr"), // (9,153): error CS0599: Invalid value for named attribute argument 'SizeConst' // [MarshalAs(UnmanagedType.ByValTStr, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] int ByValTStr_e1; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "SizeConst = -1").WithArguments("SizeConst"), // (9,169): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.ByValTStr, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] int ByValTStr_e1; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SizeParamIndex = -1"), // (9,6): error CS7046: Attribute parameter 'SizeConst' must be specified. // [MarshalAs(UnmanagedType.ByValTStr, ArraySubType = UnmanagedType.ByValTStr, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] int ByValTStr_e1; Diagnostic(ErrorCode.ERR_AttributeParameterRequired1, "MarshalAs").WithArguments("SizeConst"), // (10,41): error CS0599: Invalid value for named attribute argument 'SizeConst' // [MarshalAs(UnmanagedType.ByValTStr, SizeConst = -1)] int ByValTStr_e2; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "SizeConst = -1").WithArguments("SizeConst"), // (10,6): error CS7046: Attribute parameter 'SizeConst' must be specified. // [MarshalAs(UnmanagedType.ByValTStr, SizeConst = -1)] int ByValTStr_e2; Diagnostic(ErrorCode.ERR_AttributeParameterRequired1, "MarshalAs").WithArguments("SizeConst"), // (11,41): error CS0599: Invalid value for named attribute argument 'SizeConst' // [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Int32.MaxValue / 4 + 1)] int ByValTStr_e3; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, "SizeConst = Int32.MaxValue / 4 + 1").WithArguments("SizeConst"), // (12,6): error CS7046: Attribute parameter 'SizeConst' must be specified. // [MarshalAs(UnmanagedType.ByValTStr)] int ByValTStr_e4; Diagnostic(ErrorCode.ERR_AttributeParameterRequired1, "MarshalAs").WithArguments("SizeConst"), // (13,56): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1, SizeParamIndex=1)] int ByValTStr_e5; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "SizeParamIndex=1"), // (14,56): error CS7045: Parameter not valid for the specified unmanaged type. // [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1, ArraySubType = UnmanagedType.ByValTStr)] int ByValTStr_e6; Diagnostic(ErrorCode.ERR_ParameterNotValidForType, "ArraySubType = UnmanagedType.ByValTStr")); } /// <summary> /// Custom (MarshalType, MarshalTypeRef, MarshalCookie) one of {MarshalType, MarshalTypeRef} required, others ignored /// </summary> [Fact] public void CustomMarshal() { var source = @" using System; using System.Runtime.InteropServices; public class X { [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = null)] public int CustomMarshaler1; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = null)] public int CustomMarshaler2; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = ""foo"", MarshalTypeRef = typeof(int))] public int CustomMarshaler3; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = ""\u1234f\0oozzz"")] public int CustomMarshaler4; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = ""f\0oozzz"")] public int CustomMarshaler5; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = ""xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"")] public int CustomMarshaler6; [MarshalAs(UnmanagedType.CustomMarshaler, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] public int CustomMarshaler7; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(int))] public int CustomMarshaler8; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(int), MarshalType = ""foo"", MarshalCookie = ""hello\0world(\u1234)"")] public int CustomMarshaler9; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = null, MarshalTypeRef = typeof(int))] public int CustomMarshaler10; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = ""foo"", MarshalTypeRef = null)] public int CustomMarshaler11; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = null, MarshalTypeRef = null)] public int CustomMarshaler12; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = ""aaa\0bbb"", MarshalCookie = ""ccc\0ddd"" )] public int CustomMarshaler13; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = ""\uD869\uDED6"", MarshalCookie = ""\uD869\uDED6"" )] public int CustomMarshaler14; } "; var blobs = new Dictionary<string, byte[]> { { "CustomMarshaler1", new byte[] { 0x2c, 0x00, 0x00, 0x00, 0x00 } }, { "CustomMarshaler2", new byte[] { 0x2c, 0x00, 0x00, 0x00, 0x00 } }, { "CustomMarshaler3", new byte[] { 0x2c, 0x00, 0x00, 0x03, 0x66, 0x6f, 0x6f, 0x00 } }, { "CustomMarshaler4", new byte[] { 0x2c, 0x00, 0x00, 0x0a, 0xe1, 0x88, 0xb4, 0x66, 0x00, 0x6f, 0x6f, 0x7a, 0x7a, 0x7a, 0x00 } }, { "CustomMarshaler5", new byte[] { 0x2c, 0x00, 0x00, 0x07, 0x66, 0x00, 0x6f, 0x6f, 0x7a, 0x7a, 0x7a, 0x00 } }, { "CustomMarshaler6", new byte[] { 0x2c, 0x00, 0x00, 0x60 }.Append(Encoding.UTF8.GetBytes("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\0")) }, { "CustomMarshaler7", new byte[] { 0x2c, 0x00, 0x00, 0x00, 0x00 } }, { "CustomMarshaler8", new byte[] { 0x2c, 0x00, 0x00, 0x59 }.Append(Encoding.UTF8.GetBytes("System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\0")) }, { "CustomMarshaler9", new byte[] { 0x2c, 0x00, 0x00, 0x03, 0x66, 0x6f, 0x6f, 0x10, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x28, 0xe1, 0x88, 0xb4, 0x29 } }, { "CustomMarshaler10", new byte[] { 0x2c, 0x00, 0x00, 0x00, 0x00 } }, { "CustomMarshaler11", new byte[] { 0x2c, 0x00, 0x00, 0x03, 0x66, 0x6f, 0x6f, 0x00 } }, { "CustomMarshaler12", new byte[] { 0x2c, 0x00, 0x00, 0x00, 0x00 } }, { "CustomMarshaler13", new byte[] { 0x2c, 0x00, 0x00, 0x07, 0x61, 0x61, 0x61, 0x00, 0x62, 0x62, 0x62, 0x07, 0x63, 0x63, 0x63, 0x00, 0x64, 0x64, 0x64 } }, { "CustomMarshaler14", new byte[] { 0x2c, 0x00, 0x00, 0x04, 0xf0, 0xaa, 0x9b, 0x96, 0x04, 0xf0, 0xaa, 0x9b, 0x96 } }, }; var verifier = CompileAndVerifyFieldMarshal(source, blobs); VerifyFieldMetadataDecoding(verifier, blobs); } [Fact] public void CustomMarshal_Errors() { var source = @" #pragma warning disable 169 using System.Runtime.InteropServices; public class X { [MarshalAs(UnmanagedType.CustomMarshaler)]int CustomMarshaler_e0; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = ""a\udc00b"", MarshalCookie = ""b"" )]int CustomMarshaler_e1; [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = ""x"", MarshalCookie = ""y\udc00"" )]int CustomMarshaler_e2; } "; // Dev10 encodes incomplete surrogates, we don't. CreateCompilation(source).VerifyDiagnostics( // (8,6): error CS7047: Attribute parameter 'MarshalType' or 'MarshalTypeRef' must be specified. // [MarshalAs(UnmanagedType.CustomMarshaler)]int CustomMarshaler_e0; Diagnostic(ErrorCode.ERR_AttributeParameterRequired2, "MarshalAs").WithArguments("MarshalType", "MarshalTypeRef"), // (9,47): error CS0599: Invalid value for named attribute argument 'MarshalType' // [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "a\udc00b", MarshalCookie = "b" )]int CustomMarshaler_e1; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, @"MarshalType = ""a\udc00b""").WithArguments("MarshalType"), // (10,66): error CS0599: Invalid value for named attribute argument 'MarshalCookie' // [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "x", MarshalCookie = "y\udc00" )]int CustomMarshaler_e2; Diagnostic(ErrorCode.ERR_InvalidNamedArgument, @"MarshalCookie = ""y\udc00""").WithArguments("MarshalCookie")); } [Fact] public void EventAndEnumMembers() { var source = @" using System; using System.Runtime.InteropServices; class C { [field: MarshalAs(UnmanagedType.Bool)] event Action e; } enum E { [MarshalAs(UnmanagedType.Bool)] X = 1 } "; CompileAndVerifyFieldMarshal(source, (name, _omitted1) => (name == "e" || name == "X") ? new byte[] { 0x02 } : null); } #endregion #region Parameters and Return Values [Fact] public void Parameters() { var source = @" using System; using System.Runtime.InteropServices; class X { [return: MarshalAs(UnmanagedType.LPStr)] public static X foo( [MarshalAs(UnmanagedType.IDispatch)] ref int IDispatch, [MarshalAs(UnmanagedType.LPArray)] out int LPArray0, [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_EMPTY)] int SafeArray8, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = ""aaa\0bbb"", MarshalCookie = ""ccc\0ddd"" )] int CustomMarshaler13 ) { throw null; } } "; var blobs = new Dictionary<string, byte[]>() { { "foo:", new byte[] { 0x14 } }, // return value { "foo:IDispatch", new byte[] { 0x1a } }, { "foo:LPArray0", new byte[] { 0x2a, 0x50 } }, { "foo:SafeArray8", new byte[] { 0x1d, 0x00 } }, { "foo:CustomMarshaler13", new byte[] { 0x2c, 0x00, 0x00, 0x07, 0x61, 0x61, 0x61, 0x00, 0x62, 0x62, 0x62, 0x07, 0x63, 0x63, 0x63, 0x00, 0x64, 0x64, 0x64 } }, }; var verifier = CompileAndVerifyFieldMarshal(source, blobs, isField: false); VerifyParameterMetadataDecoding(verifier, blobs); } [Fact] public void Parameters_LocalFunction() { var source = @" using System; using System.Runtime.InteropServices; class X { void M() { [return: MarshalAs(UnmanagedType.LPStr)] static X local( [MarshalAs(UnmanagedType.IDispatch)] ref int IDispatch, [MarshalAs(UnmanagedType.LPArray)] out int LPArray0, [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_EMPTY)] int SafeArray8, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = ""aaa\0bbb"", MarshalCookie = ""ccc\0ddd"" )] int CustomMarshaler13 ) { throw null; } } } "; var blobs = new Dictionary<string, byte[]>() { { "<M>g__local|0_0:", new byte[] { 0x14 } }, // return value { "<M>g__local|0_0:IDispatch", new byte[] { 0x1a } }, { "<M>g__local|0_0:LPArray0", new byte[] { 0x2a, 0x50 } }, { "<M>g__local|0_0:SafeArray8", new byte[] { 0x1d, 0x00 } }, { "<M>g__local|0_0:CustomMarshaler13", new byte[] { 0x2c, 0x00, 0x00, 0x07, 0x61, 0x61, 0x61, 0x00, 0x62, 0x62, 0x62, 0x07, 0x63, 0x63, 0x63, 0x00, 0x64, 0x64, 0x64 } }, }; var verifier = CompileAndVerifyFieldMarshal(source, blobs, isField: false); VerifyParameterMetadataDecoding(verifier, blobs); } [Fact] public void MarshalAs_AllParameterTargets_PartialMethods() { var source = @" using System; using System.Runtime.InteropServices; public partial class X { partial void F([MarshalAs(UnmanagedType.BStr)] int pf); partial void F(int pf) { } partial void G(int pg); partial void G([MarshalAs(UnmanagedType.BStr)] int pg) {} partial void H([MarshalAs(UnmanagedType.BStr)] int ph) {} partial void H(int ph); partial void I(int pi) { } partial void I([MarshalAs(UnmanagedType.BStr)] int pi); } "; var blobs = new Dictionary<string, byte[]>() { {"F:pf", new byte[] {0x13}}, {"G:pg", new byte[] {0x13}}, {"H:ph", new byte[] {0x13}}, {"I:pi", new byte[] {0x13}}, }; CompileAndVerifyFieldMarshal(source, blobs, isField: false); } [WorkItem(544508, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544508")] [Fact] public void Parameters_Property_Accessors() { var source = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; public interface I { string P { [return: MarshalAs(UnmanagedType.BStr)] get; [param: MarshalAs(UnmanagedType.BStr)] set; } }"; CompileAndVerifyFieldMarshal(source, new Dictionary<string, byte[]>() { { "get_P:", new byte[] { 0x13 } }, // return value for get accessor { "set_P:" + ParameterSymbol.ValueParameterName, new byte[] { 0x13 } }, // value parameter for set accessor }, isField: false); } [WorkItem(544508, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544508")] [Fact] public void Parameters_Event_Accessors() { var source = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; class C { event Action<string> E { [param: MarshalAs(UnmanagedType.BStr)] add { } [param: MarshalAs(UnmanagedType.BStr)] remove { } } }"; CompileAndVerifyFieldMarshal(source, new Dictionary<string, byte[]>() { { "add_E:" + ParameterSymbol.ValueParameterName, new byte[] { 0x13 } }, { "remove_E:" + ParameterSymbol.ValueParameterName, new byte[] { 0x13 } }, }, isField: false); } [Fact] public void Parameters_Indexer_Getter() { var source = @" using System.Runtime.InteropServices; public class C { public int this[[MarshalAs(UnmanagedType.BStr)]int a, [MarshalAs(UnmanagedType.BStr)]int b] { get { return 0; } } } "; CompileAndVerifyFieldMarshal(source, new Dictionary<string, byte[]>() { { "get_Item:a", new byte[] { 0x13 } }, { "get_Item:b", new byte[] { 0x13 } }, }, isField: false); } [Fact] public void Parameters_Indexer_Setter() { var source = @" using System.Runtime.InteropServices; public class C { public int this[[MarshalAs(UnmanagedType.BStr)]int a, [MarshalAs(UnmanagedType.BStr)]int b] { [param: MarshalAs(UnmanagedType.BStr)] set { } } } "; CompileAndVerifyFieldMarshal(source, new Dictionary<string, byte[]>() { { "set_Item:" + ParameterSymbol.ValueParameterName, new byte[] { 0x13 } }, { "set_Item:a", new byte[] { 0x13 } }, { "set_Item:b", new byte[] { 0x13 } }, }, isField: false); } [WorkItem(544509, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544509")] [Fact] public void Parameters_DelegateType() { var source = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; class C { [return: MarshalAs(UnmanagedType.BStr)] public delegate string Delegate( [In, MarshalAs(UnmanagedType.BStr)]string p1, [param: In, Out, MarshalAs(UnmanagedType.BStr)]ref string p2, [Out, MarshalAs(UnmanagedType.BStr)]out string p3); }"; var marshalAsBstr = new byte[] { 0x13 }; CompileAndVerifyFieldMarshal(source, new Dictionary<string, byte[]>() { { ".ctor:object", null }, { ".ctor:method", null }, { "Invoke:", marshalAsBstr}, // return value { "Invoke:p1", marshalAsBstr }, { "Invoke:p2", marshalAsBstr }, { "Invoke:p3", marshalAsBstr }, { "BeginInvoke:p1", marshalAsBstr }, { "BeginInvoke:p2", marshalAsBstr }, { "BeginInvoke:p3", marshalAsBstr }, { "BeginInvoke:object", null }, { "BeginInvoke:callback", null }, { "EndInvoke:", marshalAsBstr }, { "EndInvoke:p1", marshalAsBstr }, { "EndInvoke:p2", marshalAsBstr }, { "EndInvoke:p3", marshalAsBstr }, { "EndInvoke:result", null }, }, isField: false); } [Fact] public void Parameters_Errors() { var source = @" #pragma warning disable 169 using System.Runtime.InteropServices; class X { public static void f1( [MarshalAs(UnmanagedType.ByValArray)] int ByValArray, [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)] int ByValTStr ) { } [return: MarshalAs(UnmanagedType.ByValArray)] public static int f2() { return 0; } [return: MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)] public static int f3() { return 0; } [MarshalAs(UnmanagedType.VBByRefStr)] public int field; } "; CreateCompilation(source).VerifyDiagnostics( // (7,20): error CS7055: Unmanaged type 'ByValArray' is only valid for fields. Diagnostic(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValArray").WithArguments("ByValArray"), // (10,20): error CS7055: Unmanaged type 'ByValTStr' is only valid for fields. Diagnostic(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValTStr").WithArguments("ByValTStr"), // (16,24): error CS7055: Unmanaged type 'ByValArray' is only valid for fields. Diagnostic(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValArray").WithArguments("ByValArray"), // (19,24): error CS7055: Unmanaged type 'ByValTStr' is only valid for fields. Diagnostic(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValTStr").WithArguments("ByValTStr"), // (22,16): error CS7054: Unmanaged type 'VBByRefStr' not valid for fields. Diagnostic(ErrorCode.ERR_MarshalUnmanagedTypeNotValidForFields, "UnmanagedType.VBByRefStr").WithArguments("VBByRefStr"), // TODO (tomat): remove // (23,16): warning CS0649: Field 'X.field' is never assigned to, and will always have its default value 0 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("X.field", "0")); } [Fact] public void Parameters_Errors_LocalFunction() { var source = @" #pragma warning disable 8321 // Unreferenced local function using System.Runtime.InteropServices; class X { void M() { static void f1( [MarshalAs(UnmanagedType.ByValArray)] int ByValArray, [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)] int ByValTStr ) { } [return: MarshalAs(UnmanagedType.ByValArray)] static int f2() { return 0; } [return: MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)] static int f3() { return 0; } } } "; CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (11,24): error CS7055: Unmanaged type 'ByValArray' is only valid for fields. // [MarshalAs(UnmanagedType.ByValArray)] Diagnostic(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValArray").WithArguments("ByValArray").WithLocation(11, 24), // (14,24): error CS7055: Unmanaged type 'ByValTStr' is only valid for fields. // [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)] Diagnostic(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValTStr").WithArguments("ByValTStr").WithLocation(14, 24), // (20,28): error CS7055: Unmanaged type 'ByValArray' is only valid for fields. // [return: MarshalAs(UnmanagedType.ByValArray)] Diagnostic(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValArray").WithArguments("ByValArray").WithLocation(20, 28), // (23,28): error CS7055: Unmanaged type 'ByValTStr' is only valid for fields. // [return: MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)] Diagnostic(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, "UnmanagedType.ByValTStr").WithArguments("ByValTStr").WithLocation(23, 28)); } /// <summary> /// type only, only on parameters /// </summary> [Fact] public void NativeTypeByValStr() { var source = @" using System; using System.Runtime.InteropServices; class X { [return: MarshalAs(UnmanagedType.VBByRefStr, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] static void f( [MarshalAs(UnmanagedType.VBByRefStr, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] ref int VBByRefStr_e1, [MarshalAs(UnmanagedType.VBByRefStr, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] char[] VBByRefStr_e2, [MarshalAs(UnmanagedType.VBByRefStr, ArraySubType = UnmanagedType.ByValTStr, IidParameterIndex = -1, MarshalCookie = null, MarshalType = null, MarshalTypeRef = null, SafeArraySubType = VarEnum.VT_BSTR, SafeArrayUserDefinedSubType = null, SizeConst = -1, SizeParamIndex = -1)] int VBByRefStr_e3) { } } "; CompileAndVerifyFieldMarshal(source, new Dictionary<string, byte[]> { { "f:", new byte[] { 0x22 } }, // return value { "f:VBByRefStr_e1", new byte[] { 0x22 } }, { "f:VBByRefStr_e2", new byte[] { 0x22 } }, { "f:VBByRefStr_e3", new byte[] { 0x22 } }, }, isField: false); } [Fact, WorkItem(545374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545374")] public void ImportOptionalMarshalAsParameter() { string text1 = @" using System.Runtime.InteropServices; public class P2<T> { public int Foo([Optional][MarshalAs(UnmanagedType.IDispatch)] T i) { if (i == null) return 0; return 1; } } "; string text2 = @" class C { public static void Main() { P2<object> p2 = new P2<object>(); System.Console.WriteLine(p2.Foo()); } } "; var comp1 = CreateCompilation(text1, assemblyName: "OptionalMarshalAsLibrary"); var comp2 = CreateCompilation(text2, options: TestOptions.ReleaseExe, references: new[] { comp1.EmitToImageReference() }, // it has to be real assembly, Comp2comp reference OK assemblyName: "APP"); CompileAndVerify(comp2, expectedOutput: @"0").VerifyIL("C.Main", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: newobj ""P2<object>..ctor()"" IL_0005: ldnull IL_0006: callvirt ""int P2<object>.Foo(object)"" IL_000b: call ""void System.Console.WriteLine(int)"" IL_0010: ret } "); } #endregion } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Features/Core/Portable/AddImport/SymbolReferenceFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolSearch; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Shared.Utilities.EditorBrowsableHelpers; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> { private partial class SymbolReferenceFinder { private const string AttributeSuffix = nameof(Attribute); private readonly string _diagnosticId; private readonly Document _document; private readonly SemanticModel _semanticModel; private readonly ISet<INamespaceSymbol> _namespacesInScope; private readonly ISyntaxFactsService _syntaxFacts; private readonly AbstractAddImportFeatureService<TSimpleNameSyntax> _owner; private readonly SyntaxNode _node; private readonly ISymbolSearchService _symbolSearchService; private readonly bool _searchReferenceAssemblies; private readonly ImmutableArray<PackageSource> _packageSources; public SymbolReferenceFinder( AbstractAddImportFeatureService<TSimpleNameSyntax> owner, Document document, SemanticModel semanticModel, string diagnosticId, SyntaxNode node, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { _owner = owner; _document = document; _semanticModel = semanticModel; _diagnosticId = diagnosticId; _node = node; _symbolSearchService = symbolSearchService; _searchReferenceAssemblies = searchReferenceAssemblies; _packageSources = packageSources; if (_searchReferenceAssemblies || packageSources.Length > 0) { Contract.ThrowIfNull(symbolSearchService); } _syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); _namespacesInScope = GetNamespacesInScope(cancellationToken); } private ISet<INamespaceSymbol> GetNamespacesInScope(CancellationToken cancellationToken) { // Add all the namespaces brought in by imports/usings. var set = _owner.GetImportNamespacesInScope(_semanticModel, _node, cancellationToken); // Also add all the namespaces we're contained in. We don't want // to add imports for these namespaces either. for (var containingNamespace = _semanticModel.GetEnclosingNamespace(_node.SpanStart, cancellationToken); containingNamespace != null; containingNamespace = containingNamespace.ContainingNamespace) { set.Add(MapToCompilationNamespaceIfPossible(containingNamespace)); } return set; } private INamespaceSymbol MapToCompilationNamespaceIfPossible(INamespaceSymbol containingNamespace) => _semanticModel.Compilation.GetCompilationNamespace(containingNamespace) ?? containingNamespace; internal Task<ImmutableArray<SymbolReference>> FindInAllSymbolsInStartingProjectAsync( bool exact, CancellationToken cancellationToken) { var searchScope = new AllSymbolsProjectSearchScope( _owner, _document.Project, exact, cancellationToken); return DoAsync(searchScope); } internal Task<ImmutableArray<SymbolReference>> FindInSourceSymbolsInProjectAsync( ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>> projectToAssembly, Project project, bool exact, CancellationToken cancellationToken) { var searchScope = new SourceSymbolsProjectSearchScope( _owner, projectToAssembly, project, exact, cancellationToken); return DoAsync(searchScope); } internal Task<ImmutableArray<SymbolReference>> FindInMetadataSymbolsAsync( IAssemblySymbol assembly, ProjectId assemblyProjectId, PortableExecutableReference metadataReference, bool exact, CancellationToken cancellationToken) { var searchScope = new MetadataSymbolsSearchScope( _owner, _document.Project.Solution, assembly, assemblyProjectId, metadataReference, exact, cancellationToken); return DoAsync(searchScope); } private async Task<ImmutableArray<SymbolReference>> DoAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); // Spin off tasks to do all our searching in parallel using var _1 = ArrayBuilder<Task<ImmutableArray<SymbolReference>>>.GetInstance(out var tasks); tasks.Add(GetReferencesForMatchingTypesAsync(searchScope)); tasks.Add(GetReferencesForMatchingNamespacesAsync(searchScope)); tasks.Add(GetReferencesForMatchingFieldsAndPropertiesAsync(searchScope)); tasks.Add(GetReferencesForMatchingExtensionMethodsAsync(searchScope)); // Searching for things like "Add" (for collection initializers) and "Select" // (for extension methods) should only be done when doing an 'exact' search. // We should not do fuzzy searches for these names. In this case it's not // like the user was writing Add or Select, but instead we're looking for // viable symbols with those names to make a collection initializer or // query expression valid. if (searchScope.Exact) { tasks.Add(GetReferencesForCollectionInitializerMethodsAsync(searchScope)); tasks.Add(GetReferencesForQueryPatternsAsync(searchScope)); tasks.Add(GetReferencesForDeconstructAsync(searchScope)); tasks.Add(GetReferencesForGetAwaiterAsync(searchScope)); tasks.Add(GetReferencesForGetEnumeratorAsync(searchScope)); tasks.Add(GetReferencesForGetAsyncEnumeratorAsync(searchScope)); } await Task.WhenAll(tasks).ConfigureAwait(false); searchScope.CancellationToken.ThrowIfCancellationRequested(); using var _2 = ArrayBuilder<SymbolReference>.GetInstance(out var allReferences); foreach (var task in tasks) { var taskResult = await task.ConfigureAwait(false); allReferences.AddRange(taskResult); } return DeDupeAndSortReferences(allReferences.ToImmutable()); } private ImmutableArray<SymbolReference> DeDupeAndSortReferences(ImmutableArray<SymbolReference> allReferences) { return allReferences .Distinct() .Where(NotNull) .Where(NotGlobalNamespace) .OrderBy((r1, r2) => r1.CompareTo(_document, r2)) .ToImmutableArray(); } private static void CalculateContext( TSimpleNameSyntax nameNode, ISyntaxFactsService syntaxFacts, out string name, out int arity, out bool inAttributeContext, out bool hasIncompleteParentMember, out bool looksGeneric) { // Has to be a simple identifier or generic name. syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out name, out arity); inAttributeContext = syntaxFacts.IsAttributeName(nameNode); hasIncompleteParentMember = syntaxFacts.HasIncompleteParentMember(nameNode); looksGeneric = syntaxFacts.LooksGeneric(nameNode); } /// <summary> /// Searches for types that match the name the user has written. Returns <see cref="SymbolReference"/>s /// to the <see cref="INamespaceSymbol"/>s or <see cref="INamedTypeSymbol"/>s those types are /// contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingTypesAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (!_owner.CanAddImportForType(_diagnosticId, _node, out var nameNode)) { return ImmutableArray<SymbolReference>.Empty; } CalculateContext( nameNode, _syntaxFacts, out var name, out var arity, out var inAttributeContext, out var hasIncompleteParentMember, out var looksGeneric); if (ExpressionBinds(nameNode, checkForExtensionMethods: false, cancellationToken: searchScope.CancellationToken)) { // If the expression bound, there's nothing to do. return ImmutableArray<SymbolReference>.Empty; } var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Type).ConfigureAwait(false); // also lookup type symbols with the "Attribute" suffix if necessary. if (inAttributeContext) { var attributeSymbols = await searchScope.FindDeclarationsAsync(name + AttributeSuffix, nameNode, SymbolFilter.Type).ConfigureAwait(false); symbols = symbols.AddRange( attributeSymbols.Select(r => r.WithDesiredName(r.DesiredName.GetWithoutAttributeSuffix(isCaseSensitive: false)))); } var typeSymbols = OfType<ITypeSymbol>(symbols); var options = await _document.GetOptionsAsync(searchScope.CancellationToken).ConfigureAwait(false); var hideAdvancedMembers = options.GetOption(CompletionOptions.HideAdvancedMembers); var editorBrowserInfo = new EditorBrowsableInfo(_semanticModel.Compilation); // Only keep symbols which are accessible from the current location and that are allowed by the current // editor browsable rules. var accessibleTypeSymbols = typeSymbols.WhereAsArray( s => ArityAccessibilityAndAttributeContextAreCorrect(s.Symbol, arity, inAttributeContext, hasIncompleteParentMember, looksGeneric) && s.Symbol.IsEditorBrowsable(hideAdvancedMembers, _semanticModel.Compilation, editorBrowserInfo)); // These types may be contained within namespaces, or they may be nested // inside generic types. Record these namespaces/types if it would be // legal to add imports for them. var typesContainedDirectlyInNamespaces = accessibleTypeSymbols.WhereAsArray(s => s.Symbol.ContainingSymbol is INamespaceSymbol); var typesContainedDirectlyInTypes = accessibleTypeSymbols.WhereAsArray(s => s.Symbol.ContainingType != null); var namespaceReferences = GetNamespaceSymbolReferences(searchScope, typesContainedDirectlyInNamespaces.SelectAsArray(r => r.WithSymbol(r.Symbol.ContainingNamespace))); var typeReferences = typesContainedDirectlyInTypes.SelectAsArray( r => searchScope.CreateReference(r.WithSymbol(r.Symbol.ContainingType))); return namespaceReferences.Concat(typeReferences); } private bool ArityAccessibilityAndAttributeContextAreCorrect( ITypeSymbol symbol, int arity, bool inAttributeContext, bool hasIncompleteParentMember, bool looksGeneric) { if (inAttributeContext && !symbol.IsAttribute()) { return false; } if (!symbol.IsAccessibleWithin(_semanticModel.Compilation.Assembly)) { return false; } if (looksGeneric && symbol.GetTypeArguments().Length == 0) { return false; } return arity == 0 || symbol.GetArity() == arity || hasIncompleteParentMember; } /// <summary> /// Searches for namespaces that match the name the user has written. Returns <see cref="SymbolReference"/>s /// to the <see cref="INamespaceSymbol"/>s those namespaces are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingNamespacesAsync( SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForNamespace(_diagnosticId, _node, out var nameNode)) { _syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out var name, out var arity); if (arity == 0 && !ExpressionBinds(nameNode, checkForExtensionMethods: false, cancellationToken: searchScope.CancellationToken)) { var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Namespace).ConfigureAwait(false); var namespaceSymbols = OfType<INamespaceSymbol>(symbols); var containingNamespaceSymbols = OfType<INamespaceSymbol>(symbols).SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, containingNamespaceSymbols); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Specialized finder for the "Color Color" case. Used when we have "Color.Black" and "Color" /// bound to a Field/Property, but not a type. In this case, we want to look for namespaces /// containing 'Color' as if we import them it can resolve this issue. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingFieldsAndPropertiesAsync( SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out var nameNode) && nameNode != null) { // We have code like "Color.Black". "Color" bound to a 'Color Color' property, and // 'Black' did not bind. We want to find a type called 'Color' that will actually // allow 'Black' to bind. var syntaxFacts = _document.GetLanguageService<ISyntaxFactsService>(); if (syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameNode) || syntaxFacts.IsNameOfMemberBindingExpression(nameNode)) { var expression = syntaxFacts.GetExpressionOfMemberAccessExpression(nameNode.Parent, allowImplicitTarget: true) ?? syntaxFacts.GetTargetOfMemberBinding(nameNode.Parent); if (expression is TSimpleNameSyntax) { // Check if the expression before the dot binds to a property or field. var symbol = _semanticModel.GetSymbolInfo(expression, searchScope.CancellationToken).GetAnySymbol(); if (symbol?.Kind is SymbolKind.Property or SymbolKind.Field) { // Check if we have the 'Color Color' case. var propertyOrFieldType = symbol.GetSymbolType(); if (propertyOrFieldType is INamedTypeSymbol propertyType && Equals(propertyType.Name, symbol.Name)) { // Try to look up 'Color' as a type. var symbolResults = await searchScope.FindDeclarationsAsync( symbol.Name, (TSimpleNameSyntax)expression, SymbolFilter.Type).ConfigureAwait(false); // Return results that have accessible members. var namedTypeSymbols = OfType<INamedTypeSymbol>(symbolResults); var name = nameNode.GetFirstToken().ValueText; var namespaceResults = namedTypeSymbols.WhereAsArray(sr => HasAccessibleStaticFieldOrProperty(sr.Symbol, name)) .SelectAsArray(sr => sr.WithSymbol(sr.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceResults); } } } } } return ImmutableArray<SymbolReference>.Empty; } private bool HasAccessibleStaticFieldOrProperty(INamedTypeSymbol namedType, string fieldOrPropertyName) { return namedType.GetMembers(fieldOrPropertyName) .Any(m => (m is IFieldSymbol || m is IPropertySymbol) && m.IsStatic && m.IsAccessibleWithin(_semanticModel.Compilation.Assembly)); } /// <summary> /// Searches for extension methods that match the name the user has written. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingExtensionMethodsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out var nameNode) && nameNode != null) { searchScope.CancellationToken.ThrowIfCancellationRequested(); // See if the name binds. If it does, there's nothing further we need to do. if (!ExpressionBinds(nameNode, checkForExtensionMethods: true, cancellationToken: searchScope.CancellationToken)) { _syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out var name, out var arity); if (name != null) { var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Member).ConfigureAwait(false); var methodSymbols = OfType<IMethodSymbol>(symbols); var extensionMethodSymbols = GetViableExtensionMethods( methodSymbols, nameNode.Parent, searchScope.CancellationToken); var namespaceSymbols = extensionMethodSymbols.SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceSymbols); } } } return ImmutableArray<SymbolReference>.Empty; } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethods( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols, SyntaxNode expression, CancellationToken cancellationToken) { return GetViableExtensionMethodsWorker(methodSymbols).WhereAsArray( s => _owner.IsViableExtensionMethod(s.Symbol, expression, _semanticModel, _syntaxFacts, cancellationToken)); } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethods( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols, ITypeSymbol typeSymbol) { return GetViableExtensionMethodsWorker(methodSymbols).WhereAsArray( s => IsViableExtensionMethod(s.Symbol, typeSymbol)); } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethodsWorker( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols) { return methodSymbols.WhereAsArray( s => s.Symbol.IsExtensionMethod && s.Symbol.IsAccessibleWithin(_semanticModel.Compilation.Assembly)); } /// <summary> /// Searches for extension methods exactly called 'Add'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForCollectionInitializerMethodsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (!_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out var nameNode)) { return ImmutableArray<SymbolReference>.Empty; } _syntaxFacts.GetNameAndArityOfSimpleName(_node, out var name, out var arity); if (name != null || !_owner.IsAddMethodContext(_node, _semanticModel)) { return ImmutableArray<SymbolReference>.Empty; } var symbols = await searchScope.FindDeclarationsAsync( nameof(IList.Add), nameNode: null, filter: SymbolFilter.Member).ConfigureAwait(false); // Note: there is no desiredName for these search results. We're searching for // extension methods called "Add", but we have no intention of renaming any // of the existing user code to that name. var methodSymbols = OfType<IMethodSymbol>(symbols).SelectAsArray(s => s.WithDesiredName(null)); var viableMethods = GetViableExtensionMethods( methodSymbols, _node.Parent, searchScope.CancellationToken); return GetNamespaceSymbolReferences(searchScope, viableMethods.SelectAsArray(m => m.WithSymbol(m.Symbol.ContainingNamespace))); } /// <summary> /// Searches for extension methods exactly called 'Select'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForQueryPatternsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForQuery(_diagnosticId, _node)) { var type = _owner.GetQueryClauseInfo(_semanticModel, _node, searchScope.CancellationToken); if (type != null) { // find extension methods named "Select" return await GetReferencesForExtensionMethodAsync( searchScope, nameof(Enumerable.Select), type).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetAwaiter'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetAwaiterAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetAwaiter(_diagnosticId, _syntaxFacts, _node)) { var type = GetAwaitInfo(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetAwaiter, type, m => m.IsValidGetAwaiter()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetEnumerator'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetEnumeratorAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetEnumerator(_diagnosticId, _syntaxFacts, _node)) { var type = GetCollectionExpressionType(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetEnumeratorMethodName, type, m => m.IsValidGetEnumerator()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetAsyncEnumerator'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetAsyncEnumeratorAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetAsyncEnumerator(_diagnosticId, _syntaxFacts, _node)) { var type = GetCollectionExpressionType(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetAsyncEnumeratorMethodName, type, m => m.IsValidGetAsyncEnumerator()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'Deconstruct'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForDeconstructAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForDeconstruct(_diagnosticId, _node)) { var type = _owner.GetDeconstructInfo(_semanticModel, _node, searchScope.CancellationToken); if (type != null) { // Note: we could check that the extension methods have the right number of out-params. // But that would involve figuring out what we're trying to deconstruct into. For now // we'll just be permissive, with the assumption that there won't be that many matching // 'Deconstruct' extension methods for the type of node that we're on. return await GetReferencesForExtensionMethodAsync( searchScope, "Deconstruct", type, m => m.ReturnsVoid).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } private async Task<ImmutableArray<SymbolReference>> GetReferencesForExtensionMethodAsync( SearchScope searchScope, string name, ITypeSymbol type, Func<IMethodSymbol, bool> predicate = null) { var symbols = await searchScope.FindDeclarationsAsync( name, nameNode: null, filter: SymbolFilter.Member).ConfigureAwait(false); // Note: there is no "desiredName" when doing this. We're not going to do any // renames of the user code. We're just looking for an extension method called // "Select", but that name has no bearing on the code in question that we're // trying to fix up. var methodSymbols = OfType<IMethodSymbol>(symbols).SelectAsArray(s => s.WithDesiredName(null)); var viableExtensionMethods = GetViableExtensionMethods(methodSymbols, type); if (predicate != null) { viableExtensionMethods = viableExtensionMethods.WhereAsArray(s => predicate(s.Symbol)); } var namespaceSymbols = viableExtensionMethods.SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceSymbols); } protected bool ExpressionBinds( TSimpleNameSyntax nameNode, bool checkForExtensionMethods, CancellationToken cancellationToken) { // See if the name binds to something other then the error type. If it does, there's nothing further we need to do. // For extension methods, however, we will continue to search if there exists any better matched method. cancellationToken.ThrowIfCancellationRequested(); var symbolInfo = _semanticModel.GetSymbolInfo(nameNode, cancellationToken); if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure && !checkForExtensionMethods) { return true; } return symbolInfo.Symbol != null; } private ImmutableArray<SymbolReference> GetNamespaceSymbolReferences( SearchScope scope, ImmutableArray<SymbolResult<INamespaceSymbol>> namespaces) { using var _ = ArrayBuilder<SymbolReference>.GetInstance(out var references); foreach (var namespaceResult in namespaces) { var symbol = namespaceResult.Symbol; var mappedResult = namespaceResult.WithSymbol(MapToCompilationNamespaceIfPossible(namespaceResult.Symbol)); var namespaceIsInScope = _namespacesInScope.Contains(mappedResult.Symbol); if (!symbol.IsGlobalNamespace && !namespaceIsInScope) references.Add(scope.CreateReference(mappedResult)); } return references.ToImmutable(); } private static ImmutableArray<SymbolResult<T>> OfType<T>(ImmutableArray<SymbolResult<ISymbol>> symbols) where T : ISymbol { return symbols.WhereAsArray(s => s.Symbol is T) .SelectAsArray(s => s.WithSymbol((T)s.Symbol)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolSearch; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Shared.Utilities.EditorBrowsableHelpers; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> { private partial class SymbolReferenceFinder { private const string AttributeSuffix = nameof(Attribute); private readonly string _diagnosticId; private readonly Document _document; private readonly SemanticModel _semanticModel; private readonly ISet<INamespaceSymbol> _namespacesInScope; private readonly ISyntaxFactsService _syntaxFacts; private readonly AbstractAddImportFeatureService<TSimpleNameSyntax> _owner; private readonly SyntaxNode _node; private readonly ISymbolSearchService _symbolSearchService; private readonly bool _searchReferenceAssemblies; private readonly ImmutableArray<PackageSource> _packageSources; public SymbolReferenceFinder( AbstractAddImportFeatureService<TSimpleNameSyntax> owner, Document document, SemanticModel semanticModel, string diagnosticId, SyntaxNode node, ISymbolSearchService symbolSearchService, bool searchReferenceAssemblies, ImmutableArray<PackageSource> packageSources, CancellationToken cancellationToken) { _owner = owner; _document = document; _semanticModel = semanticModel; _diagnosticId = diagnosticId; _node = node; _symbolSearchService = symbolSearchService; _searchReferenceAssemblies = searchReferenceAssemblies; _packageSources = packageSources; if (_searchReferenceAssemblies || packageSources.Length > 0) { Contract.ThrowIfNull(symbolSearchService); } _syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); _namespacesInScope = GetNamespacesInScope(cancellationToken); } private ISet<INamespaceSymbol> GetNamespacesInScope(CancellationToken cancellationToken) { // Add all the namespaces brought in by imports/usings. var set = _owner.GetImportNamespacesInScope(_semanticModel, _node, cancellationToken); // Also add all the namespaces we're contained in. We don't want // to add imports for these namespaces either. for (var containingNamespace = _semanticModel.GetEnclosingNamespace(_node.SpanStart, cancellationToken); containingNamespace != null; containingNamespace = containingNamespace.ContainingNamespace) { set.Add(MapToCompilationNamespaceIfPossible(containingNamespace)); } return set; } private INamespaceSymbol MapToCompilationNamespaceIfPossible(INamespaceSymbol containingNamespace) => _semanticModel.Compilation.GetCompilationNamespace(containingNamespace) ?? containingNamespace; internal Task<ImmutableArray<SymbolReference>> FindInAllSymbolsInStartingProjectAsync( bool exact, CancellationToken cancellationToken) { var searchScope = new AllSymbolsProjectSearchScope( _owner, _document.Project, exact, cancellationToken); return DoAsync(searchScope); } internal Task<ImmutableArray<SymbolReference>> FindInSourceSymbolsInProjectAsync( ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>> projectToAssembly, Project project, bool exact, CancellationToken cancellationToken) { var searchScope = new SourceSymbolsProjectSearchScope( _owner, projectToAssembly, project, exact, cancellationToken); return DoAsync(searchScope); } internal Task<ImmutableArray<SymbolReference>> FindInMetadataSymbolsAsync( IAssemblySymbol assembly, ProjectId assemblyProjectId, PortableExecutableReference metadataReference, bool exact, CancellationToken cancellationToken) { var searchScope = new MetadataSymbolsSearchScope( _owner, _document.Project.Solution, assembly, assemblyProjectId, metadataReference, exact, cancellationToken); return DoAsync(searchScope); } private async Task<ImmutableArray<SymbolReference>> DoAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); // Spin off tasks to do all our searching in parallel using var _1 = ArrayBuilder<Task<ImmutableArray<SymbolReference>>>.GetInstance(out var tasks); tasks.Add(GetReferencesForMatchingTypesAsync(searchScope)); tasks.Add(GetReferencesForMatchingNamespacesAsync(searchScope)); tasks.Add(GetReferencesForMatchingFieldsAndPropertiesAsync(searchScope)); tasks.Add(GetReferencesForMatchingExtensionMethodsAsync(searchScope)); // Searching for things like "Add" (for collection initializers) and "Select" // (for extension methods) should only be done when doing an 'exact' search. // We should not do fuzzy searches for these names. In this case it's not // like the user was writing Add or Select, but instead we're looking for // viable symbols with those names to make a collection initializer or // query expression valid. if (searchScope.Exact) { tasks.Add(GetReferencesForCollectionInitializerMethodsAsync(searchScope)); tasks.Add(GetReferencesForQueryPatternsAsync(searchScope)); tasks.Add(GetReferencesForDeconstructAsync(searchScope)); tasks.Add(GetReferencesForGetAwaiterAsync(searchScope)); tasks.Add(GetReferencesForGetEnumeratorAsync(searchScope)); tasks.Add(GetReferencesForGetAsyncEnumeratorAsync(searchScope)); } await Task.WhenAll(tasks).ConfigureAwait(false); searchScope.CancellationToken.ThrowIfCancellationRequested(); using var _2 = ArrayBuilder<SymbolReference>.GetInstance(out var allReferences); foreach (var task in tasks) { var taskResult = await task.ConfigureAwait(false); allReferences.AddRange(taskResult); } return DeDupeAndSortReferences(allReferences.ToImmutable()); } private ImmutableArray<SymbolReference> DeDupeAndSortReferences(ImmutableArray<SymbolReference> allReferences) { return allReferences .Distinct() .Where(NotNull) .Where(NotGlobalNamespace) .OrderBy((r1, r2) => r1.CompareTo(_document, r2)) .ToImmutableArray(); } private static void CalculateContext( TSimpleNameSyntax nameNode, ISyntaxFactsService syntaxFacts, out string name, out int arity, out bool inAttributeContext, out bool hasIncompleteParentMember, out bool looksGeneric) { // Has to be a simple identifier or generic name. syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out name, out arity); inAttributeContext = syntaxFacts.IsAttributeName(nameNode); hasIncompleteParentMember = syntaxFacts.HasIncompleteParentMember(nameNode); looksGeneric = syntaxFacts.LooksGeneric(nameNode); } /// <summary> /// Searches for types that match the name the user has written. Returns <see cref="SymbolReference"/>s /// to the <see cref="INamespaceSymbol"/>s or <see cref="INamedTypeSymbol"/>s those types are /// contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingTypesAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (!_owner.CanAddImportForType(_diagnosticId, _node, out var nameNode)) { return ImmutableArray<SymbolReference>.Empty; } CalculateContext( nameNode, _syntaxFacts, out var name, out var arity, out var inAttributeContext, out var hasIncompleteParentMember, out var looksGeneric); if (ExpressionBinds(nameNode, checkForExtensionMethods: false, cancellationToken: searchScope.CancellationToken)) { // If the expression bound, there's nothing to do. return ImmutableArray<SymbolReference>.Empty; } var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Type).ConfigureAwait(false); // also lookup type symbols with the "Attribute" suffix if necessary. if (inAttributeContext) { var attributeSymbols = await searchScope.FindDeclarationsAsync(name + AttributeSuffix, nameNode, SymbolFilter.Type).ConfigureAwait(false); symbols = symbols.AddRange( attributeSymbols.Select(r => r.WithDesiredName(r.DesiredName.GetWithoutAttributeSuffix(isCaseSensitive: false)))); } var typeSymbols = OfType<ITypeSymbol>(symbols); var options = await _document.GetOptionsAsync(searchScope.CancellationToken).ConfigureAwait(false); var hideAdvancedMembers = options.GetOption(CompletionOptions.HideAdvancedMembers); var editorBrowserInfo = new EditorBrowsableInfo(_semanticModel.Compilation); // Only keep symbols which are accessible from the current location and that are allowed by the current // editor browsable rules. var accessibleTypeSymbols = typeSymbols.WhereAsArray( s => ArityAccessibilityAndAttributeContextAreCorrect(s.Symbol, arity, inAttributeContext, hasIncompleteParentMember, looksGeneric) && s.Symbol.IsEditorBrowsable(hideAdvancedMembers, _semanticModel.Compilation, editorBrowserInfo)); // These types may be contained within namespaces, or they may be nested // inside generic types. Record these namespaces/types if it would be // legal to add imports for them. var typesContainedDirectlyInNamespaces = accessibleTypeSymbols.WhereAsArray(s => s.Symbol.ContainingSymbol is INamespaceSymbol); var typesContainedDirectlyInTypes = accessibleTypeSymbols.WhereAsArray(s => s.Symbol.ContainingType != null); var namespaceReferences = GetNamespaceSymbolReferences(searchScope, typesContainedDirectlyInNamespaces.SelectAsArray(r => r.WithSymbol(r.Symbol.ContainingNamespace))); var typeReferences = typesContainedDirectlyInTypes.SelectAsArray( r => searchScope.CreateReference(r.WithSymbol(r.Symbol.ContainingType))); return namespaceReferences.Concat(typeReferences); } private bool ArityAccessibilityAndAttributeContextAreCorrect( ITypeSymbol symbol, int arity, bool inAttributeContext, bool hasIncompleteParentMember, bool looksGeneric) { if (inAttributeContext && !symbol.IsAttribute()) { return false; } if (!symbol.IsAccessibleWithin(_semanticModel.Compilation.Assembly)) { return false; } if (looksGeneric && symbol.GetTypeArguments().Length == 0) { return false; } return arity == 0 || symbol.GetArity() == arity || hasIncompleteParentMember; } /// <summary> /// Searches for namespaces that match the name the user has written. Returns <see cref="SymbolReference"/>s /// to the <see cref="INamespaceSymbol"/>s those namespaces are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingNamespacesAsync( SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForNamespace(_diagnosticId, _node, out var nameNode)) { _syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out var name, out var arity); if (arity == 0 && !ExpressionBinds(nameNode, checkForExtensionMethods: false, cancellationToken: searchScope.CancellationToken)) { var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Namespace).ConfigureAwait(false); var namespaceSymbols = OfType<INamespaceSymbol>(symbols); var containingNamespaceSymbols = OfType<INamespaceSymbol>(symbols).SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, containingNamespaceSymbols); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Specialized finder for the "Color Color" case. Used when we have "Color.Black" and "Color" /// bound to a Field/Property, but not a type. In this case, we want to look for namespaces /// containing 'Color' as if we import them it can resolve this issue. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingFieldsAndPropertiesAsync( SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out var nameNode) && nameNode != null) { // We have code like "Color.Black". "Color" bound to a 'Color Color' property, and // 'Black' did not bind. We want to find a type called 'Color' that will actually // allow 'Black' to bind. var syntaxFacts = _document.GetLanguageService<ISyntaxFactsService>(); if (syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameNode) || syntaxFacts.IsNameOfMemberBindingExpression(nameNode)) { var expression = syntaxFacts.GetExpressionOfMemberAccessExpression(nameNode.Parent, allowImplicitTarget: true) ?? syntaxFacts.GetTargetOfMemberBinding(nameNode.Parent); if (expression is TSimpleNameSyntax) { // Check if the expression before the dot binds to a property or field. var symbol = _semanticModel.GetSymbolInfo(expression, searchScope.CancellationToken).GetAnySymbol(); if (symbol?.Kind is SymbolKind.Property or SymbolKind.Field) { // Check if we have the 'Color Color' case. var propertyOrFieldType = symbol.GetSymbolType(); if (propertyOrFieldType is INamedTypeSymbol propertyType && Equals(propertyType.Name, symbol.Name)) { // Try to look up 'Color' as a type. var symbolResults = await searchScope.FindDeclarationsAsync( symbol.Name, (TSimpleNameSyntax)expression, SymbolFilter.Type).ConfigureAwait(false); // Return results that have accessible members. var namedTypeSymbols = OfType<INamedTypeSymbol>(symbolResults); var name = nameNode.GetFirstToken().ValueText; var namespaceResults = namedTypeSymbols.WhereAsArray(sr => HasAccessibleStaticFieldOrProperty(sr.Symbol, name)) .SelectAsArray(sr => sr.WithSymbol(sr.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceResults); } } } } } return ImmutableArray<SymbolReference>.Empty; } private bool HasAccessibleStaticFieldOrProperty(INamedTypeSymbol namedType, string fieldOrPropertyName) { return namedType.GetMembers(fieldOrPropertyName) .Any(m => (m is IFieldSymbol || m is IPropertySymbol) && m.IsStatic && m.IsAccessibleWithin(_semanticModel.Compilation.Assembly)); } /// <summary> /// Searches for extension methods that match the name the user has written. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForMatchingExtensionMethodsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out var nameNode) && nameNode != null) { searchScope.CancellationToken.ThrowIfCancellationRequested(); // See if the name binds. If it does, there's nothing further we need to do. if (!ExpressionBinds(nameNode, checkForExtensionMethods: true, cancellationToken: searchScope.CancellationToken)) { _syntaxFacts.GetNameAndArityOfSimpleName(nameNode, out var name, out var arity); if (name != null) { var symbols = await searchScope.FindDeclarationsAsync(name, nameNode, SymbolFilter.Member).ConfigureAwait(false); var methodSymbols = OfType<IMethodSymbol>(symbols); var extensionMethodSymbols = GetViableExtensionMethods( methodSymbols, nameNode.Parent, searchScope.CancellationToken); var namespaceSymbols = extensionMethodSymbols.SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceSymbols); } } } return ImmutableArray<SymbolReference>.Empty; } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethods( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols, SyntaxNode expression, CancellationToken cancellationToken) { return GetViableExtensionMethodsWorker(methodSymbols).WhereAsArray( s => _owner.IsViableExtensionMethod(s.Symbol, expression, _semanticModel, _syntaxFacts, cancellationToken)); } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethods( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols, ITypeSymbol typeSymbol) { return GetViableExtensionMethodsWorker(methodSymbols).WhereAsArray( s => IsViableExtensionMethod(s.Symbol, typeSymbol)); } private ImmutableArray<SymbolResult<IMethodSymbol>> GetViableExtensionMethodsWorker( ImmutableArray<SymbolResult<IMethodSymbol>> methodSymbols) { return methodSymbols.WhereAsArray( s => s.Symbol.IsExtensionMethod && s.Symbol.IsAccessibleWithin(_semanticModel.Compilation.Assembly)); } /// <summary> /// Searches for extension methods exactly called 'Add'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForCollectionInitializerMethodsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (!_owner.CanAddImportForMethod(_diagnosticId, _syntaxFacts, _node, out var nameNode)) { return ImmutableArray<SymbolReference>.Empty; } _syntaxFacts.GetNameAndArityOfSimpleName(_node, out var name, out var arity); if (name != null || !_owner.IsAddMethodContext(_node, _semanticModel)) { return ImmutableArray<SymbolReference>.Empty; } var symbols = await searchScope.FindDeclarationsAsync( nameof(IList.Add), nameNode: null, filter: SymbolFilter.Member).ConfigureAwait(false); // Note: there is no desiredName for these search results. We're searching for // extension methods called "Add", but we have no intention of renaming any // of the existing user code to that name. var methodSymbols = OfType<IMethodSymbol>(symbols).SelectAsArray(s => s.WithDesiredName(null)); var viableMethods = GetViableExtensionMethods( methodSymbols, _node.Parent, searchScope.CancellationToken); return GetNamespaceSymbolReferences(searchScope, viableMethods.SelectAsArray(m => m.WithSymbol(m.Symbol.ContainingNamespace))); } /// <summary> /// Searches for extension methods exactly called 'Select'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForQueryPatternsAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForQuery(_diagnosticId, _node)) { var type = _owner.GetQueryClauseInfo(_semanticModel, _node, searchScope.CancellationToken); if (type != null) { // find extension methods named "Select" return await GetReferencesForExtensionMethodAsync( searchScope, nameof(Enumerable.Select), type).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetAwaiter'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetAwaiterAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetAwaiter(_diagnosticId, _syntaxFacts, _node)) { var type = GetAwaitInfo(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetAwaiter, type, m => m.IsValidGetAwaiter()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetEnumerator'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetEnumeratorAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetEnumerator(_diagnosticId, _syntaxFacts, _node)) { var type = GetCollectionExpressionType(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetEnumeratorMethodName, type, m => m.IsValidGetEnumerator()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'GetAsyncEnumerator'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForGetAsyncEnumeratorAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForGetAsyncEnumerator(_diagnosticId, _syntaxFacts, _node)) { var type = GetCollectionExpressionType(_semanticModel, _syntaxFacts, _node); if (type != null) { return await GetReferencesForExtensionMethodAsync(searchScope, WellKnownMemberNames.GetAsyncEnumeratorMethodName, type, m => m.IsValidGetAsyncEnumerator()).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } /// <summary> /// Searches for extension methods exactly called 'Deconstruct'. Returns /// <see cref="SymbolReference"/>s to the <see cref="INamespaceSymbol"/>s that contain /// the static classes that those extension methods are contained in. /// </summary> private async Task<ImmutableArray<SymbolReference>> GetReferencesForDeconstructAsync(SearchScope searchScope) { searchScope.CancellationToken.ThrowIfCancellationRequested(); if (_owner.CanAddImportForDeconstruct(_diagnosticId, _node)) { var type = _owner.GetDeconstructInfo(_semanticModel, _node, searchScope.CancellationToken); if (type != null) { // Note: we could check that the extension methods have the right number of out-params. // But that would involve figuring out what we're trying to deconstruct into. For now // we'll just be permissive, with the assumption that there won't be that many matching // 'Deconstruct' extension methods for the type of node that we're on. return await GetReferencesForExtensionMethodAsync( searchScope, "Deconstruct", type, m => m.ReturnsVoid).ConfigureAwait(false); } } return ImmutableArray<SymbolReference>.Empty; } private async Task<ImmutableArray<SymbolReference>> GetReferencesForExtensionMethodAsync( SearchScope searchScope, string name, ITypeSymbol type, Func<IMethodSymbol, bool> predicate = null) { var symbols = await searchScope.FindDeclarationsAsync( name, nameNode: null, filter: SymbolFilter.Member).ConfigureAwait(false); // Note: there is no "desiredName" when doing this. We're not going to do any // renames of the user code. We're just looking for an extension method called // "Select", but that name has no bearing on the code in question that we're // trying to fix up. var methodSymbols = OfType<IMethodSymbol>(symbols).SelectAsArray(s => s.WithDesiredName(null)); var viableExtensionMethods = GetViableExtensionMethods(methodSymbols, type); if (predicate != null) { viableExtensionMethods = viableExtensionMethods.WhereAsArray(s => predicate(s.Symbol)); } var namespaceSymbols = viableExtensionMethods.SelectAsArray(s => s.WithSymbol(s.Symbol.ContainingNamespace)); return GetNamespaceSymbolReferences(searchScope, namespaceSymbols); } protected bool ExpressionBinds( TSimpleNameSyntax nameNode, bool checkForExtensionMethods, CancellationToken cancellationToken) { // See if the name binds to something other then the error type. If it does, there's nothing further we need to do. // For extension methods, however, we will continue to search if there exists any better matched method. cancellationToken.ThrowIfCancellationRequested(); var symbolInfo = _semanticModel.GetSymbolInfo(nameNode, cancellationToken); if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure && !checkForExtensionMethods) { return true; } return symbolInfo.Symbol != null; } private ImmutableArray<SymbolReference> GetNamespaceSymbolReferences( SearchScope scope, ImmutableArray<SymbolResult<INamespaceSymbol>> namespaces) { using var _ = ArrayBuilder<SymbolReference>.GetInstance(out var references); foreach (var namespaceResult in namespaces) { var symbol = namespaceResult.Symbol; var mappedResult = namespaceResult.WithSymbol(MapToCompilationNamespaceIfPossible(namespaceResult.Symbol)); var namespaceIsInScope = _namespacesInScope.Contains(mappedResult.Symbol); if (!symbol.IsGlobalNamespace && !namespaceIsInScope) references.Add(scope.CreateReference(mappedResult)); } return references.ToImmutable(); } private static ImmutableArray<SymbolResult<T>> OfType<T>(ImmutableArray<SymbolResult<ISymbol>> symbols) where T : ISymbol { return symbols.WhereAsArray(s => s.Symbol is T) .SelectAsArray(s => s.WithSymbol((T)s.Symbol)); } } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/AddImports/AddImportHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.AddImports { internal static class AddImportHelpers { public static TRootSyntax MoveTrivia<TRootSyntax, TImportDirectiveSyntax>( ISyntaxFacts syntaxFacts, TRootSyntax root, SyntaxList<TImportDirectiveSyntax> existingImports, List<TImportDirectiveSyntax> newImports) where TRootSyntax : SyntaxNode where TImportDirectiveSyntax : SyntaxNode { if (existingImports.Count == 0) { // We don't have any existing usings. Move any trivia on the first token // of the file to the first using. // // Don't do this for doc comments, as they belong to the first element // already in the file (like a class) and we don't want it to move to // the using. var firstToken = root.GetFirstToken(); // Remove the leading directives from the first token. var newFirstToken = firstToken.WithLeadingTrivia( firstToken.LeadingTrivia.Where(t => IsDocCommentOrElastic(syntaxFacts, t))); root = root.ReplaceToken(firstToken, newFirstToken); // Move the leading trivia from the first token to the first using. var newFirstUsing = newImports[0].WithLeadingTrivia( firstToken.LeadingTrivia.Where(t => !IsDocCommentOrElastic(syntaxFacts, t))); newImports[0] = newFirstUsing; } else { var originalFirstUsing = existingImports[0]; if (newImports[0] != originalFirstUsing) { // We added a new first-using. Take the trivia on the existing first using // And move it to the new using. var originalFirstUsingCurrentIndex = newImports.IndexOf(originalFirstUsing); newImports[0] = newImports[0].WithLeadingTrivia(originalFirstUsing.GetLeadingTrivia()); var trailingTrivia = newImports[0].GetTrailingTrivia(); if (!syntaxFacts.IsEndOfLineTrivia(trailingTrivia.Count == 0 ? default : trailingTrivia[^1])) { newImports[0] = newImports[0].WithAppendedTrailingTrivia(syntaxFacts.ElasticCarriageReturnLineFeed); } newImports[originalFirstUsingCurrentIndex] = originalFirstUsing.WithoutLeadingTrivia(); } } return root; } private static bool IsDocCommentOrElastic(ISyntaxFacts syntaxFacts, SyntaxTrivia t) => syntaxFacts.IsDocumentationComment(t) || syntaxFacts.IsElastic(t); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.AddImports { internal static class AddImportHelpers { public static TRootSyntax MoveTrivia<TRootSyntax, TImportDirectiveSyntax>( ISyntaxFacts syntaxFacts, TRootSyntax root, SyntaxList<TImportDirectiveSyntax> existingImports, List<TImportDirectiveSyntax> newImports) where TRootSyntax : SyntaxNode where TImportDirectiveSyntax : SyntaxNode { if (existingImports.Count == 0) { // We don't have any existing usings. Move any trivia on the first token // of the file to the first using. // // Don't do this for doc comments, as they belong to the first element // already in the file (like a class) and we don't want it to move to // the using. var firstToken = root.GetFirstToken(); // Remove the leading directives from the first token. var newFirstToken = firstToken.WithLeadingTrivia( firstToken.LeadingTrivia.Where(t => IsDocCommentOrElastic(syntaxFacts, t))); root = root.ReplaceToken(firstToken, newFirstToken); // Move the leading trivia from the first token to the first using. var newFirstUsing = newImports[0].WithLeadingTrivia( firstToken.LeadingTrivia.Where(t => !IsDocCommentOrElastic(syntaxFacts, t))); newImports[0] = newFirstUsing; } else { var originalFirstUsing = existingImports[0]; if (newImports[0] != originalFirstUsing) { // We added a new first-using. Take the trivia on the existing first using // And move it to the new using. var originalFirstUsingCurrentIndex = newImports.IndexOf(originalFirstUsing); newImports[0] = newImports[0].WithLeadingTrivia(originalFirstUsing.GetLeadingTrivia()); var trailingTrivia = newImports[0].GetTrailingTrivia(); if (!syntaxFacts.IsEndOfLineTrivia(trailingTrivia.Count == 0 ? default : trailingTrivia[^1])) { newImports[0] = newImports[0].WithAppendedTrailingTrivia(syntaxFacts.ElasticCarriageReturnLineFeed); } newImports[originalFirstUsingCurrentIndex] = originalFirstUsing.WithoutLeadingTrivia(); } } return root; } private static bool IsDocCommentOrElastic(ISyntaxFacts syntaxFacts, SyntaxTrivia t) => syntaxFacts.IsDocumentationComment(t) || syntaxFacts.IsElastic(t); } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/VisualStudio/Core/Test/SolutionExplorer/FakeAnalyzersCommandHandler.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.Internal.VisualStudio.PlatformUI Imports Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer Public Class FakeAnalyzersCommandHandler Implements IAnalyzersCommandHandler Public ReadOnly Property AnalyzerContextMenuController As IContextMenuController Implements IAnalyzersCommandHandler.AnalyzerContextMenuController Get Return Nothing End Get End Property Public ReadOnly Property AnalyzerFolderContextMenuController As IContextMenuController Implements IAnalyzersCommandHandler.AnalyzerFolderContextMenuController Get Return Nothing End Get End Property Public ReadOnly Property DiagnosticContextMenuController As IContextMenuController Implements IAnalyzersCommandHandler.DiagnosticContextMenuController Get Return Nothing End Get End Property End Class
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.Internal.VisualStudio.PlatformUI Imports Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer Public Class FakeAnalyzersCommandHandler Implements IAnalyzersCommandHandler Public ReadOnly Property AnalyzerContextMenuController As IContextMenuController Implements IAnalyzersCommandHandler.AnalyzerContextMenuController Get Return Nothing End Get End Property Public ReadOnly Property AnalyzerFolderContextMenuController As IContextMenuController Implements IAnalyzersCommandHandler.AnalyzerFolderContextMenuController Get Return Nothing End Get End Property Public ReadOnly Property DiagnosticContextMenuController As IContextMenuController Implements IAnalyzersCommandHandler.DiagnosticContextMenuController Get Return Nothing End Get End Property End Class
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/CSharp/Portable/Emitter/Model/CustomModifierAdapter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Emit; using System.Diagnostics; using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal partial class CSharpCustomModifier : Cci.ICustomModifier { bool Cci.ICustomModifier.IsOptional { get { return this.IsOptional; } } Cci.ITypeReference Cci.ICustomModifier.GetModifier(EmitContext context) { return ((PEModuleBuilder)context.Module).Translate(this.ModifierSymbol, (CSharpSyntaxNode)context.SyntaxNode, context.Diagnostics); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Emit; using System.Diagnostics; using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal partial class CSharpCustomModifier : Cci.ICustomModifier { bool Cci.ICustomModifier.IsOptional { get { return this.IsOptional; } } Cci.ITypeReference Cci.ICustomModifier.GetModifier(EmitContext context) { return ((PEModuleBuilder)context.Module).Translate(this.ModifierSymbol, (CSharpSyntaxNode)context.SyntaxNode, context.Diagnostics); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Scripting/Core/xlf/ScriptingResources.ru.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="ru" original="../ScriptingResources.resx"> <body> <trans-unit id="CannotSetLanguageSpecificOption"> <source>Cannot set {0} specific option {1} because the options were already configured for a different language.</source> <target state="translated">Не удается задать параметр {1}, связанный с {0}, так как эти параметры уже настроены для другого языка.</target> <note /> </trans-unit> <trans-unit id="StackOverflowWhileEvaluating"> <source>!&lt;Stack overflow while evaluating object&gt;</source> <target state="translated">!&lt;Переполнение стека при вычислении объекта&gt;</target> <note /> </trans-unit> <trans-unit id="CantAssignTo"> <source>Can't assign '{0}' to '{1}'.</source> <target state="translated">Не удается назначить "{0}" для "{1}".</target> <note /> </trans-unit> <trans-unit id="ExpectedAnAssemblyReference"> <source>Expected an assembly reference.</source> <target state="translated">Ожидалась ссылка на сборку.</target> <note /> </trans-unit> <trans-unit id="DisplayNameOrPathCannotBe"> <source>Display name or path cannot be empty.</source> <target state="translated">Отображаемое имя или путь не могут быть пустыми.</target> <note /> </trans-unit> <trans-unit id="AbsolutePathExpected"> <source>Absolute path expected</source> <target state="translated">Ожидался абсолютный путь</target> <note /> </trans-unit> <trans-unit id="GlobalsNotAssignable"> <source>The globals of type '{0}' is not assignable to '{1}'</source> <target state="translated">Объект Globals типа "{0}" не поддерживает назначение "{1}"</target> <note /> </trans-unit> <trans-unit id="StartingStateIncompatible"> <source>Starting state was incompatible with script.</source> <target state="translated">Начальное состояние было несовместимо со скриптом.</target> <note /> </trans-unit> <trans-unit id="InvalidAssemblyName"> <source>Invalid assembly name</source> <target state="translated">Недопустимое имя сборки</target> <note /> </trans-unit> <trans-unit id="InvalidCharactersInAssemblyName"> <source>Invalid characters in assemblyName</source> <target state="translated">Недопустимые символы в assemblyName</target> <note /> </trans-unit> <trans-unit id="ScriptRequiresGlobalVariables"> <source>The script requires access to global variables but none were given</source> <target state="translated">Скрипту требуется доступ к глобальным переменным, который не был предоставлен</target> <note /> </trans-unit> <trans-unit id="GlobalVariablesWithoutGlobalType"> <source>Global variables passed to a script without a global type</source> <target state="translated">Глобальные переменные переданы в скрипт без глобального типа</target> <note /> </trans-unit> <trans-unit id="PlusAdditionalError"> <source>+ additional {0} error</source> <target state="translated">+ дополнительная ошибка: {0}</target> <note /> </trans-unit> <trans-unit id="PlusAdditionalErrors"> <source>+ additional {0} errors</source> <target state="translated">+ дополнительные ошибки: {0}</target> <note /> </trans-unit> <trans-unit id="AtFileLine"> <source> at {0} : {1}</source> <target state="translated"> в {0} : {1}</target> <note /> </trans-unit> <trans-unit id="CannotSetReadOnlyVariable"> <source>Cannot set a read-only variable</source> <target state="translated">Невозможно задать переменную только для чтения</target> <note /> </trans-unit> <trans-unit id="CannotSetConstantVariable"> <source>Cannot set a constant variable</source> <target state="translated">Невозможно задать постоянную переменную</target> <note /> </trans-unit> <trans-unit id="HelpPrompt"> <source>Type "#help" for more information.</source> <target state="translated">Введите "#help" для получения дополнительных сведений.</target> <note /> </trans-unit> <trans-unit id="HelpText"> <source>Keyboard shortcuts: Enter If the current submission appears to be complete, evaluate it. Otherwise, insert a new line. Escape Clear the current submission. UpArrow Replace the current submission with a previous submission. DownArrow Replace the current submission with a subsequent submission (after having previously navigated backwards). Ctrl-C Exit the REPL. REPL commands: #help Display help on available commands and key bindings. Script directives: #r Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll". #load Load specified script file and execute it, e.g. #load "myScript.csx".</source> <target state="translated">Сочетания клавиш Клавиша ВВОД Если текущая отправка завершена, вычисляет ее. В противном случае добавляет новую строку. Клавиша ESC Очищает текущую отправку. Клавиша СТРЕЛКА ВВЕРХ Заменяет текущую отправку на предыдущую. Клавиша СТРЕЛКА ВНИЗ Заменяет текущую отправку на последующую (после предыдущего перехода в обратном порядке). Клавиши CTRL+C Выход из REPL. Команды цикла "Чтение — вычисление — печать": #help Отображает справку по текущим командам и сочетаниям клавиш. Директивы скрипта #r Добавляет ссылку на метаданные в указанную сборку и все ее зависимости, например #r myLib.dll. #load Загружает указанный файл скрипта и выполняет его, например #load myScript.csx.</target> <note /> </trans-unit> <trans-unit id="AssemblyAlreadyLoaded"> <source>Assembly '{0}, Version={1}' has already been loaded from '{2}'. A different assembly with the same name and version can't be loaded: '{3}'.</source> <target state="translated">Сборка "{0}" версии "{1}" уже загружена из "{2}". Нельзя загрузить другую сборку с тем же именем и версией: "{3}".</target> <note /> </trans-unit> <trans-unit id="AssemblyAlreadyLoadedNotSigned"> <source>Assembly '{0}' has already been loaded from '{1}'. A different assembly with the same name can't be loaded unless it's signed: '{2}'.</source> <target state="translated">Сборка "{0}" уже загружена из "{1}". Нельзя загрузить другую сборку с тем же именем, если она не подписана: "{2}".</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ru" original="../ScriptingResources.resx"> <body> <trans-unit id="CannotSetLanguageSpecificOption"> <source>Cannot set {0} specific option {1} because the options were already configured for a different language.</source> <target state="translated">Не удается задать параметр {1}, связанный с {0}, так как эти параметры уже настроены для другого языка.</target> <note /> </trans-unit> <trans-unit id="StackOverflowWhileEvaluating"> <source>!&lt;Stack overflow while evaluating object&gt;</source> <target state="translated">!&lt;Переполнение стека при вычислении объекта&gt;</target> <note /> </trans-unit> <trans-unit id="CantAssignTo"> <source>Can't assign '{0}' to '{1}'.</source> <target state="translated">Не удается назначить "{0}" для "{1}".</target> <note /> </trans-unit> <trans-unit id="ExpectedAnAssemblyReference"> <source>Expected an assembly reference.</source> <target state="translated">Ожидалась ссылка на сборку.</target> <note /> </trans-unit> <trans-unit id="DisplayNameOrPathCannotBe"> <source>Display name or path cannot be empty.</source> <target state="translated">Отображаемое имя или путь не могут быть пустыми.</target> <note /> </trans-unit> <trans-unit id="AbsolutePathExpected"> <source>Absolute path expected</source> <target state="translated">Ожидался абсолютный путь</target> <note /> </trans-unit> <trans-unit id="GlobalsNotAssignable"> <source>The globals of type '{0}' is not assignable to '{1}'</source> <target state="translated">Объект Globals типа "{0}" не поддерживает назначение "{1}"</target> <note /> </trans-unit> <trans-unit id="StartingStateIncompatible"> <source>Starting state was incompatible with script.</source> <target state="translated">Начальное состояние было несовместимо со скриптом.</target> <note /> </trans-unit> <trans-unit id="InvalidAssemblyName"> <source>Invalid assembly name</source> <target state="translated">Недопустимое имя сборки</target> <note /> </trans-unit> <trans-unit id="InvalidCharactersInAssemblyName"> <source>Invalid characters in assemblyName</source> <target state="translated">Недопустимые символы в assemblyName</target> <note /> </trans-unit> <trans-unit id="ScriptRequiresGlobalVariables"> <source>The script requires access to global variables but none were given</source> <target state="translated">Скрипту требуется доступ к глобальным переменным, который не был предоставлен</target> <note /> </trans-unit> <trans-unit id="GlobalVariablesWithoutGlobalType"> <source>Global variables passed to a script without a global type</source> <target state="translated">Глобальные переменные переданы в скрипт без глобального типа</target> <note /> </trans-unit> <trans-unit id="PlusAdditionalError"> <source>+ additional {0} error</source> <target state="translated">+ дополнительная ошибка: {0}</target> <note /> </trans-unit> <trans-unit id="PlusAdditionalErrors"> <source>+ additional {0} errors</source> <target state="translated">+ дополнительные ошибки: {0}</target> <note /> </trans-unit> <trans-unit id="AtFileLine"> <source> at {0} : {1}</source> <target state="translated"> в {0} : {1}</target> <note /> </trans-unit> <trans-unit id="CannotSetReadOnlyVariable"> <source>Cannot set a read-only variable</source> <target state="translated">Невозможно задать переменную только для чтения</target> <note /> </trans-unit> <trans-unit id="CannotSetConstantVariable"> <source>Cannot set a constant variable</source> <target state="translated">Невозможно задать постоянную переменную</target> <note /> </trans-unit> <trans-unit id="HelpPrompt"> <source>Type "#help" for more information.</source> <target state="translated">Введите "#help" для получения дополнительных сведений.</target> <note /> </trans-unit> <trans-unit id="HelpText"> <source>Keyboard shortcuts: Enter If the current submission appears to be complete, evaluate it. Otherwise, insert a new line. Escape Clear the current submission. UpArrow Replace the current submission with a previous submission. DownArrow Replace the current submission with a subsequent submission (after having previously navigated backwards). Ctrl-C Exit the REPL. REPL commands: #help Display help on available commands and key bindings. Script directives: #r Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll". #load Load specified script file and execute it, e.g. #load "myScript.csx".</source> <target state="translated">Сочетания клавиш Клавиша ВВОД Если текущая отправка завершена, вычисляет ее. В противном случае добавляет новую строку. Клавиша ESC Очищает текущую отправку. Клавиша СТРЕЛКА ВВЕРХ Заменяет текущую отправку на предыдущую. Клавиша СТРЕЛКА ВНИЗ Заменяет текущую отправку на последующую (после предыдущего перехода в обратном порядке). Клавиши CTRL+C Выход из REPL. Команды цикла "Чтение — вычисление — печать": #help Отображает справку по текущим командам и сочетаниям клавиш. Директивы скрипта #r Добавляет ссылку на метаданные в указанную сборку и все ее зависимости, например #r myLib.dll. #load Загружает указанный файл скрипта и выполняет его, например #load myScript.csx.</target> <note /> </trans-unit> <trans-unit id="AssemblyAlreadyLoaded"> <source>Assembly '{0}, Version={1}' has already been loaded from '{2}'. A different assembly with the same name and version can't be loaded: '{3}'.</source> <target state="translated">Сборка "{0}" версии "{1}" уже загружена из "{2}". Нельзя загрузить другую сборку с тем же именем и версией: "{3}".</target> <note /> </trans-unit> <trans-unit id="AssemblyAlreadyLoadedNotSigned"> <source>Assembly '{0}' has already been loaded from '{1}'. A different assembly with the same name can't be loaded unless it's signed: '{2}'.</source> <target state="translated">Сборка "{0}" уже загружена из "{1}". Нельзя загрузить другую сборку с тем же именем, если она не подписана: "{2}".</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Features/Core/Portable/Completion/CompletionItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// One of many possible completions used to form the completion list presented to the user. /// </summary> [DebuggerDisplay("{DisplayText}")] public sealed class CompletionItem : IComparable<CompletionItem> { private readonly string _filterText; /// <summary> /// The text that is displayed to the user. /// </summary> public string DisplayText { get; } /// <summary> /// An optional prefix to be displayed prepended to <see cref="DisplayText"/>. Can be null. /// Pattern-matching of user input will not be performed against this, but only against <see /// cref="DisplayText"/>. /// </summary> public string DisplayTextPrefix { get; } /// <summary> /// An optional suffix to be displayed appended to <see cref="DisplayText"/>. Can be null. /// Pattern-matching of user input will not be performed against this, but only against <see /// cref="DisplayText"/>. /// </summary> public string DisplayTextSuffix { get; } /// <summary> /// The text used to determine if the item matches the filter and is show in the list. /// This is often the same as <see cref="DisplayText"/> but may be different in certain circumstances. /// </summary> public string FilterText => _filterText ?? DisplayText; internal bool HasDifferentFilterText => _filterText != null; /// <summary> /// The text used to determine the order that the item appears in the list. /// This is often the same as the <see cref="DisplayText"/> but may be different in certain circumstances. /// </summary> public string SortText { get; } /// <summary> /// Descriptive text to place after <see cref="DisplayText"/> in the display layer. Should /// be short as it will show up in the UI. Display will present this in a way to distinguish /// this from the normal text (for example, by fading out and right-aligning). /// </summary> public string InlineDescription { get; } /// <summary> /// The span of the syntax element associated with this item. /// /// The span identifies the text in the document that is used to filter the initial list presented to the user, /// and typically represents the region of the document that will be changed if this item is committed. /// </summary> public TextSpan Span { get; internal set; } /// <summary> /// Additional information attached to a completion item by it creator. /// </summary> public ImmutableDictionary<string, string> Properties { get; } /// <summary> /// Descriptive tags from <see cref="Tags.WellKnownTags"/>. /// These tags may influence how the item is displayed. /// </summary> public ImmutableArray<string> Tags { get; } /// <summary> /// Rules that declare how this item should behave. /// </summary> public CompletionItemRules Rules { get; } /// <summary> /// Returns true if this item's text edit requires complex resolution that /// may impact performance. For example, an edit may be complex if it needs /// to format or type check the resulting code, or make complex non-local /// changes to other parts of the file. /// Complex resolution is used so we only do the minimum amount of work /// needed to display completion items. It is performed only for the /// committed item just prior to commit. Thus, it is ideal for any expensive /// completion work that does not affect the display of the item in the /// completion list, but is necessary for committing the item. /// An example of an item type requiring complex resolution is C#/VB /// override completion. /// </summary> public bool IsComplexTextEdit { get; } /// <summary> /// The name of the <see cref="CompletionProvider"/> that created this /// <see cref="CompletionItem"/>. Not available to clients. Only used by /// the Completion subsystem itself for things like getting description text /// and making additional change during commit. /// </summary> internal string ProviderName { get; set; } /// <summary> /// The automation text to use when narrating the completion item. If set to /// null, narration will use the <see cref="DisplayText"/> instead. /// </summary> internal string AutomationText { get; set; } internal CompletionItemFlags Flags { get; set; } private CompletionItem( string displayText, string filterText, string sortText, TextSpan span, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules, string displayTextPrefix, string displayTextSuffix, string inlineDescription, bool isComplexTextEdit) { DisplayText = displayText ?? ""; DisplayTextPrefix = displayTextPrefix ?? ""; DisplayTextSuffix = displayTextSuffix ?? ""; SortText = sortText ?? DisplayText; InlineDescription = inlineDescription ?? ""; Span = span; Properties = properties ?? ImmutableDictionary<string, string>.Empty; Tags = tags.NullToEmpty(); Rules = rules ?? CompletionItemRules.Default; IsComplexTextEdit = isComplexTextEdit; if (!DisplayText.Equals(filterText, StringComparison.Ordinal)) { _filterText = filterText; } } // binary back compat overload public static CompletionItem Create( string displayText, string filterText, string sortText, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules) { return Create(displayText, filterText, sortText, properties, tags, rules, displayTextPrefix: null, displayTextSuffix: null); } // binary back compat overload public static CompletionItem Create( string displayText, string filterText, string sortText, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules, string displayTextPrefix, string displayTextSuffix) { return Create(displayText, filterText, sortText, properties, tags, rules, displayTextPrefix, displayTextSuffix, inlineDescription: null); } // binary back compat overload public static CompletionItem Create( string displayText, string filterText, string sortText, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules, string displayTextPrefix, string displayTextSuffix, string inlineDescription) { return Create( displayText, filterText, sortText, properties, tags, rules, displayTextPrefix, displayTextSuffix, inlineDescription, isComplexTextEdit: false); } public static CompletionItem Create( string displayText, string filterText = null, string sortText = null, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default, CompletionItemRules rules = null, string displayTextPrefix = null, string displayTextSuffix = null, string inlineDescription = null, bool isComplexTextEdit = false) { return new CompletionItem( span: default, displayText: displayText, filterText: filterText, sortText: sortText, properties: properties, tags: tags, rules: rules, displayTextPrefix: displayTextPrefix, displayTextSuffix: displayTextSuffix, inlineDescription: inlineDescription, isComplexTextEdit: isComplexTextEdit); } /// <summary> /// Creates a new <see cref="CompletionItem"/> /// </summary> /// <param name="displayText">The text that is displayed to the user.</param> /// <param name="filterText">The text used to determine if the item matches the filter and is show in the list.</param> /// <param name="sortText">The text used to determine the order that the item appears in the list.</param> /// <param name="span">The span of the syntax element in the document associated with this item.</param> /// <param name="properties">Additional information.</param> /// <param name="tags">Descriptive tags that may influence how the item is displayed.</param> /// <param name="rules">The rules that declare how this item should behave.</param> /// <returns></returns> [Obsolete("Use the Create overload that does not take a span", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public static CompletionItem Create( string displayText, string filterText, string sortText, TextSpan span, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules) { return new CompletionItem( span: span, displayText: displayText, filterText: filterText, sortText: sortText, properties: properties, tags: tags, rules: rules, displayTextPrefix: null, displayTextSuffix: null, inlineDescription: null, isComplexTextEdit: false); } private CompletionItem With( Optional<TextSpan> span = default, Optional<string> displayText = default, Optional<string> filterText = default, Optional<string> sortText = default, Optional<ImmutableDictionary<string, string>> properties = default, Optional<ImmutableArray<string>> tags = default, Optional<CompletionItemRules> rules = default, Optional<string> displayTextPrefix = default, Optional<string> displayTextSuffix = default, Optional<string> inlineDescription = default, Optional<bool> isComplexTextEdit = default) { var newSpan = span.HasValue ? span.Value : Span; var newDisplayText = displayText.HasValue ? displayText.Value : DisplayText; var newFilterText = filterText.HasValue ? filterText.Value : FilterText; var newSortText = sortText.HasValue ? sortText.Value : SortText; var newInlineDescription = inlineDescription.HasValue ? inlineDescription.Value : InlineDescription; var newProperties = properties.HasValue ? properties.Value : Properties; var newTags = tags.HasValue ? tags.Value : Tags; var newRules = rules.HasValue ? rules.Value : Rules; var newDisplayTextPrefix = displayTextPrefix.HasValue ? displayTextPrefix.Value : DisplayTextPrefix; var newDisplayTextSuffix = displayTextSuffix.HasValue ? displayTextSuffix.Value : DisplayTextSuffix; var newIsComplexTextEdit = isComplexTextEdit.HasValue ? isComplexTextEdit.Value : IsComplexTextEdit; if (newSpan == Span && newDisplayText == DisplayText && newFilterText == FilterText && newSortText == SortText && newProperties == Properties && newTags == Tags && newRules == Rules && newDisplayTextPrefix == DisplayTextPrefix && newDisplayTextSuffix == DisplayTextSuffix && newInlineDescription == InlineDescription && newIsComplexTextEdit == IsComplexTextEdit) { return this; } return new CompletionItem( displayText: newDisplayText, filterText: newFilterText, span: newSpan, sortText: newSortText, properties: newProperties, tags: newTags, rules: newRules, displayTextPrefix: newDisplayTextPrefix, displayTextSuffix: newDisplayTextSuffix, inlineDescription: newInlineDescription, isComplexTextEdit: newIsComplexTextEdit) { AutomationText = AutomationText, ProviderName = ProviderName, Flags = Flags, }; } /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Span"/> property changed. /// </summary> [Obsolete("Not used anymore. CompletionList.Span is used to control the span used for filtering.", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public CompletionItem WithSpan(TextSpan span) => this; /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="DisplayText"/> property changed. /// </summary> public CompletionItem WithDisplayText(string text) => With(displayText: text); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="DisplayTextPrefix"/> property changed. /// </summary> public CompletionItem WithDisplayTextPrefix(string displayTextPrefix) => With(displayTextPrefix: displayTextPrefix); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="DisplayTextSuffix"/> property changed. /// </summary> public CompletionItem WithDisplayTextSuffix(string displayTextSuffix) => With(displayTextSuffix: displayTextSuffix); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="FilterText"/> property changed. /// </summary> public CompletionItem WithFilterText(string text) => With(filterText: text); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="SortText"/> property changed. /// </summary> public CompletionItem WithSortText(string text) => With(sortText: text); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Properties"/> property changed. /// </summary> public CompletionItem WithProperties(ImmutableDictionary<string, string> properties) => With(properties: properties); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with a property added to the <see cref="Properties"/> collection. /// </summary> public CompletionItem AddProperty(string name, string value) => With(properties: Properties.Add(name, value)); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Tags"/> property changed. /// </summary> public CompletionItem WithTags(ImmutableArray<string> tags) => With(tags: tags); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with a tag added to the <see cref="Tags"/> collection. /// </summary> public CompletionItem AddTag(string tag) { if (tag == null) { throw new ArgumentNullException(nameof(tag)); } if (Tags.Contains(tag)) { return this; } else { return With(tags: Tags.Add(tag)); } } /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Rules"/> property changed. /// </summary> public CompletionItem WithRules(CompletionItemRules rules) => With(rules: rules); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="IsComplexTextEdit"/> property changed. /// </summary> public CompletionItem WithIsComplexTextEdit(bool isComplexTextEdit) => With(isComplexTextEdit: isComplexTextEdit); private string _entireDisplayText; int IComparable<CompletionItem>.CompareTo(CompletionItem other) { // Make sure expanded items are listed after non-expanded ones var thisIsExpandItem = Flags.IsExpanded(); var otherIsExpandItem = other.Flags.IsExpanded(); if (thisIsExpandItem == otherIsExpandItem) { var result = StringComparer.OrdinalIgnoreCase.Compare(SortText, other.SortText); if (result == 0) { result = StringComparer.OrdinalIgnoreCase.Compare(GetEntireDisplayText(), other.GetEntireDisplayText()); } return result; } else if (thisIsExpandItem) { return 1; } else { return -1; } } internal string GetEntireDisplayText() { if (_entireDisplayText == null) { _entireDisplayText = DisplayTextPrefix + DisplayText + DisplayTextSuffix; } return _entireDisplayText; } public override string ToString() => GetEntireDisplayText(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// One of many possible completions used to form the completion list presented to the user. /// </summary> [DebuggerDisplay("{DisplayText}")] public sealed class CompletionItem : IComparable<CompletionItem> { private readonly string _filterText; /// <summary> /// The text that is displayed to the user. /// </summary> public string DisplayText { get; } /// <summary> /// An optional prefix to be displayed prepended to <see cref="DisplayText"/>. Can be null. /// Pattern-matching of user input will not be performed against this, but only against <see /// cref="DisplayText"/>. /// </summary> public string DisplayTextPrefix { get; } /// <summary> /// An optional suffix to be displayed appended to <see cref="DisplayText"/>. Can be null. /// Pattern-matching of user input will not be performed against this, but only against <see /// cref="DisplayText"/>. /// </summary> public string DisplayTextSuffix { get; } /// <summary> /// The text used to determine if the item matches the filter and is show in the list. /// This is often the same as <see cref="DisplayText"/> but may be different in certain circumstances. /// </summary> public string FilterText => _filterText ?? DisplayText; internal bool HasDifferentFilterText => _filterText != null; /// <summary> /// The text used to determine the order that the item appears in the list. /// This is often the same as the <see cref="DisplayText"/> but may be different in certain circumstances. /// </summary> public string SortText { get; } /// <summary> /// Descriptive text to place after <see cref="DisplayText"/> in the display layer. Should /// be short as it will show up in the UI. Display will present this in a way to distinguish /// this from the normal text (for example, by fading out and right-aligning). /// </summary> public string InlineDescription { get; } /// <summary> /// The span of the syntax element associated with this item. /// /// The span identifies the text in the document that is used to filter the initial list presented to the user, /// and typically represents the region of the document that will be changed if this item is committed. /// </summary> public TextSpan Span { get; internal set; } /// <summary> /// Additional information attached to a completion item by it creator. /// </summary> public ImmutableDictionary<string, string> Properties { get; } /// <summary> /// Descriptive tags from <see cref="Tags.WellKnownTags"/>. /// These tags may influence how the item is displayed. /// </summary> public ImmutableArray<string> Tags { get; } /// <summary> /// Rules that declare how this item should behave. /// </summary> public CompletionItemRules Rules { get; } /// <summary> /// Returns true if this item's text edit requires complex resolution that /// may impact performance. For example, an edit may be complex if it needs /// to format or type check the resulting code, or make complex non-local /// changes to other parts of the file. /// Complex resolution is used so we only do the minimum amount of work /// needed to display completion items. It is performed only for the /// committed item just prior to commit. Thus, it is ideal for any expensive /// completion work that does not affect the display of the item in the /// completion list, but is necessary for committing the item. /// An example of an item type requiring complex resolution is C#/VB /// override completion. /// </summary> public bool IsComplexTextEdit { get; } /// <summary> /// The name of the <see cref="CompletionProvider"/> that created this /// <see cref="CompletionItem"/>. Not available to clients. Only used by /// the Completion subsystem itself for things like getting description text /// and making additional change during commit. /// </summary> internal string ProviderName { get; set; } /// <summary> /// The automation text to use when narrating the completion item. If set to /// null, narration will use the <see cref="DisplayText"/> instead. /// </summary> internal string AutomationText { get; set; } internal CompletionItemFlags Flags { get; set; } private CompletionItem( string displayText, string filterText, string sortText, TextSpan span, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules, string displayTextPrefix, string displayTextSuffix, string inlineDescription, bool isComplexTextEdit) { DisplayText = displayText ?? ""; DisplayTextPrefix = displayTextPrefix ?? ""; DisplayTextSuffix = displayTextSuffix ?? ""; SortText = sortText ?? DisplayText; InlineDescription = inlineDescription ?? ""; Span = span; Properties = properties ?? ImmutableDictionary<string, string>.Empty; Tags = tags.NullToEmpty(); Rules = rules ?? CompletionItemRules.Default; IsComplexTextEdit = isComplexTextEdit; if (!DisplayText.Equals(filterText, StringComparison.Ordinal)) { _filterText = filterText; } } // binary back compat overload public static CompletionItem Create( string displayText, string filterText, string sortText, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules) { return Create(displayText, filterText, sortText, properties, tags, rules, displayTextPrefix: null, displayTextSuffix: null); } // binary back compat overload public static CompletionItem Create( string displayText, string filterText, string sortText, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules, string displayTextPrefix, string displayTextSuffix) { return Create(displayText, filterText, sortText, properties, tags, rules, displayTextPrefix, displayTextSuffix, inlineDescription: null); } // binary back compat overload public static CompletionItem Create( string displayText, string filterText, string sortText, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules, string displayTextPrefix, string displayTextSuffix, string inlineDescription) { return Create( displayText, filterText, sortText, properties, tags, rules, displayTextPrefix, displayTextSuffix, inlineDescription, isComplexTextEdit: false); } public static CompletionItem Create( string displayText, string filterText = null, string sortText = null, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default, CompletionItemRules rules = null, string displayTextPrefix = null, string displayTextSuffix = null, string inlineDescription = null, bool isComplexTextEdit = false) { return new CompletionItem( span: default, displayText: displayText, filterText: filterText, sortText: sortText, properties: properties, tags: tags, rules: rules, displayTextPrefix: displayTextPrefix, displayTextSuffix: displayTextSuffix, inlineDescription: inlineDescription, isComplexTextEdit: isComplexTextEdit); } /// <summary> /// Creates a new <see cref="CompletionItem"/> /// </summary> /// <param name="displayText">The text that is displayed to the user.</param> /// <param name="filterText">The text used to determine if the item matches the filter and is show in the list.</param> /// <param name="sortText">The text used to determine the order that the item appears in the list.</param> /// <param name="span">The span of the syntax element in the document associated with this item.</param> /// <param name="properties">Additional information.</param> /// <param name="tags">Descriptive tags that may influence how the item is displayed.</param> /// <param name="rules">The rules that declare how this item should behave.</param> /// <returns></returns> [Obsolete("Use the Create overload that does not take a span", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public static CompletionItem Create( string displayText, string filterText, string sortText, TextSpan span, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules) { return new CompletionItem( span: span, displayText: displayText, filterText: filterText, sortText: sortText, properties: properties, tags: tags, rules: rules, displayTextPrefix: null, displayTextSuffix: null, inlineDescription: null, isComplexTextEdit: false); } private CompletionItem With( Optional<TextSpan> span = default, Optional<string> displayText = default, Optional<string> filterText = default, Optional<string> sortText = default, Optional<ImmutableDictionary<string, string>> properties = default, Optional<ImmutableArray<string>> tags = default, Optional<CompletionItemRules> rules = default, Optional<string> displayTextPrefix = default, Optional<string> displayTextSuffix = default, Optional<string> inlineDescription = default, Optional<bool> isComplexTextEdit = default) { var newSpan = span.HasValue ? span.Value : Span; var newDisplayText = displayText.HasValue ? displayText.Value : DisplayText; var newFilterText = filterText.HasValue ? filterText.Value : FilterText; var newSortText = sortText.HasValue ? sortText.Value : SortText; var newInlineDescription = inlineDescription.HasValue ? inlineDescription.Value : InlineDescription; var newProperties = properties.HasValue ? properties.Value : Properties; var newTags = tags.HasValue ? tags.Value : Tags; var newRules = rules.HasValue ? rules.Value : Rules; var newDisplayTextPrefix = displayTextPrefix.HasValue ? displayTextPrefix.Value : DisplayTextPrefix; var newDisplayTextSuffix = displayTextSuffix.HasValue ? displayTextSuffix.Value : DisplayTextSuffix; var newIsComplexTextEdit = isComplexTextEdit.HasValue ? isComplexTextEdit.Value : IsComplexTextEdit; if (newSpan == Span && newDisplayText == DisplayText && newFilterText == FilterText && newSortText == SortText && newProperties == Properties && newTags == Tags && newRules == Rules && newDisplayTextPrefix == DisplayTextPrefix && newDisplayTextSuffix == DisplayTextSuffix && newInlineDescription == InlineDescription && newIsComplexTextEdit == IsComplexTextEdit) { return this; } return new CompletionItem( displayText: newDisplayText, filterText: newFilterText, span: newSpan, sortText: newSortText, properties: newProperties, tags: newTags, rules: newRules, displayTextPrefix: newDisplayTextPrefix, displayTextSuffix: newDisplayTextSuffix, inlineDescription: newInlineDescription, isComplexTextEdit: newIsComplexTextEdit) { AutomationText = AutomationText, ProviderName = ProviderName, Flags = Flags, }; } /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Span"/> property changed. /// </summary> [Obsolete("Not used anymore. CompletionList.Span is used to control the span used for filtering.", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public CompletionItem WithSpan(TextSpan span) => this; /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="DisplayText"/> property changed. /// </summary> public CompletionItem WithDisplayText(string text) => With(displayText: text); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="DisplayTextPrefix"/> property changed. /// </summary> public CompletionItem WithDisplayTextPrefix(string displayTextPrefix) => With(displayTextPrefix: displayTextPrefix); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="DisplayTextSuffix"/> property changed. /// </summary> public CompletionItem WithDisplayTextSuffix(string displayTextSuffix) => With(displayTextSuffix: displayTextSuffix); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="FilterText"/> property changed. /// </summary> public CompletionItem WithFilterText(string text) => With(filterText: text); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="SortText"/> property changed. /// </summary> public CompletionItem WithSortText(string text) => With(sortText: text); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Properties"/> property changed. /// </summary> public CompletionItem WithProperties(ImmutableDictionary<string, string> properties) => With(properties: properties); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with a property added to the <see cref="Properties"/> collection. /// </summary> public CompletionItem AddProperty(string name, string value) => With(properties: Properties.Add(name, value)); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Tags"/> property changed. /// </summary> public CompletionItem WithTags(ImmutableArray<string> tags) => With(tags: tags); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with a tag added to the <see cref="Tags"/> collection. /// </summary> public CompletionItem AddTag(string tag) { if (tag == null) { throw new ArgumentNullException(nameof(tag)); } if (Tags.Contains(tag)) { return this; } else { return With(tags: Tags.Add(tag)); } } /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Rules"/> property changed. /// </summary> public CompletionItem WithRules(CompletionItemRules rules) => With(rules: rules); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="IsComplexTextEdit"/> property changed. /// </summary> public CompletionItem WithIsComplexTextEdit(bool isComplexTextEdit) => With(isComplexTextEdit: isComplexTextEdit); private string _entireDisplayText; int IComparable<CompletionItem>.CompareTo(CompletionItem other) { // Make sure expanded items are listed after non-expanded ones var thisIsExpandItem = Flags.IsExpanded(); var otherIsExpandItem = other.Flags.IsExpanded(); if (thisIsExpandItem == otherIsExpandItem) { var result = StringComparer.OrdinalIgnoreCase.Compare(SortText, other.SortText); if (result == 0) { result = StringComparer.OrdinalIgnoreCase.Compare(GetEntireDisplayText(), other.GetEntireDisplayText()); } return result; } else if (thisIsExpandItem) { return 1; } else { return -1; } } internal string GetEntireDisplayText() { if (_entireDisplayText == null) { _entireDisplayText = DisplayTextPrefix + DisplayText + DisplayTextSuffix; } return _entireDisplayText; } public override string ToString() => GetEntireDisplayText(); } }
-1