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
<ExtensionAttribute>
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
<Extension()>
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
<ExtensionAttribute>
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
<ExtensionAttribute>
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
<ExtensionAttribute>
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 & .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, " & 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 = " & Me.A & "; .B = " & Me.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) & "; .C = " & 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 = " & Me.A & "; .B = " & Me.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) & "; .C = " & 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 = " & Me.A & "; .B = " & Me.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) & "; .C = " & 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 = " & Me._abc.A & "; .B = " & Me._abc.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) & "; .C = " & 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 = " & Me._abc.A & "; .B = " & Me._abc.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) & "; .C = " & 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 = " & a.A & "; B = " & a.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) & "; C = " & 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 = " & a.A & "; B = " & a.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) & "; C = " & 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 = " & a.A & "; B = " & a.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) & "; C = " & 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 = " & a.A & "; B = " & a.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) & "; C = " & 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 & "=" & 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 & "=" & 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 & "=" & 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 & " > " & 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
<Extension()>
Public Sub Goo(ByRef x As C1)
x = New C1(42)
Console.WriteLine(x.Field)
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
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
<ExtensionAttribute>
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
<Extension()>
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
<ExtensionAttribute>
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
<ExtensionAttribute>
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
<ExtensionAttribute>
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 & .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, " & 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 = " & Me.A & "; .B = " & Me.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) & "; .C = " & 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 = " & Me.A & "; .B = " & Me.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) & "; .C = " & 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 = " & Me.A & "; .B = " & Me.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) & "; .C = " & 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 = " & Me._abc.A & "; .B = " & Me._abc.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) & "; .C = " & 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 = " & Me._abc.A & "; .B = " & Me._abc.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) & "; .C = " & 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 = " & a.A & "; B = " & a.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) & "; C = " & 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 = " & a.A & "; B = " & a.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) & "; C = " & 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 = " & a.A & "; B = " & a.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) & "; C = " & 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 = " & a.A & "; B = " & a.B.ToString("M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture) & "; C = " & 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 & "=" & 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 & "=" & 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 & "=" & 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 & " > " & 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
<Extension()>
Public Sub Goo(ByRef x As C1)
x = New C1(42)
Console.WriteLine(x.Field)
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
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>// <autogenerated />
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>// <autogenerated />
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>
<Assembly: Goo(0, True, S:="x")>
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>
<Assembly: CLSCompliant(True)>
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>
<Assembly: CLSCompliant(True)>
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>
$$<Assembly: System.Reflection.AssemblyCompany("Microsoft")>
</Code>
Dim expected =
<Code>
<Assembly: System.Reflection.AssemblyCompany("Microsoft")>
<Assembly: CLSCompliant(True)>
</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>
$$<Assembly: System.Reflection.AssemblyCompany("Microsoft")>
Class C
End Class
</Code>
Dim expected =
<Code>
<Assembly: System.Reflection.AssemblyCompany("Microsoft")>
<Assembly: CLSCompliant(True)>
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>
$$<Assembly: System.Reflection.AssemblyCompany("Microsoft")>
<Assembly: System.Reflection.AssemblyCopyright("2012")>
Class C
End Class
</Code>
Dim expected =
<Code>
<Assembly: System.Reflection.AssemblyCompany("Microsoft")>
<Assembly: System.Reflection.AssemblyCopyright("2012")>
<Assembly: CLSCompliant(True)>
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>
''' <summary></summary>
Class $$C
End Class
</Code>
Dim expected =
<Code>
<Assembly: CLSCompliant(True)>
''' <summary></summary>
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>
''' <summary>
'''
''' </summary>
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>
<Assembly: Goo(0, True, S:="x")>
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>
<Assembly: CLSCompliant(True)>
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>
<Assembly: CLSCompliant(True)>
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>
$$<Assembly: System.Reflection.AssemblyCompany("Microsoft")>
</Code>
Dim expected =
<Code>
<Assembly: System.Reflection.AssemblyCompany("Microsoft")>
<Assembly: CLSCompliant(True)>
</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>
$$<Assembly: System.Reflection.AssemblyCompany("Microsoft")>
Class C
End Class
</Code>
Dim expected =
<Code>
<Assembly: System.Reflection.AssemblyCompany("Microsoft")>
<Assembly: CLSCompliant(True)>
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>
$$<Assembly: System.Reflection.AssemblyCompany("Microsoft")>
<Assembly: System.Reflection.AssemblyCopyright("2012")>
Class C
End Class
</Code>
Dim expected =
<Code>
<Assembly: System.Reflection.AssemblyCompany("Microsoft")>
<Assembly: System.Reflection.AssemblyCopyright("2012")>
<Assembly: CLSCompliant(True)>
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>
''' <summary></summary>
Class $$C
End Class
</Code>
Dim expected =
<Code>
<Assembly: CLSCompliant(True)>
''' <summary></summary>
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>
''' <summary>
'''
''' </summary>
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:<file> Reference metadata from the specified assembly file (alternative form: /reference)
/r:<file list> Reference metadata from the specified assembly files (alternative form: /reference)
/lib:<path list> List of directories where to look for libraries specified by #r directive.
(alternative forms: /libPath /libPaths)
/u:<namespace> Define global namespace using (alternative forms: /using, /usings, /import, /imports)
/langversion:? Display the allowed values for language version and exit
/langversion:<string> 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`
@<file> 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:<file> Metadados de referência do arquivo do assembly especificado (formato alternativo: /reference)
/r:<file list> Metadados de referência dos arquivos do assembly especificados (formato alternativo: /reference)
/lib:<path list> Lista de diretórios nos quais procurar bibliotecas especificadas pela diretiva #r.
(formatos alternativos: /libPath /libPaths)
/u:<namespace> Definir o namespace global usando (formatos alternativos: /using, /usings, /import, /imports)
/langversion:? Exibir os valores permitidos para versão do idioma e sair
/langversion:<string> 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'
@<file> 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:<file> Reference metadata from the specified assembly file (alternative form: /reference)
/r:<file list> Reference metadata from the specified assembly files (alternative form: /reference)
/lib:<path list> List of directories where to look for libraries specified by #r directive.
(alternative forms: /libPath /libPaths)
/u:<namespace> Define global namespace using (alternative forms: /using, /usings, /import, /imports)
/langversion:? Display the allowed values for language version and exit
/langversion:<string> 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`
@<file> 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:<file> Metadados de referência do arquivo do assembly especificado (formato alternativo: /reference)
/r:<file list> Metadados de referência dos arquivos do assembly especificados (formato alternativo: /reference)
/lib:<path list> Lista de diretórios nos quais procurar bibliotecas especificadas pela diretiva #r.
(formatos alternativos: /libPath /libPaths)
/u:<namespace> Definir o namespace global usando (formatos alternativos: /using, /usings, /import, /imports)
/langversion:? Exibir os valores permitidos para versão do idioma e sair
/langversion:<string> 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'
@<file> 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
IHDR n wV sRGB gAMA a pHYs od IDATx^_%u 泞' a)YJbG-K!ʘC\
{CִPYFQ{X[<kO Ji [@b{yywyQY'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!|5vx0?{Y BI
U$b<Xn-:w!fà'^/=e \;Յh ۬o{BX#*Е <BY+*O~[o{B|,w '.DquFrXd[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/ooSOb#
9^
S]?`g.籅QA{
X
q _]ކV/OйƏߖ[)*-zꯊm^Oa>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
яFqPzEb5JvJGNٱOQF "|$
dFDvBpSD)į*5B;)rBImٱq5FPXuñA`G8B4FDvBܼy[nL{`=a]t+tb\FP/PPSJxBǡ0Vԋrٙy tGpȌ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_#IW73;P`+5b\6 È#|([Z /&dEd-kDNzg'/:h]QDk_e2)[zbs{:ݽ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?#ߊBr]gae
Ӏk~Y7AleyٳϞ,`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? [xhF|
"QϯN?._kO#R? ,ph˳cVITyx>8^8a?|YVfD*r+< aÔ'm3
<goqgt.O%n>v[#^lօ
U({
BM_K䳳KWa}t*Dg1za"FuAUڧ"-|~0^^:5fU 5 'Kj5uuA_#A|[$l%F.
Nx#LݫU%*#kw\^^~)0n
:>?t낰KWR@5yR7ʒ*P\o^
Rw~
PY$>,3ۂa7.rБ7pM $\̅W
\FkTyX=LD
#uAإ 71xti# J'3x]v*5<CE97rK]ׯcnQXzNuj^ 2,*aǮ]օz4JmIs.}FsO j.َa'.ͳ ``&t_u lOx]v.Aj5>+ǁ5낰KW<.?#'2L_8i2#$Ix]{x 87Z?ȹ ,^_Du6,DPSEaeAI/uAإ@sMY&!v*@W^aǮ U%##낰WAޤwX=
&O.ƄۅY٥<~vz@# CN UiNGL~H$.낰cW9%M
VFN^>on Ո
b U(eJq]
; a%O! U};/._@UpA[;o{ng낰3WwV?"^ݸ
-Sz]X
.>k Ha#`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ܸxzZ*[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ֆSnc;ֆ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 ZfK BBGfC7ɵz=:Nݡۆ:
kbA{%=0s尼5@맼8(#YcH4G$X |"E@bZmۆ:Ǥ}
q*D!Vk/~c}$
?rPkÊO8(`>AqGnQ\
rD҆b*ϡO4QdMkCq0ZNj[ A9q"=:~@sNk^`#]RaG-<t@EۄFp`_k
{ֆbpj̋<XYNV"rCk\'prOq\f,O{.^'j8Ro6?.ՆyVc@~y j@BrF&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\k 2˙,A"H;\HgֆM!AVGCͱH$uQ'"ֆimXp<,7RPfzm 6ea4YWi=*#k!K$5vH u>&xmX;\}6^6Dh#8=E tض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#`uaT08ae|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); WzOdDQ J-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{WIc axU(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$C qKj5&`@
&"
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,_`WbaZWO1eT>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&MgA NH$80<w T"ДUXߙOKrHU0oFfLX:[īD*.VΟ?Hf"YXs| "c;ѭ<.(8<G
scW(cDžTAA9RWB%<=dFlUx7Aˀg/`07(YGn
CvPG#H<yt OApdd[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?jW D2xUZ*]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
3Uը@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&Ǫɯ꺍dCb$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<`PN7.$;*8ndWN_?joǏ'ʮ}"gvHD,8^Vv瓛d?§ t_Ua U?-fe_^\cUӟBpV+?BXpB9B*r>$zU8.TUeUx!@dU0gpVg @cW 2wUUP&[*M=RTO~#2oݕ?(Uae*
Nīe7]H8ȍGH%29,eG@7U$+
iiV PE l!GUAG&)_*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 xVaF HdP!T
eUD`bl˪p`8 O
y5`-2AP
CT.¨Jأaɪ0mV,T qT@.CD*4bE$JZ_x]-XvnSUgU
0fşf٥,!6#-$>=<7p)O0 4yBngt)%̵*<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?1pL!]`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
]'6BJRCLeyƜ"S^V`Yn̂iw9.x7n_}6~tjcNٳP7qvٳ!)֤7.ܾډ݇vڅ#n>B-:gupc3XCN8N]cnbg%3;SAr﨣Șv.0,`r.c=cjT]pyir]͖Tmql.$;8.tp|ًv Wc͋7)<=cYz 9_bP[0C]8wܙ3g=x1,rI-DjM%jưILŖ_O&ghZ*ٝٙ>X[P+P3څ@dSz="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>PbvϿ,m]3|gC^nPOs^uWmمI%څy;gD1
MA0_@3~W)_Esk
deGodW!$h2vxN 튭nenw|T2#Xr3 3b[Y/$Duvaͣ0Am
lm]M|_~xv7/8'2eq Hah$TIkM埉Z?e$?LȂp,';Wbv+c&]H;9wEK(-M}3CƏȇ%2l.ׯX uM1?(embHE
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
^ZBW1Eh6Z \_XW6 ^D]`h]g
rX 1x+g26V+aMS3L]l`GhUOEh⯠>ο:%w,|R[s0
oX.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寉%uo7ل0QuV۠8햡,_-[?V,Ćw֭&{/M[fv! hQAߕ!}["A!<8 M|0m[$vs!j
ՔJ _=EliqФ[1Ə,BWՠE 6;\L :Av.^;r(znz`FzJBh`覿0bFΉB+UI5BDTlW;ICk9O?Cq&x'>*$K+0Un5a ;
]٭f~nY] Na1 B,2^Ύ&FO(uIBQ{$<WSip:B"h\+8. j]UBE
a+#(2j@#
;+.|a?#hb' |pw5PM{sA9"rJ8.$
;tva2BX
ATP0ߧvUEشCԁfA VZ W'R4mv}d]h\d[(ʈpB_"Ɯ?\]}#ZЦ>;4.q/]'م?bpۅK0}`AC
'
T@o~bt9}lIY#I|lvy v~!>arnB
6TO"MX6|Ƣ*#;ZSg]xchSfNq+6ojR4<3Br$kw993 ypJsnzźB}F=n4Qm" lNGoӦy+s N1>I HP0p"Dj%q+Z?Űj6(8'vW.8BhۿO.o%_LvgAXc^:nzE]xÚߧ\vk8B <fL`}'nzNvavhYvW]pVۅ^YCj50+vYFhiv^̡fTއu.VP0l.4 ,f3"NmRgfż!
C><ʱm\R6D]ľC!AyG6υۅ^ba+va39΅fghW0s"nzEgBQoO ;`)=[3Bhf¶QG@ +6 ً#9^-vWt.2
ۅ^YnzEB^13,z VΩVj_~ẑۅ^f>i5م$^|MZߘ@;
I'.- jP5FBham@wp+Z»>_pNB!#!f1>3vWt.h~!M]PxD]]]@[ĝ=Bh2s"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삾ˀ&Wa
*`(7 _6D$ڎ D ؖE8=vW.lp"nvW.pqhV:Qȵxa8L=QD%=ZBEP_-,(,Y1mcB,.*Br4VdaGQu]mDswq+v.tQ.8+BOgurt9qq'P$@AQvT)R}R av8@Rמn]`
U-l" &C4kIFP0F`$~0*#ѵnz>mva_p˾gM]` [hs2|
[%kcaIeD9EgD̲_)"&)ݵ{.dd&&û6H`RU.م͠M}hΎvW]pVۅ^ovW^ zlqPオKG_ӯÑu^#ރL+
(ltj$mb~z0,b[;:nMa*ZxmU^S,#scw#nzڅvahtFp+.8+Bs 3g~>A"q! ae*g[H}ѥTy;.@mjDj@[,C0 r,[r 5%P/@A4Snz^مyLcS/8킳.
` /'䇲vCB^-
vȻOK|~)ҕ.
籽y&w;H͗{<`5+2HKXrle/P~ylCDF8ܴO#2w/\]n_=V/8k킳.
$f|Pfի
1R@5POb^FTۅ^vA/e4ߤ@qIlK?kL=tߌkKj/ô·ۅ^vY nzۅ/܀=o"@e.l07A;.
,g#AYWaTЃ]4S0#vBg٭q
킳.
3/ xO.ݻ(>- Khl)DV1?Bp0;v|$kh[
Ufv풍PrRb8n=bY~~ۅ^va}$pFhS_BpvByk+ӐרowrGQ+ԏ;$
7
%
Bt*Ig^V.م2
yYZY!pk +)Dq8۪YmAvU+C0-:A*8(J3)[.vW.,І/8v
nz}*t@2hTz H%X<dvWt.WCFUeb6Eę<GkeZe-
ZN=.65 W%p7-NǕwvD:r_pS]x0*k`BPB5`%!Buwp+v.?3vvmE1
t
/)4>ض}aP`!rU"<F qB _X/}h]hYBpb]+,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>c geG(
p6Qꒄ"68p
ZB]'?(ӵeNBpvh}LB_!c55R8J~o
+*re@VjkBh,G̅6ep&nvWڅGdv`B(mQ텅
vWw}Qݟ "(ԙ녅
vW],M*nzg%]mv2.^IjTHG iTV+8vWڅ0]rn,
ImkVؤUM54
(ىq+gf'ZjQ4Cqgp+.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\bJ`+]څ%QjefBhnq+.,g7c۱3)۳$Ө-'NtɖW'(OW߰Xlۅ^vaw"eŖ-XaSy
$ɮy?YVew+ :2(1lMBpnao jN0]pNBhb]Hc^]i]hO,˾0h!v3/۱ h_KZE
,ۅ^b~>bc]Xeqb´逜p)vҞ&,0PI-0dڒ:'Ӹ]mv}İP[A[#ؖfHwT/Tva5MɏMJ ?!˦>]uȶތ^-nzEgBѦ5qgq+.8+BQLChzPTOsyI#@~y:Kq.VIn6*ҒGã[4dW`"k$8+S D,Bq+Z;IG$i,NiI_pNBQ/۸P矷k_&Puq:;j_ jlFhj>u]pVۅ^)2Of%w9wIdwHLX
IvWم~aMvHm!p|6uٝyH}A+ Y?NߛU"vW~1
5@[wv.<v9va0HQԇ Nx(;=GG#L{' v.څc{Mma, PW[|8[iCF[d&"t)YK༩al |قۅ^Y,0Q26mv||9b}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$uw}WQ.ذ&pAnw>3'wy!gFo:7?G\䪖dOR%Io<#ȓlQJTDpW9nzFblxCeX]`DۓHKaU;gBD7$MJ^FsϟɨDC0UۅdBۅ^G|9"62]pNBHl
nq+[`[CΉ]-3;nzEblۅ_:7υBAvl}4
3GnXu9¿C=Q8xA#ga+;/?,ܹ/߉;MF5
;wp计O33|;_Ɲh|XBv914
O<wgVPHeD F̕5
, c|N(";8-Z9ﷱM _~CFb+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/\cMg<[:8cǗ
F#QuQpo(JxVWo|3$Qnm4
86j.dQ\$_͇@w!QppQ(Ki(- h[Oq_YiU|
D(v Z7
3FYf FAC! F`Ɉ
a!o_Eip0/hۇQHލaFAY9jyy{/h9}
$3;nzE47
(
ܜ|{2ԍf
b8Sj:;O,oiE:^Ԍjd;Bb4,cb(v3RdSwTnTr:,l³"$bXrqFN0
!r3NCm(xk< (l@Gǖ^'!7o,=ZmJb40CT<cܶ,lGFhihlHBD'J0yՌVH%0p8ǧlRTD|Bә/Jw)1Όl
FE5lnJ
KDX&O0s*z> Rs(Yj/XбFa[ݲak([KH]D4nS[
f? b 4u=iPebhd|<QPhVWqkZkf4
{@(6[&IҪw(7 (Hd7 hASD,X S=:>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]k Yh0P !7ڀ%'(Ajҏ-[Ye2vq\=MeShaPg)0lqgؖvϳL;;gy:nzgy(uIRLr^Oa')hD^y@ec[c^46LX 8%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٢QzEFqǘԜ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ꕦIoQS~#ޫ7b]y|EU3/ZIW3h5
g3=@\!4oa%ѕ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-]M qO{eO$/V?sm0-ìrQU<)lh;ڋHS~<E1ӣ<{7\Ex'[u#s:P(8˳QQ/ѬZ.h~A1TjZ<0PQ39LEQ>zm M5
+KDiE k 4d+a&5
mn7تkF!d!mP$q6;1$5ޝXF!l9^MS-gȸ5<bB36!F[ii@-E>D͚Q4mCOV,HB`P7
ԴgHlVh3
}!nbFc
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$}ǡ.=)={), B7v>>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]gE 4
\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"(D L qڌi|C1O
؍jFMZvy_$=D(olt BؖQl8hJ8G6Q&9@mXխ6{FX&Vh%8'8 7
b[FaWP1;>6nq+(8FWQpǍBQ!/,2]T:q˕T\-
>aDP+fG2$Hl{^j
q7n/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"HvFWO3DՍ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_ӭ@,q 9@cP#D~ց=3nzEQCT])}?|;]6(]6uʵk$2H{
FWl(l 5
c
sFWw}3QqFWQpǍBp,^+Fcx(JՑBg 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Ӄ\#i2yp }$]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+(uBp,^FY7
(|!,;$I yM8LdXB+s:@[')㔘
4I#n'}3
[&$! TnUY BCb:I.j@0F2IQ{ht.s9I%(Pyd#)8+`º&BQbĝFWQXuBh1
1DUǙ^FY7
(jb Y_}Z
cvX[HKM)eX'+8QFj_Xр[ "WvViCPVHU2bC.24#V<+;
k=Q1
h0aiEVǖYEl|"ڂ*b? 16<"H 4P'5
4U7
?F}FՍBm$ |BbRfQ 1~c
<u`V$EQSpgy(
7
Qnq+a.Y.yaބvaYޕnVĈ fwAjnuF"lUFWQxb,m
MmOwûhDwmg]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/71ԕBXʁX[ FAos0O {
`ƹ-(,)8kč<nzžgQnq+zoh oFE̴JUFKudzQK"3
Ν{ꩧNհ~4@̲v7CY|oI71S(k40$TReVSƍ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
y n6,.aEXuªV--<dTK˂V:S
r)m!1* nzžk %hKҢ8Q0<<dWJg*-EA.,}T-5FWQxcèQXSpg&(
7
Qnq+(~0<aL<IBQh<
8Pg,<%N2ÍQy#7
bߌ<cmuiGR.ա5BΦ]>"d<5p9$|rl#U{FUT@Uvv+("<qM
5!lh܅@cFwm[:\c ZbA*U7
b½{*lh-FmN6NaVXΡPF:+ F=geQX zׄ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
7lCDFSpV;c3z|LYn~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#YS7
,(`k?c4q5͌І""Qy2SI]W2A#rpKFWQk63+m4ElUJIY|4Fa^ ;4BpA|7
<nzgy(
7
P mvICy8B;7Lm JNBukp+(B}>MDvXȃCډ6<lC}lI D21IR
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}R4V biʟ(ଏ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$^F 4j WLHȫNJb;,$,,DROOb PB %ȃl(]4
?p xzBUcBFE,f8[:*kiʏ%W}Uדnz{T xl{F˱\@<N.UK 6$U wCe#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+0bb<6Ki玳,
w̴D䱦o7
(CT}Ο?ո`c#D8Hhc p&BX8Ԋ#$͘8q ؇)8i6^oFۛ7or]=F;1rnq;'QE(dD.+Q'l7
bߌ@jx?
BP
9VȞߦb6G\rHʱYDuN8a(2
zu 5
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
dDItdr$lw7
(|Qۇ>IUXn
ภQfe&tYSpƞFa|L&nq+(8FWQpǍBh5
2Dg'S{PDu "R^ଞ>UwXO!j)upz|-SpȾl;h ( g)8kdߌN RUQ5WFSXnz^gMQnq+ڌe37
bB9[;VX!Z&PTgXO,7
(|!ΝK>E/OaZ<z\ãDPr!"S,HfC$25rxt90:Y gX)sKFW("9s&1
|f[]Mb̶}$qD 5urAHPGVmǍ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^kbOau($7Ym7
bߌ<cml|O1YRBƆ 9.v4]$B^Ծ `W[|!ߘ έBrx^b9<
FWQExN3mҞ
j!ФنJ5캥-Ht vQ`,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("VwU9wmDVj:8% c9גv+Z/ji`nٖe($ )f4{XDDm46R#UҒXp#.KPYOǎQnF`^:pv]4K7lq7|Bg6`v&\& |